### Setup using install() function Source: https://logtape.org/manual/adaptors Use the install function to programmatically route logs to log4js. ```typescript import log4js from "log4js"; import { install } from "@logtape/adaptor-log4js"; log4js.configure({ appenders: { out: { type: "stdout" } }, categories: { default: { appenders: ["out"], level: "info" } } }); // With default options (category-based loggers) install(log4js); // Now any LogTape-enabled library will log through log4js import { getLogger } from "@logtape/logtape"; const logger = getLogger("my-app"); logger.info("This will be logged through log4js"); ``` -------------------------------- ### Quick setup with auto-installer Source: https://logtape.org/manual/adaptors Integrate LogTape with log4js by importing the install module. ```typescript import log4js from "log4js"; // Configure log4js first log4js.configure({ appenders: { out: { type: "stdout" } }, categories: { default: { appenders: ["out"], level: "info" } } }); // Simply import to automatically set up the adapter import "@logtape/adaptor-log4js/install"; // Now all LogTape logs will be routed to log4js import { getLogger } from "@logtape/logtape"; const logger = getLogger("my-app"); logger.info("This will be logged through log4js"); ``` -------------------------------- ### Install @logtape/graphql-yoga Source: https://logtape.org/manual/integrations Installation commands for various JavaScript runtimes. ```Deno deno add jsr:@logtape/graphql-yoga ``` ```npm npm add @logtape/graphql-yoga ``` ```pnpm pnpm add @logtape/graphql-yoga ``` ```Yarn yarn add @logtape/graphql-yoga ``` ```Bun bun add @logtape/graphql-yoga ``` -------------------------------- ### Complete Configuration Examples Source: https://logtape.org/manual/config Full configuration examples provided in both JSON and YAML formats. ```json { "sinks": { "console": { "type": "#console()", "formatter": { "type": "#ansiColor()", "timestamp": "date-time-tz" } }, "file": { "type": "@logtape/file#getFileSink()", "path": "/var/log/app.log", "formatter": "#jsonLines()" } }, "loggers": [ { "category": ["myapp"], "sinks": ["console", "file"], "lowestLevel": "info" } ] } ``` ```yaml sinks: console: type: "#console()" formatter: type: "#ansiColor()" timestamp: date-time-tz file: type: "@logtape/file#getFileSink()" path: /var/log/app.log formatter: "#jsonLines()" loggers: - category: [myapp] sinks: [console, file] lowestLevel: info ``` -------------------------------- ### Install LogTape Source: https://logtape.org/manual/install Standard installation commands for different package managers and runtimes. ```sh deno add jsr:@logtape/logtape ``` ```sh npm add @logtape/logtape ``` ```sh pnpm add @logtape/logtape ``` ```sh yarn add @logtape/logtape ``` ```sh bun add @logtape/logtape ``` -------------------------------- ### Install @logtape/file package Source: https://logtape.org/sinks/file Installation commands for various JavaScript runtimes. ```sh deno add jsr:@logtape/file ``` ```sh npm add @logtape/file ``` ```sh pnpm add @logtape/file ``` ```sh yarn add @logtape/file ``` ```sh bun add @logtape/file ``` -------------------------------- ### Install @logtape/express Source: https://logtape.org/manual/integrations Installation commands for various package managers. ```Deno deno add jsr:@logtape/express ``` ```npm npm add @logtape/express ``` ```pnpm pnpm add @logtape/express ``` ```Yarn yarn add @logtape/express ``` ```Bun bun add @logtape/express ``` -------------------------------- ### Configure Shared Setup File Source: https://logtape.org/manual/testing Configure LogTape in a shared setup file and register it in the Vitest configuration. ```typescript import { defineConfig } from "vitest/config"; export default defineConfig({ test: { setupFiles: ["./test/setup-logtape.ts"], }, }); ``` ```typescript import { AsyncLocalStorage } from "node:async_hooks"; import { configure } from "@logtape/logtape"; await configure({ contextLocalStorage: new AsyncLocalStorage(), sinks: {}, loggers: [ { category: ["logtape", "meta"], sinks: [] }, ], }); ``` -------------------------------- ### Incorrect configuration example Source: https://logtape.org/lint/require-meta-sink This example demonstrates a configuration missing the required meta logger entry. ```typescript import { configure } from "@logtape/logtape"; await configure({ sinks: { console: consoleSink }, loggers: [ // No meta logger entry → diagnostics fall back to the built-in console sink { category: ["my-app"], sinks: ["console"] }, ], }); ``` -------------------------------- ### Correct configuration example Source: https://logtape.org/lint/require-meta-sink This example shows the correct way to include a meta logger entry using either ['logtape'] or ['logtape', 'meta'] categories. ```typescript import { configure } from "@logtape/logtape"; await configure({ sinks: { console: consoleSink }, loggers: [ { category: ["my-app"], sinks: ["console"] }, // Either array form is accepted: { category: ["logtape"], sinks: ["console"] }, // or: { category: ["logtape", "meta"], sinks: ["console"] }, ], }); ``` -------------------------------- ### Install Pino adaptor automatically Source: https://logtape.org/manual/adaptors Use the install() function to automatically route all LogTape logs to a Pino logger. ```typescript import { pino } from "pino"; import { install } from "@logtape/adaptor-pino"; const pinoLogger = pino({ level: "info", transport: { target: "pino-pretty" } }); // Install with custom logger and options install(pinoLogger, { category: { position: "start", decorator: "[]", separator: "." } }); // Now any LogTape-enabled library will log through Pino import { getLogger } from "@logtape/logtape"; const logger = getLogger("my-app"); logger.info("This will be logged through Pino"); ``` -------------------------------- ### Install @logtape/testing-vitest Source: https://logtape.org/manual/testing Commands to install the testing package using various package managers. ```npm npm add @logtape/testing-vitest ``` ```pnpm pnpm add @logtape/testing-vitest ``` ```Yarn yarn add @logtape/testing-vitest ``` ```Bun bun add @logtape/testing-vitest ``` ```Deno deno add jsr:@logtape/testing-vitest npm:vitest ``` -------------------------------- ### Shared Preload Module Setup Source: https://logtape.org/manual/testing Configure LogTape once in a shared module and preload it during test execution to avoid per-file setup. ```javascript import { AsyncLocalStorage } from "node:async_hooks"; import { configure } from "@logtape/logtape"; await configure({ contextLocalStorage: new AsyncLocalStorage(), sinks: {}, loggers: [ { category: ["logtape", "meta"], sinks: [] }, ], }); ``` ```bash node --import ./test/setup-logtape.mjs --test ``` ```typescript import { test } from "@logtape/testing-node"; import { getLogger } from "@logtape/logtape"; test("case", async () => { getLogger(["my-lib"]).info("Fixture state: {state}.", { state: "ready", }); // Run assertions. The info log is printed only if this test fails. }); ``` -------------------------------- ### Use setupLogTape in a test file Source: https://logtape.org/manual/testing Demonstrates importing and executing the setup function before running tests. ```typescript import { test, expect } from "@logtape/testing-vitest"; import { getLogger } from "@logtape/logtape"; import { setupLogTape } from "./setup-logtape.ts"; await setupLogTape(); test("case", () => { getLogger(["my-lib"]).info("Fixture state: {state}."); expect(1 + 1).toBe(2); // The info log is printed only if this test fails. }); ``` -------------------------------- ### Install @logtape/pretty package Source: https://logtape.org/manual/formatters Commands to install the pretty formatter package using various package managers. ```sh deno add jsr:@logtape/pretty ``` ```sh npm add @logtape/pretty ``` ```sh pnpm add @logtape/pretty ``` ```sh yarn add @logtape/pretty ``` ```sh bun add @logtape/pretty ``` -------------------------------- ### Install LogTape Hono adapter Source: https://logtape.org/manual/integrations Installation commands for the @logtape/hono package across different JavaScript runtimes. ```sh deno add jsr:@logtape/hono ``` ```sh npm add @logtape/hono ``` ```sh pnpm add @logtape/hono ``` ```sh yarn add @logtape/hono ``` ```sh bun add @logtape/hono ``` -------------------------------- ### Install with custom logger and options Source: https://logtape.org/manual/adaptors Uses the install function to apply custom Winston logger instances and specific level mappings. ```typescript import winston from "winston"; import { install } from "@logtape/adaptor-winston"; const customLogger = winston.createLogger({ transports: [new winston.transports.File({ filename: "app.log" })] }); // Install with custom logger and options install(customLogger, { category: { position: "start", decorator: "[]" }, levelsMap: { "trace": "silly", "debug": "debug", "info": "verbose", "warning": "info", "error": "warn", "fatal": "error", } }); ``` -------------------------------- ### Configure linting rules Source: https://logtape.org/lint/prefer-lazy-evaluation Configuration examples for ESLint and Deno Lint. ```javascript import logtape from "@logtape/lint/eslint"; export default [ { plugins: { "@logtape": logtape }, rules: { "@logtape/prefer-lazy-evaluation": "warn", }, }, ]; ``` ```json { "unstable": ["lint"], "lint": { "plugins": ["jsr:@logtape/lint/deno"], "rules": { "include": ["logtape/prefer-lazy-evaluation"] } } } ``` -------------------------------- ### Setup LogTape via top-level function Source: https://logtape.org/manual/testing Call a shared setup function at the top level of each test file if preloading is not feasible. ```typescript import { AsyncLocalStorage } from "node:async_hooks"; import { configure } from "@logtape/logtape"; let configured = false; export async function setupLogTape(): Promise { if (configured) return; configured = true; await configure({ contextLocalStorage: new AsyncLocalStorage(), sinks: {}, loggers: [ { category: ["logtape", "meta"], sinks: [] }, ], }); } ``` ```typescript import { test } from "@logtape/testing-bun"; import { getLogger } from "@logtape/logtape"; import { setupLogTape } from "./setup-logtape.ts"; await setupLogTape(); test("case", () => { getLogger(["my-lib"]).info("Fixture state: {state}."); // Run assertions. The info log is printed only if this test fails. }); ``` -------------------------------- ### Setup LogTape via top-level function Source: https://logtape.org/manual/testing Call a shared setup function at the top level of each test file if preloading is not feasible. ```typescript import { AsyncLocalStorage } from "node:async_hooks"; import { configure } from "@logtape/logtape"; let configured = false; export async function setupLogTape(): Promise { if (configured) return; configured = true; await configure({ contextLocalStorage: new AsyncLocalStorage(), sinks: {}, loggers: [ { category: ["logtape", "meta"], sinks: [] }, ], }); } ``` ```typescript import { test } from "@logtape/testing-deno"; import { getLogger } from "@logtape/logtape"; import { setupLogTape } from "./setup-logtape.ts"; await setupLogTape(); test("case", () => { getLogger(["my-lib"]).info("Fixture state: {state}."); // Run assertions. The info log is printed only if this test fails. }); ``` -------------------------------- ### Install LogTape Source: https://logtape.org/ Command to add the LogTape package to your project using Deno. ```bash deno add jsr:@logtape/logtape ``` -------------------------------- ### Install Unstable LogTape Source: https://logtape.org/manual/install Commands to install the development version of LogTape. ```sh npm add @logtape/logtape@dev ``` ```sh pnpm add @logtape/logtape@dev ``` ```sh yarn add @logtape/logtape@dev ``` ```sh bun add @logtape/logtape@dev ``` -------------------------------- ### Install LogTape Deno testing package Source: https://logtape.org/manual/testing Add the testing package to your Deno project. ```bash deno add jsr:@logtape/testing-deno ``` -------------------------------- ### Install testing package Source: https://logtape.org/manual/library Commands to add the @logtape/testing package to your project. ```bash deno add jsr:@logtape/testing ``` ```bash npm add @logtape/testing ``` ```bash pnpm add @logtape/testing ``` ```bash yarn add @logtape/testing ``` ```bash bun add @logtape/testing ``` -------------------------------- ### Correct usage examples Source: https://logtape.org/lint/no-unawaited-log Examples showing valid ways to handle log calls with async callbacks, including awaiting, returning, and concise arrow function bodies. ```typescript import { getLogger } from "@logtape/logtape"; const logger = getLogger(["my-app"]); async function handler() { // Awaited: await logger.debug("Data: {d}.", async () => ({ d: await fetchData() })); // Returned (caller is responsible for awaiting): return logger.debug("Data: {d}.", async () => ({ d: await fetchData() })); } // Concise arrow body propagates the promise: const logData = async () => logger.debug("Data: {d}.", async () => ({ d: await fetchData() })); ``` -------------------------------- ### Top-level Setup Function Source: https://logtape.org/manual/testing Define a shared setup function to be called at the top level of each test file if preloading is not possible. ```typescript import { AsyncLocalStorage } from "node:async_hooks"; import { configure } from "@logtape/logtape"; let configured = false; export async function setupLogTape(): Promise { if (configured) return; configured = true; await configure({ contextLocalStorage: new AsyncLocalStorage(), sinks: {}, loggers: [ { category: ["logtape", "meta"], sinks: [] }, ], }); } ``` ```typescript import { test } from "@logtape/testing-node"; import { getLogger } from "@logtape/logtape"; import { setupLogTape } from "./setup-logtape.ts"; await setupLogTape(); test("case", async () => { getLogger(["my-lib"]).info("Fixture state: {state}."); // Run assertions. The info log is printed only if this test fails. }); ``` -------------------------------- ### Install Drizzle ORM adapter Source: https://logtape.org/manual/integrations Commands to install the @logtape/drizzle-orm package using various package managers. ```sh deno add jsr:@logtape/drizzle-orm ``` ```sh npm add @logtape/drizzle-orm ``` ```sh pnpm add @logtape/drizzle-orm ``` ```sh yarn add @logtape/drizzle-orm ``` ```sh bun add @logtape/drizzle-orm ``` -------------------------------- ### Environment variable expansion syntax Source: https://logtape.org/manual/config Example configuration showing the use of default values in environment variable expansion. ```json { "sinks": { "file": { "type": "@logtape/file#getFileSink()", "path": "${LOG_PATH:/var/log/app.log}" } } } ``` -------------------------------- ### Install @logtape/adaptor-pino Source: https://logtape.org/manual/adaptors Commands to add the Pino adaptor package using various package managers. ```Deno deno add jsr:@logtape/adaptor-pino ``` ```npm npm add @logtape/adaptor-pino ``` ```pnpm pnpm add @logtape/adaptor-pino ``` ```Yarn yarn add @logtape/adaptor-pino ``` ```Bun bun add @logtape/adaptor-pino ``` -------------------------------- ### Install Bunyan adapter automatically Source: https://logtape.org/manual/adaptors Use the install function to route all LogTape logs to a Bunyan logger instance. ```typescript import bunyan from "bunyan"; import { install } from "@logtape/adaptor-bunyan"; const bunyanLogger = bunyan.createLogger({ name: "my-app", level: "info" }); // Install with custom logger and options install(bunyanLogger, { category: { position: "start", decorator: "[]", separator: "." } }); // Now any LogTape-enabled library will log through Bunyan import { getLogger } from "@logtape/logtape"; const logger = getLogger("my-app"); logger.info("This will be logged through Bunyan"); ``` -------------------------------- ### Install LogTape Bun testing package Source: https://logtape.org/manual/testing Add the testing package to your project dependencies. ```bash bun add @logtape/testing-bun ``` -------------------------------- ### Configuring LogTape in an application Source: https://logtape.org/comparison Example of how an application can configure LogTape to capture logs from a library. ```typescript // In your application import { configure, getConsoleSink } from "@logtape/logtape"; import { processData } from "some-library"; await configure({ sinks: { console: getConsoleSink(), }, loggers: [ { category: ["some-library"], lowestLevel: "debug", sinks: ["console"] }, ], }); processData([1, 2, 3]); // Now you'll see the library's logs ``` -------------------------------- ### Configure LogTape with GraphQL Yoga Source: https://logtape.org/manual/integrations Basic setup showing how to configure LogTape and pass the logger to the Yoga server instance. ```typescript import { configure, getConsoleSink } from "@logtape/logtape"; import { getYogaLogger } from "@logtape/graphql-yoga"; import { createSchema, createYoga } from "graphql-yoga"; await configure({ sinks: { console: getConsoleSink() }, loggers: [ { category: ["graphql-yoga"], sinks: ["console"], lowestLevel: "debug" } ], }); const yoga = createYoga({ schema: createSchema({ typeDefs: /* GraphQL */ ` type Query { hello: String! } `, resolvers: { Query: { hello: () => "world", }, }, }), logging: getYogaLogger(), }); ``` -------------------------------- ### Configure Database Logging with AsyncSink Source: https://logtape.org/manual/sinks Example of integrating an asynchronous database insertion into the LogTape configuration. ```typescript // @noErrors: 2345 interface Database { /** * A hypothetical table interface. */ readonly logs: Table<"logs">; } interface Table { /** * A hypothetical method to insert a record into the table. */ insert(record: TableRecord): Promise; } interface TableRecord { timestamp: number; level: string; category: string; message: string; properties: string; } /** * A hypothetical database interface. */ const db = null as unknown as Database; // ---cut-before--- import { type AsyncSink, configure, fromAsyncSink } from "@logtape/logtape"; const databaseSink: AsyncSink = async (record) => { await db.logs.insert({ timestamp: record.timestamp, level: record.level, category: record.category.join("."), message: record.message.join(""), properties: JSON.stringify(record.properties), }); }; await configure({ sinks: { database: fromAsyncSink(databaseSink), }, loggers: [ { category: [], sinks: ["database"], lowestLevel: "info" }, ], }); ``` -------------------------------- ### Install log4js adapter Source: https://logtape.org/manual/adaptors Commands to add the log4js adapter dependency to your project. ```sh deno add jsr:@logtape/adaptor-log4js ``` ```sh npm add @logtape/adaptor-log4js ``` ```sh pnpm add @logtape/adaptor-log4js ``` ```sh yarn add @logtape/adaptor-log4js ``` ```sh bun add @logtape/adaptor-log4js ``` -------------------------------- ### Install skills-npm as a development dependency Source: https://logtape.org/manual/llm Install the skills-npm package using your preferred package manager to enable automatic skill synchronization. ```bash npm install -D skills-npm ``` ```bash pnpm add -D skills-npm ``` ```bash yarn add -D skills-npm ``` ```bash bun add -D skills-npm ``` -------------------------------- ### Install @logtape/testing-node Source: https://logtape.org/manual/testing Commands to add the testing package using various Node.js package managers. ```bash npm add @logtape/testing-node ``` ```bash pnpm add @logtape/testing-node ``` ```bash yarn add @logtape/testing-node ``` ```bash bun add @logtape/testing-node ``` -------------------------------- ### Correct Code Examples Source: https://logtape.org/lint/no-message-interpolation Examples that comply with the rule, including structured templates, plain strings, and tagged templates. ```typescript import { getLogger } from "@logtape/logtape"; const logger = getLogger(["my-app"]); logger.info("User {userId} logged in.", { userId }); logger.error("Request {reqId} failed.", { reqId }); logger.debug("Processing {count} items.", { count: items.length }); // Plain backtick strings without ${} are allowed logger.info(`User logged in.`); // Tagged template literals (LogTape template syntax) are allowed logger.info`User ${userId} logged in.`; ``` -------------------------------- ### Install @logtape/elysia Source: https://logtape.org/manual/integrations Commands to add the LogTape Elysia plugin using various package managers. ```sh deno add jsr:@logtape/elysia ``` ```sh npm add @logtape/elysia ``` ```sh pnpm add @logtape/elysia ``` ```sh yarn add @logtape/elysia ``` ```sh bun add @logtape/elysia ``` -------------------------------- ### Library logging with LogTape Source: https://logtape.org/comparison Example of a library using LogTape to log without requiring configuration. ```typescript // In some-library/index.js import { getLogger } from "@logtape/logtape"; const logger = getLogger(["some-library"]); export function processData(data) { logger.info("Processing data with {size} items.", { size: data.length }); // ... process data } ``` -------------------------------- ### Install @logtape/adaptor-winston Source: https://logtape.org/manual/adaptors Commands to add the Winston adaptor package to your project using different package managers. ```sh deno add jsr:@logtape/adaptor-winston ``` ```sh npm add @logtape/adaptor-winston ``` ```sh pnpm add @logtape/adaptor-winston ``` ```sh yarn add @logtape/adaptor-winston ``` ```sh bun add @logtape/adaptor-winston ``` -------------------------------- ### Install @logtape/adaptor-bunyan Source: https://logtape.org/manual/adaptors Commands to add the Bunyan adapter package using various package managers. ```sh deno add jsr:@logtape/adaptor-bunyan ``` ```sh npm add @logtape/adaptor-bunyan ``` ```sh pnpm add @logtape/adaptor-bunyan ``` ```sh yarn add @logtape/adaptor-bunyan ``` ```sh bun add @logtape/adaptor-bunyan ``` -------------------------------- ### Use Explicit Setup in Tests Source: https://logtape.org/manual/testing Importing from the main package allows using configured LogTape instances in test files. ```typescript import { test, expect } from "@logtape/testing-vitest"; import { getLogger } from "@logtape/logtape"; test("case", () => { getLogger(["my-lib"]).info("Fixture state: {state}.", { state: "ready", }); expect(1 + 1).toBe(2); // The info log is printed only if this test fails. }); ``` -------------------------------- ### Configure LogTape with Fastify Source: https://logtape.org/manual/integrations Basic setup for using LogTape as the logging backend for a Fastify application. ```typescript import { configure, getConsoleSink } from "@logtape/logtape"; import { getLogTapeFastifyLogger } from "@logtape/fastify"; import Fastify from "fastify"; await configure({ sinks: { console: getConsoleSink() }, loggers: [ { category: ["fastify"], sinks: ["console"], lowestLevel: "info" } ], }); const fastify = Fastify({ loggerInstance: getLogTapeFastifyLogger(), }); fastify.get("/", async (request, reply) => { // Uses LogTape under the hood with request context request.log.info("Handling request"); return { hello: "world" }; }); await fastify.listen({ port: 3000 }); ``` -------------------------------- ### Traditional library logging with winston Source: https://logtape.org/comparison Example of a library forcing a specific logging configuration on the consumer. ```typescript // In some-library/index.js import winston from "winston"; const logger = winston.createLogger({ level: "info", format: winston.format.json(), transports: [new winston.transports.Console()] }); export function processData(data) { logger.info("Processing data", { size: data.length }); // ... process data } ``` -------------------------------- ### Configure standard file sink Source: https://logtape.org/sinks/file Example of configuring a file sink with custom buffering and non-blocking settings. ```typescript // @noErrors: 2345 import { getFileSink } from "@logtape/file"; import { configure } from "@logtape/logtape"; await configure({ sinks: { file: getFileSink("my-app.log", { lazy: true, bufferSize: 8192, flushInterval: 5000, nonBlocking: true, }), }, // Omitted for brevity }); ``` -------------------------------- ### Install OpenTelemetry sink package Source: https://logtape.org/sinks/otel Commands to add the @logtape/otel package using various package managers. ```sh deno add jsr:@logtape/otel ``` ```sh npm add @logtape/otel ``` ```sh pnpm add @logtape/otel ``` ```sh yarn add @logtape/otel ``` ```sh bun add @logtape/otel ``` -------------------------------- ### Configure pretty formatter Source: https://logtape.org/manual/formatters Example of integrating the prettyFormatter into the LogTape configuration for the console sink. ```typescript import { configure, getConsoleSink } from "@logtape/logtape"; import { prettyFormatter } from "@logtape/pretty"; await configure({ sinks: { console: getConsoleSink({ formatter: prettyFormatter }), }, loggers: [ { category: [], sinks: ["console"], lowestLevel: "debug" }, ], }); ``` -------------------------------- ### Install LogTape Fastify package Source: https://logtape.org/manual/integrations Commands to add the @logtape/fastify package using various package managers. ```Deno deno add jsr:@logtape/fastify ``` ```npm npm add @logtape/fastify ``` ```pnpm pnpm add @logtape/fastify ``` ```Yarn yarn add @logtape/fastify ``` ```Bun bun add @logtape/fastify ``` -------------------------------- ### Configure shared LogTape preload module Source: https://logtape.org/manual/testing Define a shared setup module and preload it for the test run to avoid per-file configuration. ```typescript import { AsyncLocalStorage } from "node:async_hooks"; import { configure } from "@logtape/logtape"; await configure({ contextLocalStorage: new AsyncLocalStorage(), sinks: {}, loggers: [ { category: ["logtape", "meta"], sinks: [] }, ], }); ``` ```bash deno test --preload ./test/setup-logtape.ts ``` ```typescript import { test } from "@logtape/testing-deno"; import { getLogger } from "@logtape/logtape"; test("case", () => { getLogger(["my-lib"]).info("Fixture state: {state}.", { state: "ready", }); // Run assertions. The info log is printed only if this test fails. }); ``` -------------------------------- ### Configure shared LogTape preload module Source: https://logtape.org/manual/testing Define a shared setup module and preload it for the test run to avoid per-file configuration. ```typescript import { AsyncLocalStorage } from "node:async_hooks"; import { configure } from "@logtape/logtape"; await configure({ contextLocalStorage: new AsyncLocalStorage(), sinks: {}, loggers: [ { category: ["logtape", "meta"], sinks: [] }, ], }); ``` ```bash bun test --preload ./test/setup-logtape.ts ``` ```typescript import { test } from "@logtape/testing-bun"; import { getLogger } from "@logtape/logtape"; test("case", () => { getLogger(["my-lib"]).info("Fixture state: {state}.", { state: "ready", }); // Run assertions. The info log is printed only if this test fails. }); ``` -------------------------------- ### Add prepare script to package.json Source: https://logtape.org/manual/llm Configure the prepare script in your package.json to ensure skills-npm runs during installation. ```json { "scripts": { "prepare": "skills-npm" } } ``` -------------------------------- ### Configure context local storage Source: https://logtape.org/manual/categories Required setup for withCategoryPrefix to function, using AsyncLocalStorage from node:async_hooks. ```typescript // @noErrors: 2307 import { AsyncLocalStorage } from "node:async_hooks"; import { configure } from "@logtape/logtape"; await configure({ // ... other settings ... // ---cut-start--- sinks: {}, loggers: [], // ---cut-end--- contextLocalStorage: new AsyncLocalStorage(), }); ``` -------------------------------- ### Define Sinks in Configuration Source: https://logtape.org/manual/config Example structure for defining console and file sinks within a configuration object. ```json { "sinks": { "console": { "type": "#console()" }, "file": { "type": "@logtape/file#getFileSink()", "path": "/var/log/app.log" } } } ``` -------------------------------- ### Pretty formatter output example Source: https://logtape.org/manual/formatters Visual representation of how log records appear when using the pretty formatter. ```ansi ✨ info logtape·meta LogTape loggers are configured. Note that LogTape itself uses the meta logger, which has category [ 'logtape', 'meta' ]. The meta logger purposes to log internal errors such as sink exceptions. If you are seeing this message, the meta logger is automatically configured. It's recommended to configure the meta logger with a separate sink so that you can easily notice if logging itself fails or is misconfigured. To turn off this message, configure the meta logger with higher log levels than 'info'. See also . 🔍 trace myapp·module This is a trace log. 🐛 debug myapp·module This is a debug log with value: { foo: 123 } ✨ info myapp This is a very long informational log ⚡ warning myapp This is a warning. ❌ error myapp·module This is an error with exception: Error: This is an exception. at file:///tmp/test.ts:23:10 💀 fatal myapp This is a fatal error. ``` -------------------------------- ### Install @logtape/syslog package Source: https://logtape.org/sinks/syslog Commands to add the syslog package to your project using various package managers. ```sh deno add jsr:@logtape/syslog ``` ```sh npm add @logtape/syslog ``` ```sh pnpm add @logtape/syslog ``` ```sh yarn add @logtape/syslog ``` ```sh bun add @logtape/syslog ``` -------------------------------- ### Install LogTape Koa middleware Source: https://logtape.org/manual/integrations Commands to add the @logtape/koa package using various package managers. ```sh deno add jsr:@logtape/koa ``` ```sh npm add @logtape/koa ``` ```sh pnpm add @logtape/koa ``` ```sh yarn add @logtape/koa ``` ```sh bun add @logtape/koa ``` -------------------------------- ### Configure CloudWatch Logs sink Source: https://logtape.org/sinks/cloudwatch-logs Basic setup using getCloudWatchLogsSink with log group, stream, and region parameters. ```typescript import { configure } from "@logtape/logtape"; import { getCloudWatchLogsSink } from "@logtape/cloudwatch-logs"; await configure({ sinks: { cloudwatch: getCloudWatchLogsSink({ logGroupName: "/aws/lambda/my-function", logStreamName: "my-stream", region: "us-east-1", }), }, loggers: [ { category: [], sinks: ["cloudwatch"], lowestLevel: "info" }, ], }); ``` -------------------------------- ### Configure LogTape for tests Source: https://logtape.org/manual/testing Defines a reusable setup function for LogTape to be called at the top level of test files. ```typescript import { AsyncLocalStorage } from "node:async_hooks"; import { configure } from "@logtape/logtape"; let configured = false; export async function setupLogTape(): Promise { if (configured) return; configured = true; await configure({ contextLocalStorage: new AsyncLocalStorage(), sinks: {}, loggers: [ { category: ["logtape", "meta"], sinks: [] }, ], }); } ``` -------------------------------- ### Example JSON Log Record Source: https://logtape.org/sinks/cloudwatch-logs A sample log record formatted as a JSON object for CloudWatch Logs. ```json { "@timestamp": "2023-12-01T10:30:00.000Z", "level": "ERROR", "logger": "api.auth", "message": "Failed login attempt for user {\"email\":\"user@example.com\"}", "properties": { "ip": "192.168.1.1", "userAgent": "Mozilla/5.0...", "attempts": 3 } } ``` -------------------------------- ### Install LogTape Config Package Source: https://logtape.org/manual/config Commands to add the @logtape/config package to your project using various package managers. ```sh deno add jsr:@logtape/config ``` ```sh npm add @logtape/config ``` ```sh pnpm add @logtape/config ``` ```sh yarn add @logtape/config ``` ```sh bun add @logtape/config ``` -------------------------------- ### Install LogTape Lint package Source: https://logtape.org/lint Commands to add the @logtape/lint package to your project using different package managers. ```sh deno add jsr:@logtape/lint ``` ```sh npm add --save-dev @logtape/lint ``` ```sh pnpm add --save-dev @logtape/lint ``` ```sh yarn add --dev @logtape/lint ``` ```sh bun add --dev @logtape/lint ``` -------------------------------- ### Manually setting up Cursor skills Source: https://logtape.org/manual/llm Copy the skill directory into the project's .cursor/skills folder. ```bash mkdir -p .cursor/skills cp -r node_modules/@logtape/logtape/skills/logtape .cursor/skills/logtape ``` -------------------------------- ### Incorrect Code Examples Source: https://logtape.org/lint/no-message-interpolation Examples that trigger the no-message-interpolation lint error. ```typescript import { getLogger } from "@logtape/logtape"; const logger = getLogger(["my-app"]); logger.info(`User ${userId} logged in.`); // ← error logger.error(`Request ${reqId} failed.`); // ← error logger.debug(`Processing ${items.length} items.`); // ← error ``` -------------------------------- ### Configure Windows Event Log sink Source: https://logtape.org/sinks/windows-eventlog Example of initializing the Windows Event Log sink within the LogTape configuration. ```typescript import { configure } from "@logtape/logtape"; import { getWindowsEventLogSink } from "@logtape/windows-eventlog"; await configure({ sinks: { eventlog: getWindowsEventLogSink({ sourceName: "MyApplication", }), }, loggers: [ { category: [], sinks: ["eventlog"], lowestLevel: "info" }, ], }); ``` -------------------------------- ### Incorrect usage example Source: https://logtape.org/lint/no-unawaited-log An example of an unawaited log call that triggers the lint error. ```typescript import { getLogger } from "@logtape/logtape"; const logger = getLogger(["my-app"]); async function handler() { logger.debug("Data: {d}.", async () => ({ // ← error d: await fetchData(), })); } ``` -------------------------------- ### Configuring postinstall script Source: https://logtape.org/manual/llm Automate skill export by adding a postinstall script to package.json. ```json { "scripts": { "postinstall": "agents export --target claude" } } ``` -------------------------------- ### Correct usage examples Source: https://logtape.org/lint/prefer-lazy-evaluation Shows how to wrap property objects in arrow functions to satisfy the rule, and notes that static values are permitted. ```typescript import { getLogger } from "@logtape/logtape"; const logger = getLogger(["my-app"]); // Wrap the object in an arrow function: logger.debug("Fetched data: {data}.", () => ({ data: fetchData() })); logger.debug("Value: {x}.", () => ({ x: compute() })); // Plain property values without calls are fine: logger.info("Hello {name}.", { name: "world" }); logger.info("Count: {n}.", { n: items.length }); ``` -------------------------------- ### Configure LogTape via dedicated setup file Source: https://logtape.org/manual/config Create a dedicated configuration file and import it first in the application entry point to ensure synchronous initialization. ```typescript import { configureSync, getConsoleSink } from "@logtape/logtape"; configureSync({ sinks: { console: getConsoleSink(), }, loggers: [ { category: "my-app", lowestLevel: "debug", sinks: ["console"], }, ], }); ``` ```typescript // Configuration must be imported first! import "./setup"; import { App } from "./App"; // ... rest of your application ``` -------------------------------- ### Manually setting up Claude Code skills Source: https://logtape.org/manual/llm Copy the skill directory into the project's .claude/skills folder. ```bash mkdir -p .claude/skills cp -r node_modules/@logtape/logtape/skills/logtape .claude/skills/logtape ``` -------------------------------- ### Default text formatter output Source: https://logtape.org/manual/formatters Example output format for the defaultTextFormatter. ```text 2023-11-14 22:13:20.000 +00:00 [INF] category·subcategory: Hello, world! ``` -------------------------------- ### Configure library logging with LogTape Source: https://logtape.org/manual/library Demonstrates setting up console and file sinks, defining log levels, and applying filters for specific library categories. ```typescript // @noErrors: 2307 import { getFileSink } from "@logtape/file"; import { configure, getConsoleSink } from "@logtape/logtape"; import { Database } from "my-awesome-lib"; await configure({ sinks: { console: getConsoleSink(), file: getFileSink("app.log") }, filters: { excludeDebug: (record) => record.level !== "debug" }, loggers: [ { category: ["my-awesome-lib"], lowestLevel: "info", sinks: ["console", "file"] }, { category: ["my-awesome-lib", "database"], lowestLevel: "debug", sinks: ["file"], filters: ["excludeDebug"] } ] }); const db = new Database("localhost", 5432, "user"); db.connect(); db.query("SELECT * FROM users"); ``` -------------------------------- ### Log with structured data Source: https://logtape.org/sinks/syslog Example of logging a message with properties that will be included as structured data. ```typescript import { configure, getLogger } from "@logtape/logtape"; import { getSyslogSink } from "@logtape/syslog"; await configure({ sinks: { syslog: getSyslogSink({ includeStructuredData: true, structuredDataId: "myapp@12345", }), }, loggers: [ { category: [], sinks: ["syslog"], lowestLevel: "debug" }, ], }); const logger = getLogger(); logger.info("User login successful", { userId: 12345, method: "oauth" }); ``` -------------------------------- ### Implement a universal library with LogTape Source: https://logtape.org/comparison Demonstrates using LogTape to create a logging-enabled library that functions consistently across all major JavaScript runtimes. ```typescript // Works in Node.js, Deno, Bun, browsers, and edge functions import { getLogger } from "@logtape/logtape"; const logger = getLogger(["my-universal-lib"]); export function apiCall(url: string) { logger.debug("Making API call to {url}", { url }); // Use appropriate fetch implementation for the runtime return fetch(url).then(response => { logger.info("API call completed with status {status}", { status: response.status }); return response; }); } ``` -------------------------------- ### Basic Express Integration Source: https://logtape.org/manual/integrations Standard setup for using LogTape middleware in an Express application. ```typescript import { configure, getConsoleSink } from "@logtape/logtape"; import { expressLogger } from "@logtape/express"; import express from "express"; await configure({ sinks: { console: getConsoleSink() }, loggers: [ { category: ["express"], sinks: ["console"], lowestLevel: "info" } ], }); const app = express(); app.use(expressLogger()); app.get("/", (req, res) => { res.json({ hello: "world" }); }); app.listen(3000); ``` -------------------------------- ### logfmt formatter output Source: https://logtape.org/manual/formatters Example output format for the logfmtFormatter, producing space-delimited key-value pairs. ```logfmt time=2023-11-14T22:13:20.000Z level=info logger=my.logger msg="Hello, world!" key=value ``` -------------------------------- ### Use Autoload Entry Point Source: https://logtape.org/manual/testing Importing from the autoload entry point configures minimal context storage for failure log reporting. ```typescript import { test, expect } from "@logtape/testing-vitest/autoload"; import { getLogger } from "@logtape/logtape"; test("case", () => { getLogger(["my-lib"]).info("Fixture state: {state}.", { state: "ready", }); expect(1 + 1).toBe(2); // The info log is printed only if this test fails. }); ``` -------------------------------- ### Basic Koa integration Source: https://logtape.org/manual/integrations Standard setup for using LogTape middleware within a Koa application. ```typescript import { configure, getConsoleSink } from "@logtape/logtape"; import { koaLogger } from "@logtape/koa"; import Koa from "koa"; await configure({ sinks: { console: getConsoleSink() }, loggers: [ { category: ["koa"], sinks: ["console"], lowestLevel: "info" } ], }); const app = new Koa(); app.use(koaLogger()); app.use((ctx) => { ctx.body = { hello: "world" }; }); app.listen(3000); ``` -------------------------------- ### Configure LogTape Synchronously Source: https://logtape.org/manual/config Use this for synchronous setup. Note that sinks requiring asynchronous disposal, such as stream sinks, cannot be used with this method. ```typescript import { configureSync, getConsoleSink } from "@logtape/logtape"; configureSync({ sinks: { console: getConsoleSink(), }, loggers: [ { category: "my-app", lowestLevel: "info", sinks: ["console"], }, ], }); ```