### Local Development Setup Commands Source: https://www.evlog.dev/frameworks/tanstack-start Commands to clone the Evlog repository, navigate to the TanStack Start example, install dependencies, and run the development server. ```bash git clone https://github.com/hugorcd/evlog.git cd evlog/examples/tanstack-start pnpm install pnpm run dev ``` -------------------------------- ### Run Evlog Fastify Example Locally Source: https://www.evlog.dev/frameworks/fastify Clone the repository, install dependencies, and run the Fastify example. Access the interactive UI at http://localhost:3000. ```bash git clone https://github.com/hugorcd/evlog.git cd evlog pnpm install pnpm run example:fastify ``` -------------------------------- ### Run Evlog Next.js Example Locally Source: https://www.evlog.dev/frameworks/nextjs Clone the Evlog repository, navigate to the Next.js example directory, install dependencies, and run the development server. ```bash git clone https://github.com/hugorcd/evlog.git cd evlog/examples/nextjs pnpm install pnpm run dev ``` -------------------------------- ### Run React Router Example Locally Source: https://www.evlog.dev/frameworks/react-router Clone the repository, install dependencies, and run the example to explore the interactive test UI. Open http://localhost:5173 to view the UI. ```bash git clone https://github.com/hugorcd/evlog.git cd evlog pnpm install pnpm run example:react-router ``` -------------------------------- ### Run Evlog Example Locally Source: https://www.evlog.dev/frameworks/elysia Clone the Evlog repository, install dependencies, and run the Elysia example to explore the interactive test UI locally. ```bash git clone https://github.com/hugorcd/evlog.git cd evlog pnpm install pnpm run example:elysia ``` -------------------------------- ### Run Evlog SvelteKit Example Locally Source: https://www.evlog.dev/frameworks/sveltekit Clone the Evlog repository, install dependencies, and run the SvelteKit example to explore the interactive test UI locally. Access the UI at http://localhost:5173. ```bash git clone https://github.com/hugorcd/evlog.git cd evlog pnpm install pnpm run example:sveltekit ``` -------------------------------- ### Clone and Run Evlog Hono Example Locally Source: https://www.evlog.dev/frameworks/hono Clone the Evlog repository, install dependencies, and run the Hono example to explore the interactive test UI locally. Access the UI at http://localhost:3000. ```bash git clone https://github.com/hugorcd/evlog.git cd evlog pnpm install pnpm run example:hono ``` -------------------------------- ### Running the NestJS Example Locally Source: https://www.evlog.dev/frameworks/nestjs Clone the Evlog repository, install dependencies, and run the NestJS example using pnpm. Access the interactive test UI at http://localhost:3000. ```bash git clone https://github.com/hugorcd/evlog.git cd evlog pnpm install pnpm run example:nestjs ``` -------------------------------- ### Install Evlog with bun Source: https://www.evlog.dev/frameworks/aws-lambda Install the evlog package using bun. ```bash bun add evlog ``` -------------------------------- ### Configure Evlog for Different Environments Source: https://www.evlog.dev/adapters/overview Example environment variables for configuring various Evlog adapters (Axiom, OTLP, HyperDX, PostHog, Sentry, Better Stack, Datadog). These variables allow for zero-config setup. ```dotenv # Axiom (NUXT_AXIOM_* or AXIOM_*) AXIOM_TOKEN=xaat-xxx AXIOM_DATASET=my-logs # OTLP (NUXT_OTLP_* or OTEL_*) OTLP_ENDPOINT=https://otlp.example.com # HyperDX (NUXT_HYPERDX_* or HYPERDX_*) HYPERDX_API_KEY= # PostHog (NUXT_POSTHOG_* or POSTHOG_*) POSTHOG_API_KEY=phc_xxx # Sentry (NUXT_SENTRY_* or SENTRY_*) SENTRY_DSN=https://key@o0.ingest.sentry.io/123 # Better Stack (NUXT_BETTER_STACK_* or BETTER_STACK_*) BETTER_STACK_SOURCE_TOKEN=your-source-token # Datadog (NUXT_DATADOG_* or DATADOG_* or DD_*) DD_API_KEY=your-api-key DD_SITE=datadoghq.eu ``` -------------------------------- ### Install evlog AI assistant skill Source: https://www.evlog.dev/getting-started/installation Install the evlog skill for your AI assistant (e.g., Claude Code, Cursor) to get guided setup and code review assistance. ```bash npx skills add https://www.evlog.dev ``` -------------------------------- ### Migrate Winston to Evlog Source: https://www.evlog.dev/logging/simple-logging This example demonstrates migrating from Winston to Evlog. Evlog's `initLogger` handles configuration, eliminating the need for manual transport and format setup. ```typescript import { createLogger, format, transports } from 'winston' const log = createLogger({ defaultMeta: { service: 'checkout' }, format: format.json(), transports: [new transports.Console()] }) log.info({ event: 'checkout_started' }) log.info({ event: 'cart_loaded', items: 3, total: 9999 }) log.warn({ event: 'inventory_low', sku: 'SKU-42' }) log.error({ event: 'payment_failed', reason: 'card_declined' }) ``` ```typescript import { initLogger, log } from 'evlog' initLogger({ env: { service: 'checkout' } }) log.info({ event: 'checkout_started' }) log.info({ event: 'cart_loaded', items: 3, total: 9999 }) log.warn({ event: 'inventory_low', sku: 'SKU-42' }) log.error({ event: 'payment_failed', reason: 'card_declined' }) ``` -------------------------------- ### Install @evlog/nuxthub with bun Source: https://www.evlog.dev/adapters/self-hosted/nuxthub Install the NuxtHub core and evlog-nuxthub packages using bun. ```bash bun add @nuxthub/core @evlog/nuxthub ``` -------------------------------- ### Install Evlog with yarn Source: https://www.evlog.dev/frameworks/aws-lambda Install the evlog package using yarn. ```bash yarn add evlog ``` -------------------------------- ### Run Evlog Express Example Source: https://www.evlog.dev/frameworks/express Execute the example Express application using the pnpm run command. ```bash pnpm run example:express ``` -------------------------------- ### Initialize AI Logger and Emit Event Source: https://www.evlog.dev/logging/ai-sdk/overview A general example for initializing both a standard logger and an AI logger, followed by emitting an event. This is useful for standalone setups or when explicit logger creation is preferred. ```javascript import { createLogger } from 'evlog' import { createAILogger } from 'evlog/ai' const log = createLogger() const ai = createAILogger(log) // ... log.emit() ``` -------------------------------- ### Install Evlog and Fastify Source: https://www.evlog.dev/frameworks/fastify Install the necessary packages for Evlog and Fastify using your preferred package manager. ```bash pnpm add evlog fastify ``` ```bash bun add evlog fastify ``` ```bash yarn add evlog fastify ``` ```bash npm install evlog fastify ``` -------------------------------- ### Install Evlog with npm Source: https://www.evlog.dev/frameworks/aws-lambda Install the evlog package using npm. ```bash npm install evlog ``` -------------------------------- ### Install @evlog/nuxthub with npm Source: https://www.evlog.dev/adapters/self-hosted/nuxthub Install the NuxtHub core and evlog-nuxthub packages using npm. ```bash npm install @nuxthub/core @evlog/nuxthub ``` -------------------------------- ### Install Evlog with pnpm Source: https://www.evlog.dev/frameworks/aws-lambda Install the evlog package using pnpm. ```bash pnpm add evlog ``` -------------------------------- ### Install @evlog/nuxthub with pnpm Source: https://www.evlog.dev/adapters/self-hosted/nuxthub Install the NuxtHub core and evlog-nuxthub packages using pnpm. ```bash pnpm add @nuxthub/core @evlog/nuxthub ``` -------------------------------- ### Quick Start Source: https://www.evlog.dev/adapters/building-blocks/http Initialize the logger with the HTTP log drain for sending client-side logs. ```APIDOC ## Quick Start app.ts ```typescript import { initLogger, log } from 'evlog' import { createHttpLogDrain } from 'evlog/http' const drain = createHttpLogDrain({ drain: { endpoint: 'https://logs.example.com/v1/ingest' }, }) initLogger({ drain }) log.info({ action: 'page_view', path: location.pathname }) ``` ``` -------------------------------- ### Install AI SDK with bun Source: https://www.evlog.dev/logging/ai-sdk/overview Add the AI SDK as a dependency using bun. ```bash bun add ai ``` -------------------------------- ### Initialize HTTP Log Drain with Default Settings Source: https://www.evlog.dev/adapters/building-blocks/http Quick start example for initializing the HTTP log drain with default batching and retry settings. Use this for basic client-side log transport. ```typescript import { initLogger, log } from 'evlog' import { createHttpLogDrain } from 'evlog/http' const drain = createHttpLogDrain({ drain: { endpoint: 'https://logs.example.com/v1/ingest' }, }) initLogger({ drain }) log.info({ action: 'page_view', path: location.pathname }) ``` -------------------------------- ### Install @evlog/nuxthub with yarn Source: https://www.evlog.dev/adapters/self-hosted/nuxthub Install the NuxtHub core and evlog-nuxthub packages using yarn. ```bash yarn add @nuxthub/core @evlog/nuxthub ``` -------------------------------- ### Install Evlog for Hono Source: https://www.evlog.dev/frameworks/hono Install the necessary Evlog and Hono packages using your preferred package manager. ```bash pnpm add evlog hono @hono/node-server ``` ```bash bun add evlog hono @hono/node-server ``` ```bash yarn add evlog hono @hono/node-server ``` ```bash npm install evlog hono @hono/node-server ``` -------------------------------- ### Install Evlog with Express Source: https://www.evlog.dev/frameworks/express Install the necessary packages for Evlog and Express using your preferred package manager. ```bash pnpm add evlog express ``` ```bash bun add evlog express ``` ```bash yarn add evlog express ``` ```bash npm install evlog express ``` -------------------------------- ### Quick Start: Logger Initialization Source: https://www.evlog.dev/adapters/self-hosted/fs Initialize the logger with the file system drain. ```typescript import { createFsDrain } from 'evlog/fs' initLogger({ drain: createFsDrain() }) ``` -------------------------------- ### Install Evlog and Elysia Source: https://www.evlog.dev/frameworks/elysia Install the necessary packages for Elysia and Evlog using your preferred package manager. ```bash pnpm add evlog elysia ``` ```bash bun add evlog elysia ``` ```bash yarn add evlog elysia ``` ```bash npm install evlog elysia ``` -------------------------------- ### Quick Start: Next.js Integration Source: https://www.evlog.dev/adapters/self-hosted/fs Initialize Evlog with the file system drain in your Next.js application. ```typescript // lib/evlog.ts import { createEvlog } from 'evlog/next' import { createFsDrain } from 'evlog/fs' export const { withEvlog, useLogger, log, createError } = createEvlog({ service: 'my-app', drain: createFsDrain(), }) ``` -------------------------------- ### Install AI SDK with pnpm Source: https://www.evlog.dev/logging/ai-sdk/overview Add the AI SDK as a dependency using pnpm. ```bash pnpm add ai ``` -------------------------------- ### Example Request Size Output Source: https://www.evlog.dev/enrichers/built-in Example of the 'event.requestSize' field structure after being processed by the Request Size enricher. ```json { "requestSize": { "requestBytes": 1234, "responseBytes": 5678 } } ``` -------------------------------- ### Example User Agent Output Source: https://www.evlog.dev/enrichers/built-in Example of the 'event.userAgent' field structure after being processed by the User Agent enricher. ```json { "userAgent": { "raw": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120.0.0.0", "browser": { "name": "Chrome", "version": "120.0.0.0" }, "os": { "name": "macOS", "version": "10.15.7" }, "device": { "type": "desktop" } } } ``` -------------------------------- ### Clone Evlog Repository and Install Dependencies Source: https://www.evlog.dev/frameworks/express Clone the Evlog repository from GitHub and install the necessary project dependencies using pnpm. ```bash git clone https://github.com/hugorcd/evlog.git cd evlog pnpm install ``` -------------------------------- ### Install AI SDK with npm Source: https://www.evlog.dev/logging/ai-sdk/overview Add the AI SDK as a dependency using npm. ```bash npm install ai ``` -------------------------------- ### Install Better Auth Source: https://www.evlog.dev/logging/better-auth/overview Install Better Auth as a direct dependency in your application using your preferred package manager. ```bash pnpm add better-auth ``` ```bash bun add better-auth ``` ```bash yarn add better-auth ``` ```bash npm install better-auth ``` -------------------------------- ### Quick Start: Standalone Integration Source: https://www.evlog.dev/adapters/self-hosted/fs Configure Evlog with the file system drain for standalone applications. ```typescript import { createFsDrain } from 'evlog/fs' EvlogModule.forRoot({ drain: createFsDrain() }) ``` -------------------------------- ### Install evlog for Nitro Source: https://www.evlog.dev/frameworks/nitro Choose the package manager that suits your project to install the evlog package. ```bash pnpm add evlog ``` ```bash bun add evlog ``` ```bash yarn add evlog ``` ```bash npm install evlog ``` -------------------------------- ### Install AI SDK with yarn Source: https://www.evlog.dev/logging/ai-sdk/overview Add the AI SDK as a dependency using yarn. ```bash yarn add ai ``` -------------------------------- ### Example Log Event Structure Source: https://www.evlog.dev/adapters/overview This is an example of a typical log event structure that evlog can process and send to adapters. ```json { level: "info", method: "POST", path: "/checkout", duration: 234, user: {...}, cart: {...} } ``` -------------------------------- ### Install Agent Skill CLI Source: https://www.evlog.dev/getting-started/agent-skills Manually install the evlog agent skill using the skills CLI. Compatible agents can discover and use skills automatically. ```bash npx skills add https://www.evlog.dev ``` -------------------------------- ### Install Evlog for NestJS Source: https://www.evlog.dev/frameworks/nestjs Install the necessary Evlog packages along with NestJS core and platform dependencies using your preferred package manager. ```bash pnpm add evlog @nestjs/common @nestjs/core @nestjs/platform-express ``` ```bash bun add evlog @nestjs/common @nestjs/core @nestjs/platform-express ``` ```bash yarn add evlog @nestjs/common @nestjs/core @nestjs/platform-express ``` ```bash npm install evlog @nestjs/common @nestjs/core @nestjs/platform-express ``` -------------------------------- ### Install Evlog for React Router Source: https://www.evlog.dev/frameworks/react-router Install the necessary Evlog packages for React Router integration using your preferred package manager. ```bash pnpm add evlog react-router @react-router/node @react-router/serve ``` ```bash bun add evlog react-router @react-router/node @react-router/serve ``` ```bash yarn add evlog react-router @react-router/node @react-router/serve ``` ```bash npm install evlog react-router @react-router/node @react-router/serve ``` -------------------------------- ### Example Wide Event Output Source: https://www.evlog.dev/frameworks/tanstack-start This is an example of the terminal output for a wide event, showing the request method, path, status, duration, and contextual fields set via the logger. ```text 14:58:15 INFO [my-app] GET /api/hello 200 in 52ms ├─ cache: hit=true ttl=3600 ├─ action: fetch_profile ├─ user: id=user_123 plan=pro └─ requestId: 4a8ff3a8-... ``` -------------------------------- ### AI SDK Wide Event Example Source: https://www.evlog.dev/logging/ai-sdk/usage This is an example of a wide event generated after a 3-step agent run, showcasing accumulated AI call details, model information, token usage, tool calls, and timing. ```json { "ai": { "calls": 3, "steps": 3, "model": "claude-sonnet-4.6", "provider": "anthropic", "inputTokens": 4500, "outputTokens": 1200, "totalTokens": 5700, "finishReason": "stop", "toolCalls": [ { "name": "searchWeb", "input": { "query": "TypeScript 6.0 features" } }, { "name": "queryDatabase", "input": { "sql": "SELECT * FROM docs WHERE topic = 'typescript'" } }, { "name": "searchWeb", "input": { "query": "TypeScript 6.0 release date" } } ], "responseId": "msg_01XFDUDYJgAACzvnptvVoYEL", "stepsUsage": [ { "model": "claude-sonnet-4.6", "inputTokens": 1200, "outputTokens": 300, "toolCalls": ["searchWeb"] }, { "model": "claude-sonnet-4.6", "inputTokens": 1500, "outputTokens": 400, "toolCalls": ["queryDatabase", "searchWeb"] }, { "model": "claude-sonnet-4.6", "inputTokens": 1800, "outputTokens": 500 } ], "msToFirstChunk": 312, "msToFinish": 8200, "tokensPerSecond": 146 } } ``` -------------------------------- ### Migrate Console.log to Evlog Source: https://www.evlog.dev/logging/simple-logging This example illustrates replacing standard `console.log` calls with Evlog. Evlog provides structured logging capabilities out-of-the-box. ```typescript console.log('[checkout] Starting checkout') console.log('[checkout] cart loaded', { items: 3, total: 9999 }) console.warn('[checkout] inventory low', { sku: 'SKU-42' }) console.error('[checkout] payment failed', { reason: 'card_declined' }) ``` ```typescript import { initLogger, log } from 'evlog' initLogger({ env: { service: 'checkout' } }) log.info({ event: 'checkout_started' }) log.info({ event: 'cart_loaded', items: 3, total: 9999 }) log.warn({ event: 'inventory_low', sku: 'SKU-42' }) log.error({ event: 'payment_failed', reason: 'card_declined' }) ``` -------------------------------- ### Quick Start: Express Integration Source: https://www.evlog.dev/adapters/self-hosted/fs Add the Evlog middleware with the file system drain to your Express application. ```typescript import { createFsDrain } from 'evlog/fs' app.use(evlog({ drain: createFsDrain() })) ``` -------------------------------- ### Install File System Drain Source: https://www.evlog.dev/adapters/self-hosted/fs Import the createFsDrain function from the evlog/fs module to use the file system adapter. ```typescript import { createFsDrain } from 'evlog/fs' ``` -------------------------------- ### Define custom framework integration Source: https://www.evlog.dev/frameworks/custom-integration This example demonstrates how to define a custom evlog integration for a framework using the `defineFrameworkIntegration` function. It includes request extraction, logger attachment, and middleware setup. ```typescript import type { IncomingMessage, ServerResponse } from 'node:http' import { createLoggerStorage, defineFrameworkIntegration, type BaseEvlogOptions, } from 'evlog/toolkit' import type { RequestLogger } from 'evlog' export type MyFrameworkEvlogOptions = BaseEvlogOptions const { storage, useLogger } = createLoggerStorage( 'middleware context. Make sure evlog middleware is registered before your routes.', ) export { useLogger } const integration = defineFrameworkIntegration({ name: 'my-framework', extractRequest: (req) => ({ method: req.method || 'GET', path: req.url || '/', headers: req.headers, requestId: typeof req.headers['x-request-id'] === 'string' ? req.headers['x-request-id'] : undefined, }), attachLogger: (req, logger) => { (req as IncomingMessage & { log: RequestLogger }).log = logger }, storage, }) export function evlog(options: MyFrameworkEvlogOptions = {}) { return async (req: IncomingMessage, res: ServerResponse, next: () => Promise) => { const { skipped, finish, runWith } = integration.start(req, options) if (skipped) { await next() return } try { await runWith(() => next()) await finish({ status: res.statusCode }) } catch (error) { await finish({ error: error as Error }) throw error } } } ``` -------------------------------- ### Configurable Drain Pipeline Source: https://www.evlog.dev/adapters/building-blocks/pipeline Configures the drain pipeline with custom settings for batching, retries, buffer size, and a callback for dropped events. The resulting drain can then be wired into your framework as shown in the Quick Start examples. ```typescript import type { DrainContext } from 'evlog' import { createDrainPipeline } from 'evlog/pipeline' import { createAxiomDrain } from 'evlog/axiom' const pipeline = createDrainPipeline({ batch: { size: 50, intervalMs: 5000, }, retry: { maxAttempts: 3, backoff: 'exponential', initialDelayMs: 1000, maxDelayMs: 30000, }, maxBufferSize: 1000, onDropped: (events, error) => { console.error(`[evlog] Dropped ${events.length} events:`, error?.message) }, }) export const drain = pipeline(createAxiomDrain()) // Then wire `drain` to your framework — see Quick Start above. ``` -------------------------------- ### Evlog Client Provider Setup Source: https://www.evlog.dev/frameworks/nextjs Wrap your root layout with `EvlogProvider` to enable client-side logging and transport. Configure the service name and transport options. ```typescript import { EvlogProvider } from 'evlog/next/client' export default function Layout({ children }: { children: React.ReactNode }) { return ( {children} ) } ``` -------------------------------- ### Example Tail Sampling Configuration Source: https://www.evlog.dev/core-concepts/sampling Illustrates a sampling configuration with both rates for head sampling and conditions for tail sampling. Logs are kept if they meet any tail condition or pass head sampling. ```javascript sampling: { rates: { info: 10 }, keep: [ { status: 400 }, { duration: 1000 }, ], } ``` -------------------------------- ### Run All Benchmarks Source: https://www.evlog.dev/core-concepts/performance Execute all available benchmarks for the evlog package. Ensure you are in the correct directory. ```bash cd packages/evlog pnpm run bench ``` -------------------------------- ### Example Trace Context Output Source: https://www.evlog.dev/enrichers/built-in Example of the 'event.traceContext', 'event.traceId', and 'event.spanId' fields after being processed by the Trace Context enricher. ```json { "traceContext": { "traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", "traceId": "4bf92f3577b34da6a3ce929d0e0e4736", "spanId": "00f067aa0ba902b7" }, "traceId": "4bf92f3577b34da6a3ce929d0e0e4736", "spanId": "00f067aa0ba902b7" } ``` -------------------------------- ### Initialize Evlog Logger for Scripts Source: https://www.evlog.dev/ Set up Evlog for standalone Node.js scripts. This example shows how to initialize the logger globally and create a task-specific logger instance. ```typescript import { initLogger, createLogger } from 'evlog' initLogger({ env: { service: 'migrate' } }) const log = createLogger({ task: 'user-migration' }) const users = await db.query('SELECT * FROM legacy_users') log.set({ found: users.length }) for (const user of users) { await newDb.upsert({ id: user.id, email: user.email, plan: user.plan }) } log.set({ migrated: users.length, status: 'complete' }) log.emit() ``` -------------------------------- ### Evlog Community Package Structure Source: https://www.evlog.dev/adapters/building-blocks/toolkit Recommended directory structure for building a community package on top of Evlog. Ensure 'evlog' is a peerDependency. ```bash my-evlog-pkg/ ├─ src/ │ ├─ drain.ts # createMyDrain via defineHttpDrain │ ├─ enricher.ts # createMyEnricher via defineEnricher │ └─ index.ts # re-exports ├─ test/ # vitest, mock fetch ├─ package.json # peerDependency: "evlog" └─ README.md ``` -------------------------------- ### Example Wide Event with Plugin Fields Source: https://www.evlog.dev/logging/better-auth/identify-user This is an example of a wide event that includes custom fields captured via the `extend` option, such as 'organization' and 'role'. ```json { "userId": "QBX9tPjJQExWawAbNll75", "user": { "id": "QBX9tPjJQExWawAbNll75", "name": "Hugo Richard" }, "organization": { "id": "org_42", "name": "Acme" }, "role": "admin" } ``` -------------------------------- ### Structured Error Response Example Source: https://www.evlog.dev/getting-started/introduction Example of the JSON output for a structured error created with Evlog, including status code, message, and detailed data. ```json { "statusCode": 402, "message": "Payment failed", "data": { "why": "Card declined by issuer (insufficient funds)", "fix": "Try a different payment method or contact your bank", "link": "https://docs.example.com/payments/declined" } } ``` -------------------------------- ### Run Comparison Benchmarks Source: https://www.evlog.dev/core-concepts/performance Execute benchmarks that compare evlog against alternative libraries. This command focuses on specific comparison tests. ```bash pnpm exec vitest bench bench/comparison/ ``` -------------------------------- ### Example Audit Log Payload Source: https://www.evlog.dev/logging/audit/overview This is an example of a structured audit log event as it might appear in your logs. It includes service context and detailed audit information. ```json { "level": "info", "service": "billing-api", "method": "POST", "path": "/api/invoices/inv_889/refund", "status": 200, "duration": "84ms", "requestId": "a566ef91-7765-4f59-b6f0-b9f40ce71599", "audit": { "action": "invoice.refund", "actor": { "type": "user", "id": "usr_42", "email": "demo@example.com" }, "target": { "type": "invoice", "id": "inv_889" }, "outcome": "success", "reason": "Customer requested refund", "version": 1, "idempotencyKey": "ak_8f3c4b2a1e5d6f7c", "context": { "requestId": "a566ef91-7765-4f59-b6f0-b9f40ce71599", "ip": "203.0.113.7", "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36" } } } ``` -------------------------------- ### Migrate consola to evlog Source: https://www.evlog.dev/getting-started/vs-other-loggers This example shows how to migrate from consola to evlog. It translates consola's tagged logging and error reporting to evlog's unified event model. ```javascript import { consola } from 'consola' const log = consola.withTag('checkout') log.info('Starting checkout flow') try { const cart = await getCart(userId) log.info('cart loaded', { items: cart.items.length, total: cart.total }) const charge = await stripe.charge(cart.total) log.info('charge ok', { chargeId: charge.id }) if (!charge.success) { throw new Error(`Payment failed: ${charge.decline_reason}`) } } catch (err) { log.error('checkout failed', err) throw err } ``` ```javascript import { initLogger, createLogger, createError } from 'evlog' initLogger({ env: { service: 'checkout' } }) const log = createLogger({ flow: 'checkout' }) try { const cart = await getCart(userId) log.set({ cart: { items: cart.items.length, total: cart.total } }) const charge = await stripe.charge(cart.total) log.set({ stripe: { chargeId: charge.id } }) if (!charge.success) { throw createError({ message: 'Payment failed', status: 402, why: charge.decline_reason, fix: 'Try a different payment method', }) } } catch (err) { log.error(err as Error) throw err } finally { log.emit() } ``` -------------------------------- ### Next.js Evlog Setup Source: https://www.evlog.dev/enrichers/built-in Configures Evlog for a Next.js application, including the initialization of built-in enrichers. This setup provides a centralized way to manage enrichers for the entire application. ```typescript // lib/evlog.ts import { createEvlog } from 'evlog/next' import { createUserAgentEnricher, createGeoEnricher, createRequestSizeEnricher, createTraceContextEnricher, } from 'evlog/enrichers' const enrichers = [ createUserAgentEnricher(), createGeoEnricher(), createRequestSizeEnricher(), createTraceContextEnricher(), ] export const { withEvlog, useLogger, log, createError } = createEvlog({ service: 'my-app', enrich: (ctx) => { for (const enricher of enrichers) enricher(ctx) }, }) ``` -------------------------------- ### Evlog Wide Event Lifecycle Example Source: https://www.evlog.dev/core-concepts/performance Demonstrates how Evlog accumulates context into a single event using `log.set()` before emitting it with `log.emit()`. This pattern is efficient for real-world API requests. ```javascript const log = createLogger({ method: 'POST', path: '/api/checkout', requestId: 'req_abc' }) log.set({ user: { id: 'usr_123', plan: 'pro' } }) log.set({ cart: { items: 3, total: 9999 } }) log.set({ payment: { method: 'card', last4: '4242' } }) log.emit({ status: 200 }) ``` -------------------------------- ### Production Sampling Configuration with Next.js Source: https://www.evlog.dev/core-concepts/sampling Set up production-ready sampling rates and keep conditions for Next.js applications using `createEvlog`. ```typescript import { createEvlog } from 'evlog/next' export const { withEvlog, useLogger } = createEvlog({ service: 'my-app', sampling: { rates: { info: 10, warn: 50, debug: 0, error: 100, }, keep: [ { status: 400 }, { duration: 1000 }, { path: '/api/payments/**' }, { path: '/api/auth/**' }, ], }, }) ``` -------------------------------- ### Production Sampling Configuration with Hono/Express/Fastify Source: https://www.evlog.dev/core-concepts/sampling Initialize Evlog with production sampling configurations for frameworks like Hono, Express, or Fastify. ```typescript import { initLogger } from 'evlog' initLogger({ env: { service: 'my-app' }, sampling: { rates: { info: 10, warn: 50, debug: 0, error: 100, }, keep: [ { status: 400 }, { duration: 1000 }, { path: '/api/payments/**' }, { path: '/api/auth/**' }, ], }, }) ``` -------------------------------- ### Basic streamText usage Source: https://www.evlog.dev/logging/ai-sdk/overview Example of using `streamText` from the AI SDK without Evlog integration. ```typescript export default defineEventHandler(async (event) => { const result = streamText({ model: 'anthropic/claude-sonnet-4.6', messages, }) return result.toTextStreamResponse() }) ``` -------------------------------- ### Quick Reference Source: https://www.evlog.dev/adapters/building-blocks/toolkit This section provides a quick reference of all the available functions and types exported by the `evlog/toolkit` package. ```APIDOC ## Quick Reference ```typescript import { // Plugins — the unified extension contract definePlugin, drainPlugin, enricherPlugin, composePlugins, // Drains defineDrain, defineHttpDrain, composeDrains, // Enrichers defineEnricher, composeEnrichers, // Tail sampling composeKeep, // Configuration defineEvlog, toLoggerConfig, toMiddlewareOptions, resolveAdapterConfig, type ConfigField, // Framework integrations defineFrameworkIntegration, createMiddlewareLogger, createLoggerStorage, type BaseEvlogOptions, // HTTP transport httpPost, // Helpers getHeader, normalizeNumber, extractSafeHeaders, extractSafeNodeHeaders, mergeEventField, toTypedAttributeValue, toOtlpAttributeValue, OTEL_SEVERITY_NUMBER, OTEL_SEVERITY_TEXT, } from 'evlog/toolkit' ``` ``` -------------------------------- ### Create Evlog Instrumentation Exports Source: https://www.evlog.dev/frameworks/nextjs Set up instrumentation exports for Next.js `instrumentation.ts` file, including a file system drain and output capture. ```typescript import { createInstrumentation } from 'evlog/next/instrumentation' import { createFsDrain } from 'evlog/fs' export const { register, onRequestError } = createInstrumentation({ service: 'my-app', drain: createFsDrain(), captureOutput: true, }) ``` -------------------------------- ### Quick Start: Elysia Integration Source: https://www.evlog.dev/adapters/self-hosted/fs Register Evlog with the file system drain in your Elysia application. ```typescript import { createFsDrain } from 'evlog/fs' await app.register(evlog, { drain: createFsDrain() }) ``` -------------------------------- ### Pino Log Lines Example Source: https://www.evlog.dev/core-concepts/performance Illustrates how traditional loggers like pino emit multiple log lines for a single request, each requiring separate serialization and processing. This is contrasted with Evlog's single-event approach. ```javascript const child = pinoLogger.child({ method: 'POST', path: '/api/checkout', requestId: 'req_abc' }) child.info({ user: { id: 'usr_123', plan: 'pro' } }, 'user context') child.info({ cart: { items: 3, total: 9999 } }, 'cart context') child.info({ payment: { method: 'card', last4: '4242' } }, 'payment context') child.info({ status: 200 }, 'request complete') ``` -------------------------------- ### Axiom Adapter Missing Configuration Error Source: https://www.evlog.dev/adapters/cloud/axiom Troubleshooting message indicating missing AXIOM_DATASET or AXIOM_TOKEN environment variables. ```console [evlog/axiom] Missing dataset or token. Set AXIOM_DATASET and AXIOM_TOKEN ``` -------------------------------- ### Create Client Error with Status Code 404 Source: https://www.evlog.dev/logging/structured-errors Example of throwing a 404 error when a resource is not found. ```typescript // Resource not found throw createError({ message: 'Order not found', status: 404, }) ``` -------------------------------- ### Direct API Usage Source: https://www.evlog.dev/adapters/cloud/hyperdx Examples of using the lower-level functions `sendToHyperDX` and `sendBatchToHyperDX` for advanced use cases. ```APIDOC ## Direct API Usage For advanced use cases, you can use the lower-level functions: server/utils/hyperdx.ts ```javascript import { sendToHyperDX, sendBatchToHyperDX } from 'evlog/hyperdx' // Send a single event await sendToHyperDX(event, { apiKey: process.env.HYPERDX_API_KEY!, }) // Send multiple events in one request await sendBatchToHyperDX(events, { apiKey: process.env.HYPERDX_API_KEY!, endpoint: 'https://in-otel.hyperdx.io', }) ``` ``` -------------------------------- ### Initialize evlog Logger Source: https://www.evlog.dev/logging/simple-logging Initialize the logger once at startup for standalone projects. `env.service` defaults to 'app' if not specified. ```typescript import { initLogger, log } from 'evlog' initLogger({ env: { service: 'my-app' }, }) log.info('app', 'Server started') ``` -------------------------------- ### Node.js (Hono/Express/Fastify) Evlog Initialization Source: https://www.evlog.dev/core-concepts/redaction Initialize Evlog for generic Node.js environments like Hono, Express, or Fastify. This includes setting the service name and sampling configuration for production redaction. ```typescript import { initLogger } from 'evlog' initLogger({ env: { service: 'my-app' }, sampling: { rates: { info: 10, debug: 0 }, keep: [{ status: 400 }, { duration: 1000 }], }, }) ``` -------------------------------- ### Svelte: Setup Auth Identity Subscription Source: https://www.evlog.dev/logging/better-auth/client-sync Set up client identity synchronization in Svelte by subscribing to the auth session. Run this function once when the app boots. ```typescript import { setIdentity, clearIdentity } from 'evlog/http' import { authClient } from '$lib/auth-client' export function setupAuthIdentity() { const session = authClient.useSession() session.subscribe(({ data }) => { if (data?.user) { setIdentity({ userId: data.user.id, userName: data.user.name }) } else { clearIdentity() } }) } ``` -------------------------------- ### Initialize Evlog with Global Options Source: https://www.evlog.dev/core-concepts/configuration Configure global logger settings including enabling logging, environment context, pretty printing, silent mode, stringification, minimum log level, sampling, and custom drains. Call `initLogger()` once at application startup. ```typescript import { initLogger } from 'evlog' import { createAxiomDrain } from 'evlog/axiom' initLogger({ enabled: true, env: { service: 'my-api', environment: 'production' }, pretty: false, silent: false, stringify: true, minLevel: 'info', sampling: { rates: { info: 10 }, keep: [{ status: 400 }] }, drain: createAxiomDrain(), }) ``` -------------------------------- ### Create Error with Actionable Fix and Link Source: https://www.evlog.dev/logging/structured-errors Example of an error with a specific `why` and an actionable `fix`, along with a link for more information. ```typescript // Actionable fix throw createError({ message: 'Upload failed', status: 413, why: 'File exceeds maximum size (10MB)', fix: 'Reduce the file size or compress the image before uploading', link: '/docs/upload-limits', }) ``` -------------------------------- ### Run Bundle Size Script Source: https://www.evlog.dev/core-concepts/performance Execute a script to measure the bundle size of evlog entry points. This helps track performance regressions related to code size. ```bash pnpm exec tsx bench/scripts/size.ts ``` -------------------------------- ### Unhelpful Error Example Source: https://www.evlog.dev/logging/structured-errors Demonstrates a common unhelpful error thrown in an API route, lacking context for debugging. ```javascript // Unhelpful error throw new Error('Payment failed') ```