Cloudflare - v1.3.0
    Preparing search index...

    Function logToAnalytics

    • Wraps every request and, when it finishes, emits the two records a request should leave behind — deliberately in two different places:

      • One log line to Workers Logs, via Logger, under request.completed or request.failed. Level follows the outcome: 5xx and thrown errors log at error, 4xx at warn, everything else at info.
      • One metric to Analytics Engine, via AnalyticsService: duration plus a unit count, grouped by path with method, status, colo, and country as dimensions — the shape rate, latency, and error-rate queries need.

      Analytics Engine samples at volume, which is right for aggregates and wrong for individual lines, so nothing that must be read back verbatim goes there.

      Parameters

      • c: Context<any, string, {}>

        The Hono request context.

      • next: Next

        Passes control to the next middleware.

      Returns Promise<void | Response>

      Nothing — the two records are written after next() settles.

      Register this before any middleware that can short-circuit — Hono runs middleware in registration order, so a logger behind the API-key check would never see a 401.

      requestId, method, path, ip, colo, country, status and durationMs are offered as context, and LOG_FIELDS decides which of them are ingested. The default in cloudflareDefaults keeps the first four and the status, because Cloudflare already records the rest on its own $metadata envelope and a Worker gains nothing by paying for a second copy of a column the dashboard renders anyway.

      That default is right only while the lines stay inside Workers Logs. A deployment shipping through Logpush, exporting OTel, or writing to a file should add service — a record that only means something inside one vendor's console is not a record — and one chasing a regional fault should add colo and country.

      What is never restated is anything this middleware would have to compute twice, or that says nothing about the request: the CPU and wall time, the outcome, the script version.

      The request-scoped logger and its request id are stored on the context as logger and requestId, so a handler can log with the same correlation:

      ctx.get('logger').warn('authentication.failed', { reason })
      

      That id survives a Service Binding hop only if the caller sends it on. See RequestCorrelation.

      Bayu Dwiyan Satria

      1.0.0

      1.0.0