ForgeOps-Tracker

 view release on metacpan or  search on metacpan

README.md  view on Meta::CPAN


```perl
ForgeOps::Tracker::init(
    dsn              => '...',
    propagate_traces => 0, # never send traceparent (default 1)

    # Default undef: every host. A string matches that host and its subdomains on a dot boundary
    # ("internal.example" matches "orders.internal.example", not "notinternal.example"); a qr//
    # regular expression is matched against the host.
    trace_propagation_targets => ['internal.example', qr/\A10\.0\./],
);
```

### Where an error happened

An error reported during a request (from `Integrations::PSGI`/`Integrations::Dancer2`, or your own
`report` call from inside a route) carries up to three extra fields:

- `trace_id`: the request's W3C trace id, which ForgeOps uses to link this error to errors that
  other services reported for the same trace.
- `transaction_name`: the same name performance monitoring and traces use, `"GET /users/:id"`.
- `endpoint`: the HTTP method and the route as declared, `"GET /users/:id"`. Never the literal
  path, so an id or a token in the URL never ends up here.

`Dancer2Performance` fills in all three as soon as Dancer2 has matched the route, before the route
itself runs. `PSGIPerformance` fills in only `trace_id`, since plain PSGI has no route pattern (a
raw path is neither a transaction name nor an endpoint); if your PSGI app has its own router, name
the request yourself with `ForgeOps::Tracker::set_request_route('GET /users/:id', 'GET /users/:id')`.
They need one of the performance integrations enabled, are left out entirely outside a request, and
are never PII-scrubbed: they're structured fields, not free text. An error that escapes the request
keeps them (and the affected user and breadcrumb trail) even though `Integrations::PSGI` sits outside
`PSGIPerformance` and reports it after the request's own state has been cleared.

## Custom metrics and infrastructure monitoring

Two explicit calls (nothing is automatic, so there is no `track_metrics` option): a business event you
name yourself, and a reading from one of your own hosts.

```perl
ForgeOps::Tracker::capture_metric('signup');          # value defaults to 1: a bare counter
ForgeOps::Tracker::capture_metric('payment', 49);     # a real magnitude; it may be negative (a refund)

ForgeOps::Tracker::capture_infrastructure_metric('cpu', 0.42);                    # hostname defaults to server_name
ForgeOps::Tracker::capture_infrastructure_metric('disk', 0.81, hostname => 'db-1');
ForgeOps::Tracker::flush_metrics();                                                # optional: send right now
```

Each capture is buffered and flushed as one batch every `metric_flush_interval` /
`infrastructure_metric_flush_interval` seconds (60 by default) on a background thread, and once more
from an `END` block when the program ends normally, so a short-lived cron script that captures a few
readings and falls off the end needs nothing more (a test runs exactly that in a child `perl`); call
`flush_metrics()` if it might exit another way (`POSIX::_exit`). Every entry is stored as it was
captured (a signup is a row, not a running total), so a count or sum you compute later is exact. Both
are a no-op when the client isn't enabled for the environment.

A delivery that fails for now (a network error, a timeout, a 5xx, a 408 or a 429) keeps every entry
for the next flush, and an entry captured while a delivery is in flight is kept too (a test pins this
with a gated delivery on a second thread). A batch the server rejects (any other 4xx, such as the 403
a plan without the feature answers) is dropped rather than sent again, and so is one that has failed
5 flushes in a row. The buffer holds at most 1000 entries per kind and drops further ones until a
flush lets go of them. A NaN, infinite or non-numeric value is dropped at capture. Requires a ForgeOps
plan that includes custom metrics / infrastructure monitoring.

## What changed

ForgeOps can show what changed in your system next to the errors and slowdowns that followed it.
Two ways in:

**Record a change yourself** when something changes that no deploy captures, like a feature flag
flipped, a config value edited, or a migration run by hand:

```perl
ForgeOps::Tracker::record_change(
    kind    => 'feature_flag',   # feature_flag, config, migration, dependency, infrastructure, or other
    title   => 'Enabled new_checkout for 10% of users',
    details => { flag => 'new_checkout', rollout_percent => 10 },
    actor   => 'ops@example.com',
    url     => 'https://flags.example.com/new_checkout',
);
```

`kind` and `title` are required; `details` (a hashref), `environment` (defaults to the configured
one), `service`, `actor`, `url`, `id` (an idempotency key, so sending the same change twice records
it once), and `occurred_at` (an ISO 8601 string or epoch seconds, defaulting to now) are optional.
An unknown `kind` is sent as `other`. It's queued for the same kind of background thread as error
events, so it never slows down the caller, never dies, and does nothing when the client isn't
enabled for the environment.

**Changes between deploys are detected for you.** Once per process, `init()` queues a snapshot of
what the process is running for that background thread: the Perl version. ForgeOps compares it with
the previous boot's and records whatever changed. Module versions aren't included: Perl has no
single reliable record of which versions an app runs, and the snapshot leaves out anything it would
have to guess at.

```perl
ForgeOps::Tracker::init(
    dsn                 => 'https://<api_key>@getforgeops.net/api/v1/events',
    detect_changes      => 1,   # default; 0 sends no startup snapshot
    track_env_var_names => 0,   # default; 1 also sends environment variable names
);
```

With `track_env_var_names` on, the snapshot lists the names of your environment variables (never
their values), so an added or removed variable shows up as a change. Names that differ from host to
host, like `HOSTNAME`, `PATH`, `PORT`, `LC_*`, and Kubernetes service variables, are left out, as
are the client's own `FORGE_OPS_*` settings.

Requires a ForgeOps plan that includes change tracking; on a plan that doesn't, both are accepted but not recorded,
and the response says why.

## Database errors

Perl has no exception type that carries the statement, but DBI puts it in the error text as `[for Statement "SELECT ..."]` when the handle has `ShowErrorStatement` turned on (DBIx::Class turns it on for you), and SQLite's own errors end `while compil...

To also send the SQL statement itself, opt in. Every string and number is replaced by `?` before it
leaves your process (`WHERE email = 'a@b.co' AND id = 42` is sent as `WHERE email = ? AND id = ?`),
and ForgeOps masks it again on arrival:

```perl
my $dbh = DBI->connect($dsn, $user, $pass, { RaiseError => 1, ShowErrorStatement => 1 });



( run in 2.111 seconds using v1.01-cache-2.11-cpan-60884a8df76 )