### Install Hiprax Logger Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Install the package via npm. ```bash npm install @hiprax/logger ``` -------------------------------- ### Log Output Formats Source: https://github.com/hiprax/logger/blob/main/_autodocs/endpoints.md Examples of how log entries appear in console, file, and structured JSON formats. ```text [INFO] (http) POST /api/users 201 12.45ms (completed) ``` ```text UTC: 2026-06-15 14:30:22 [INFO] (http) POST /api/users 201 12.45ms (completed) { "tenantId": "org-123", "userId": 42 } ``` ```json { "level": "info", "message": "POST /api/users 201 12.45ms (completed)", "timestamp": "2026-06-15 14:30:22", "module": "http", "event": "completed", "method": "POST", "url": "/api/users", "statusCode": 201, "responseTimeMs": 12.45, "contentLength": 256, "ip": "192.168.1.100", "userAgent": "Mozilla/5.0...", "tenantId": "org-123", "userId": 42 } ``` -------------------------------- ### Capture start time before body parsing Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-request-logger.md Manually set the start time in an early middleware to ensure the logger accounts for time spent in body parsers. ```typescript import express from "express"; import { createRequestLogger, REQUEST_START_SYMBOL } from "@hiprax/logger"; const app = express(); // First middleware — captures the earliest timestamp app.use((req, res, next) => { (req as any)[REQUEST_START_SYMBOL] = process.hrtime.bigint(); next(); }); // Slow body parser app.use(express.json()); // Logger picks up the start time app.use(createRequestLogger({ includeHttpContext: true })); ``` -------------------------------- ### Timezone Output Format Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Example of how UTC and additional IANA timezones are rendered in log file output. ```text UTC: 2026-06-15 14:30:22 Europe/London: 2026-06-15 15:30:22 [INFO] (auth) Login successful ``` -------------------------------- ### Capture early start time Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-request-logger.md Manually set the REQUEST_START_SYMBOL to measure latency before the logger middleware is initialized. ```typescript import { createRequestLogger, REQUEST_START_SYMBOL } from "@hiprax/logger"; app.use((req, res, next) => { (req as any)[REQUEST_START_SYMBOL] = process.hrtime.bigint(); next(); }); app.use(express.json()); // slow parser app.use(createRequestLogger({ includeHttpContext: true })); // responseTimeMs now reflects time from the very first middleware ``` -------------------------------- ### Configure request logger with loggingMode Source: https://github.com/hiprax/logger/blob/main/_autodocs/types.md Examples of using built-in presets and custom configuration objects within the createRequestLogger function. ```typescript createRequestLogger({ loggingMode: "prod-only", // log only in production }); createRequestLogger({ loggingMode: { sources: ["DEPLOYMENT_STAGE"], allow: ["staging", "qa"], fallback: false, }, }); ``` -------------------------------- ### Mounting Request Logger Middleware Source: https://github.com/hiprax/logger/blob/main/_autodocs/configuration.md Mount the logger before slow middleware to capture accurate latency, or use the REQUEST_START_SYMBOL to manually track start time. ```typescript import { createRequestLogger, REQUEST_START_SYMBOL } from "@hiprax/logger"; const app = express(); // Mount FIRST (before slow body parsers, auth, etc.) // so responseTimeMs reflects true end-to-end latency app.use(createRequestLogger({ includeHttpContext: true })); // Then body parser, auth, etc. app.use(express.json()); // OR: capture start time earlier and pass it via symbol app.use((req, res, next) => { (req as any)[REQUEST_START_SYMBOL] = process.hrtime.bigint(); next(); }); app.use(express.json()); // slow parser // Logger picks up start time and calculates true duration app.use(createRequestLogger({ includeHttpContext: true })); ``` -------------------------------- ### Example Crash Log Entry Source: https://github.com/hiprax/logger/blob/main/README.md The JSON structure of a crash record produced by the logger. ```json { "crash": "uncaughtException", "level": "error", "message": "uncaughtException: …" } ``` -------------------------------- ### Configure Request Logger Source: https://github.com/hiprax/logger/blob/main/_autodocs/types.md Example usage of createRequestLogger with a custom message builder using the RequestLogEntry type. ```typescript import { createRequestLogger } from "@hiprax/logger"; app.use( createRequestLogger({ includeHttpContext: true, messageBuilder: (entry: RequestLogEntry) => { return `${entry.method} ${entry.url} → ${entry.statusCode} (${entry.responseTimeMs}ms) [${entry.event}]`; }, }), ); ``` -------------------------------- ### Handling RequestLoggerOptionError Source: https://github.com/hiprax/logger/blob/main/_autodocs/errors.md Examples of catching and handling specific RequestLoggerOptionError codes when configuring request loggers. ```typescript import { createRequestLogger, RequestLoggerOptionError } from "@hiprax/logger"; try { createRequestLogger({ maskBodyKeys: [42 as unknown as string], }); } catch (err) { if (err instanceof RequestLoggerOptionError && err.code === "INVALID_MASK") { console.error("Mask configuration is invalid:", err.message); // Use defaults return createRequestLogger({ maskBodyKeys: [] }); } else { throw err; } } try { createRequestLogger({ maxBodyLength: 0 }); } catch (err) { if (err instanceof RequestLoggerOptionError && err.code === "INVALID_BODY_LIMIT") { console.error("Body limit invalid:", err.message); // Use default 3000 } else { throw err; } } try { createRequestLogger({ level: "invalid" as any }); } catch (err) { if (err instanceof RequestLoggerOptionError && err.code === "INVALID_LEVEL") { console.error("Level is invalid:", err.message); } else { throw err; } } ``` -------------------------------- ### createNoopLogger Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Creates a silent no-op logger that drops every call. Useful for libraries or test setups requiring a default logger that emits no output. ```APIDOC ## createNoopLogger ### Description Creates a silent no-op logger that drops every call on the floor. Returns a singleton instance that implements all standard npm log-level methods as no-ops. ### Signature `function createNoopLogger(): winston.Logger` ### Return Value Returns a `winston.Logger` instance. All methods return the logger for chainability. This instance is not affected by `resetLoggerRegistry()`. ``` -------------------------------- ### Override Request Start Time with REQUEST_START_SYMBOL Source: https://github.com/hiprax/logger/blob/main/README.md Use this pattern to ensure response time accuracy when the logger cannot be mounted as the first middleware in the stack. ```ts import express from "express"; import { createRequestLogger, REQUEST_START_SYMBOL } from "@hiprax/logger"; const app = express(); // First piece of middleware — captures the earliest possible timestamp. app.use((req, _res, next) => { (req as any)[REQUEST_START_SYMBOL] = process.hrtime.bigint(); next(); }); // Slow body parser, authentication, etc. app.use(express.json()); // Logger picks up the start time from the symbol. app.use(createRequestLogger({ includeHttpContext: true })); ``` -------------------------------- ### Initialize and use the logger Source: https://github.com/hiprax/logger/blob/main/README.md Demonstrates creating a logger instance with specific module naming and timezone configuration, followed by a warning log entry. ```ts import { createLogger } from "@hiprax/logger"; const securityLogger = createLogger({ moduleName: "security/failedLogins", extraTimezones: ["Europe/London"], }); securityLogger.warn(`Failed login attempt\nEmail: ${email}\nIP: ${req.realIp}`); ``` -------------------------------- ### Execute Release Workflow Source: https://github.com/hiprax/logger/blob/main/README.md Standard command sequence for preparing, syncing, and tagging a new project release. ```bash npm run release:prepare -- patch # or minor / major # Open the printed PR URL, wait for CI green, squash-and-merge. npm run sync # pull main, drop merged branches npm run release:tag # creates + pushes vX.Y.Z (triggers publish) ``` -------------------------------- ### REQUEST_START_SYMBOL Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-request-logger.md A unique symbol used to override the per-request start timestamp. By setting this on the request object, the logger can calculate end-to-end latency starting from an upstream instrumentation hook. ```APIDOC ## REQUEST_START_SYMBOL ### Description A unique symbol used to override the per-request start timestamp captured by the middleware. Set this property on the request object to ensure `responseTimeMs` reflects the true end-to-end latency. ### Type Contract - **Value**: `bigint` (must be produced by `process.hrtime.bigint()`) - **Behavior**: If the value is not a `bigint`, the middleware silently ignores it and falls back to its own entry-time capture. ### Usage Example ```typescript import express from "express"; import { createRequestLogger, REQUEST_START_SYMBOL } from "@hiprax/logger"; const app = express(); // Set the start time before other middleware app.use((req, res, next) => { (req as any)[REQUEST_START_SYMBOL] = process.hrtime.bigint(); next(); }); app.use(createRequestLogger({ includeHttpContext: true })); ``` ``` -------------------------------- ### Initialize Library with No-op Logger Source: https://github.com/hiprax/logger/blob/main/README.md Demonstrates setting a default no-op logger for a library that can be overridden by the consumer. ```ts import { createLogger, createNoopLogger } from "@hiprax/logger"; // Library-side default — caller can override. export interface InitOptions { logger?: import("winston").Logger; } export const init = ({ logger = createNoopLogger() }: InitOptions = {}) => { logger.info("Library initialized"); // ... library setup that may emit log lines ... }; // Application-side opt-in to real logging. init({ logger: createLogger({ moduleName: "my-app" }) }); ``` -------------------------------- ### InvalidTimezoneError Trigger Source: https://github.com/hiprax/logger/blob/main/_autodocs/errors.md Example of triggering an InvalidTimezoneError by providing an invalid IANA timezone string. ```typescript createLogger({ extraTimezones: ["Not/A_Real_Zone"] }); // Throws: InvalidTimezoneError: Invalid timezone identifier: Not/A_Real_Zone ``` -------------------------------- ### Initialize basic logger Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Create a logger instance using default settings. ```typescript import { createLogger } from "@hiprax/logger"; const logger = createLogger(); logger.info("Application started"); ``` -------------------------------- ### Run project tests Source: https://github.com/hiprax/logger/blob/main/README.md Executes the test suite using npm. Tests run in-band for deterministic results. ```bash npm test ``` -------------------------------- ### Initialize basic Express middleware Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-request-logger.md Mount the logger as the first middleware to ensure accurate end-to-end latency measurement. ```typescript import express from "express"; import { createRequestLogger } from "@hiprax/logger"; const app = express(); app.use(express.json()); app.use(createRequestLogger()); app.get("/health", (req, res) => res.json({ ok: true })); ``` -------------------------------- ### createLogger(options?: LoggerOptions) Source: https://github.com/hiprax/logger/blob/main/README.md Initializes a new logger instance with the specified configuration options for file logging and timezone support. ```APIDOC ## createLogger(options?: LoggerOptions) ### Description Initializes a logger instance. The options object allows configuration of file logging behavior and additional timezone rendering. ### Parameters - **includeFile** (boolean) - Optional - Enables module-specific rotating file logging. Default: true. - **includeGlobalFile** (boolean) - Optional - Enables shared rotating file logging. Default: true. - **globalModuleName** (string) - Optional - Label for the shared log file. Default: 'all-logs'. - **extraTimezones** (string | string[]) - Optional - Additional IANA zones rendered beside UTC. Invalid zones will throw an InvalidTimezoneError. Default: []. ``` -------------------------------- ### Truncated JSON Body Representation Source: https://github.com/hiprax/logger/blob/main/_autodocs/endpoints.md Example of the JSON structure returned when a body exceeds the configured length. ```json { "_truncated": true, "_originalLength": 4500, "_preview": "{\n \"field1\": \"val1\", \"field2\": \"...\" }" } ``` -------------------------------- ### createLogger(options) Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Initializes a new logger instance with optional configuration for module naming, log levels, formatting, and metadata handling. ```APIDOC ## createLogger(options) ### Description Creates and returns a logger instance. The logger can be configured to handle specific modules, log levels, and output formats. ### Parameters - **options** (object) - Optional - Configuration object for the logger. - **moduleName** (string) - Optional - The name of the module associated with the logs. - **logDirectory** (string) - Optional - The filesystem path where logs should be stored. - **level** (string) - Optional - The minimum log level (e.g., 'debug', 'info', 'warn', 'error'). - **format** (string) - Optional - The output format, such as 'json'. - **extraTimezones** (string[]) - Optional - Array of timezones to include in log output. - **maskMetaKeys** (string[]) - Optional - Array of metadata keys to redact (e.g., 'password'). - **onTransportError** (function) - Optional - Callback function triggered when a transport error occurs. ### Usage Example ```typescript import { createLogger } from "@hiprax/logger"; const logger = createLogger({ moduleName: "auth", level: "debug", maskMetaKeys: ["password"] }); logger.info("User logged in", { userId: 123, password: "secret" }); ``` ``` -------------------------------- ### Customize and apply rotation strategy Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Demonstrates how to retrieve the default strategy, modify its properties, and pass it to the logger configuration. ```typescript import { createLogger, getDefaultRotation } from "@hiprax/logger"; const rotation = getDefaultRotation(); rotation.maxFiles = "30d"; rotation.zippedArchive = true; const logger = createLogger({ rotation }); ``` -------------------------------- ### Initialize Logger per Module Source: https://github.com/hiprax/logger/blob/main/README.md Standard pattern for creating a logger instance for individual modules. ```ts // auth.ts, db.ts, cache.ts, … — one logger per module const logger = createLogger({ moduleName: "auth" }); ``` -------------------------------- ### createLogger(options?: LoggerOptions) Source: https://github.com/hiprax/logger/blob/main/README.md Initializes a new logger instance with specified rotation strategies, custom transports, and error handling callbacks. ```APIDOC ## createLogger(options?: LoggerOptions) ### Description Initializes a logger instance. The options object allows configuration of file rotation strategies, additional winston transports, and error handling logic. ### Parameters - **rotation** (RotationStrategy) - Optional - Rotation configuration for the module file. Defaults to 20 MB / 14 days / daily. - **globalRotation** (RotationStrategy) - Optional - Override rotation for the shared file. Falls back to `rotation` when omitted. - **additionalTransports** (winston.transport[]) - Optional - Appends custom transports. Entries are validated for `log` and `on` methods. Mutating the array after initialization has no effect. - **onTransportError** ((err, transport) => void) - Optional - Callback invoked when a transport emits an error event. Errors are deduplicated and caught to prevent process crashes. ``` -------------------------------- ### Initialize Basic Logger Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Create a logger instance for a specific module. ```typescript import { createLogger } from "@hiprax/logger"; const logger = createLogger({ moduleName: "app" }); logger.info("Application started"); ``` -------------------------------- ### Configure JSON Logger Source: https://github.com/hiprax/logger/blob/main/README.md Initialize the logger with JSON formatting and specify keys to be redacted from metadata. ```ts import { createLogger } from "@hiprax/logger"; const logger = createLogger({ moduleName: "api", format: "json", // The maskMetaKeys redaction continues to apply BEFORE serialization, // so secrets never reach the JSON line. maskMetaKeys: ["password", "authorization", "apiKey"], }); logger.info("Login", { userId: 42, email: "u@example.com", password: "topsecret", durationMs: 12.4, }); ``` -------------------------------- ### Printf Token Handling Source: https://github.com/hiprax/logger/blob/main/README.md Demonstration of how printf tokens are treated as literal text and how they affect metadata logging. ```ts logger.info("User %s logged in", "u-42"); // message: "User %s logged in" — the "u-42" argument is not substituted ``` ```ts logger.info("route /users", { requestId: "r1" }); // requestId logged logger.info("route /a%d", { requestId: "r1" }); // requestId NOT logged ``` ```ts // With splat() composed in, this URL would be REWRITTEN in the log: logger.info("route /caf%c3%a9", { ip }); // -> "route /caf3%a9" ``` ```ts // Avoid — a printf token in `url` (e.g. "%d", or the "%c3" of an encoded // path) silently drops `ip`: logger.info(`Unknown route ${url}`, { ip }); // Prefer — a static message with everything structured: logger.info("Unknown route", { url, ip }); ``` -------------------------------- ### createLogger(options?: LoggerOptions) Source: https://github.com/hiprax/logger/blob/main/README.md Creates or retrieves a cached Winston logger instance configured with safe defaults, rotating files, and UTC timestamps. ```APIDOC ## createLogger(options?: LoggerOptions) ### Description Creates a fully configured Winston logger with safe defaults, rotating files, UTC timestamps, and optional timezone mirrors. Instances are cached by `moduleName` + `logDirectory` to prevent duplicate transports. ### Parameters #### Options - **moduleName** (string) - Optional - Label used in log lines and for module-specific files. Supports nested scopes (e.g., 'security/failedLogins'). Defaults to 'global'. ``` -------------------------------- ### Manage Logger Instance Caching Source: https://github.com/hiprax/logger/blob/main/_autodocs/configuration.md Demonstrates how logger instances are cached by module name and directory, and how to reset the registry. ```typescript const logger1 = createLogger({ moduleName: "auth" }); const logger2 = createLogger({ moduleName: "auth" }); // logger1 === logger2 (same instance, cached) const logger3 = createLogger({ moduleName: "auth", logDirectory: "/tmp/logs" }); // logger3 is a different instance (different logDirectory) // Conflicting options on a cached key log a warning and return the cached instance const logger4 = createLogger({ moduleName: "auth", level: "debug" }); // console.warn(): "Logger for moduleName 'auth' already created with different options: level" // logger4 === logger1 (returns the cached instance, ignores new options) // resetLoggerRegistry() clears the cache resetLoggerRegistry(); const logger5 = createLogger({ moduleName: "auth" }); // logger5 is a fresh instance (NOT logger1) ``` -------------------------------- ### createLogger(options?: LoggerOptions) Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Creates or retrieves a cached Winston logger instance configured with rotating file transports, UTC timestamps, and optional crash capture. ```APIDOC ## createLogger ### Description Creates a fully configured Winston logger instance with rotating file transports, UTC timestamps, optional timezone mirrors, and optional crash capture. Instances are cached by `moduleName` + `logDirectory`. ### Signature `function createLogger(options?: LoggerOptions): winston.Logger` ### Parameters - **options** (LoggerOptions) - Optional - Configuration object for logger behavior - **options.moduleName** (string) - Optional - Label used in log lines and for module-specific files - **options.logDirectory** (string) - Optional - Target directory for log files - **options.level** (LogLevel) - Optional - Default severity level - **options.consoleLevel** (LogLevel) - Optional - Console-specific level override - **options.includeConsole** (boolean) - Optional - Enables console logging - **options.includeFile** (boolean) - Optional - Enables module-specific rotating file logging - **options.includeGlobalFile** (boolean) - Optional - Enables shared rotating file logging - **options.globalModuleName** (string) - Optional - Label for the shared global log file - **options.extraTimezones** (string | string[]) - Optional - Additional IANA timezone identifiers - **options.rotation** (RotationStrategy) - Optional - Rotation config for module-scoped file - **options.globalRotation** (RotationStrategy) - Optional - Override rotation for shared file - **options.additionalTransports** (winston.transport[]) - Optional - Custom Winston transports - **options.onTransportError** (function) - Optional - Callback for transport errors - **options.clock** (function) - Optional - Clock injection point for testing - **options.captureUncaught** (boolean) - Optional - Register with process-wide crash capture - **options.exitOnUncaught** (boolean) - Optional - Exit process after capturing fatal - **options.colorize** (boolean | object) - Optional - ANSI colorization control - **options.maskMetaKeys** (string[]) - Optional - Metadata keys to redact - **options.format** ("pretty" | "json") - Optional - Output format - **options.escapeMessageNewlines** (boolean) - Optional - Escape newlines in messages ### Return Value Returns a `winston.Logger` instance. ### Throws - `InvalidTimezoneError` - Invalid IANA identifier - `LoggerOptionError` - Configuration validation errors (INVALID_LEVEL, INVALID_ROTATION, LOG_DIRECTORY_UNWRITABLE, INVALID_FORMAT, INVALID_MASK) - `TypeError` - Invalid additional transports ``` -------------------------------- ### Standard Winston Logging Methods Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Standard npm log-level methods supported by all logger instances. ```typescript logger.error(message?: string, meta?: any): winston.Logger logger.warn(message?: string, meta?: any): winston.Logger logger.info(message?: string, meta?: any): winston.Logger logger.http(message?: string, meta?: any): winston.Logger // level 3 logger.verbose(message?: string, meta?: any): winston.Logger // level 4 logger.debug(message?: string, meta?: any): winston.Logger logger.silly(message?: string, meta?: any): winston.Logger logger.log(level: LogLevel, message?: string, meta?: any): winston.Logger ``` -------------------------------- ### Configure HTTP Logger and Request Middleware Source: https://github.com/hiprax/logger/blob/main/README.md Sets up a logger with the 'http' level and configures the request middleware to emit logs at that same level. ```ts const httpLogger = createLogger({ moduleName: "http", level: "http" }); app.use(createRequestLogger({ logger: httpLogger, level: () => "http" })); ``` -------------------------------- ### Configure Request Logger Levels Source: https://github.com/hiprax/logger/blob/main/_autodocs/endpoints.md Demonstrates how to set a static log level or a dynamic function to determine the log level based on the HTTP status code. ```typescript createRequestLogger({ level: "info" }) // always info createRequestLogger({ level: (statusCode) => statusCode >= 500 ? "error" : "info", }) ``` -------------------------------- ### Define REQUEST_START_SYMBOL Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-request-logger.md The symbol is created using Symbol.for to ensure consistency across multiple package instances. ```typescript const REQUEST_START_SYMBOL: unique symbol = Symbol.for("hiprax.request.start") ``` -------------------------------- ### Configure HTTP Middleware Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Utilities for integrating request and response logging into HTTP middleware stacks. ```typescript // Create request/response logging middleware createRequestLogger(options?: RequestLoggerOptions): LoggableMiddleware // Symbol for overriding middleware start timestamp const REQUEST_START_SYMBOL: unique symbol ``` -------------------------------- ### Configure Custom Logging Mode Source: https://github.com/hiprax/logger/blob/main/README.md Define custom environment variable sources and allowed values to control logging activation. ```ts createRequestLogger({ loggingMode: { sources: ["DEPLOYMENT_STAGE"], // env vars to check (priority order) allow: ["staging", "qa"], // values that enable logging fallback: false, // behavior when no env source is found }, }); ``` -------------------------------- ### createRequestLogger Source: https://github.com/hiprax/logger/blob/main/README.md Initializes the request logger with custom environment-aware logging modes. ```APIDOC ## createRequestLogger ### Description Configures the request logging behavior based on environment variables. ### Parameters - **loggingMode** (object) - Optional - Configuration for environment-aware logging. - **sources** (array) - Required - List of environment variables to check. - **allow** (array) - Required - Values that enable logging. - **fallback** (boolean) - Required - Behavior when no env source is found. ### Request Example ```ts createRequestLogger({ loggingMode: { sources: ["DEPLOYMENT_STAGE"], allow: ["staging", "qa"], fallback: false, }, }); ``` ``` -------------------------------- ### Configure logger rotation Source: https://github.com/hiprax/logger/blob/main/_autodocs/types.md Demonstrates using default rotation settings, overriding specific fields, and creating mutable copies. ```typescript import { createLogger, defaultRotation, getDefaultRotation } from "@hiprax/logger"; // Use frozen default const logger1 = createLogger({ rotation: defaultRotation, }); // Spread to override one field const logger2 = createLogger({ rotation: { ...defaultRotation, maxFiles: "30d" }, }); // Get mutable copy const rotation = getDefaultRotation(); rotation.maxFiles = "30d"; rotation.zippedArchive = true; const logger3 = createLogger({ rotation }); ``` -------------------------------- ### Implement Multi-Module Logging Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Create separate logger instances for different modules to enable both module-scoped and shared global log files. ```typescript // auth.ts const authLogger = createLogger({ moduleName: "auth" }); // db.ts const dbLogger = createLogger({ moduleName: "db" }); // api.ts const apiLogger = createLogger({ moduleName: "api" }); // All write to: // - Module-scoped files: auth-YYYY-MM-DD.log, db-YYYY-MM-DD.log, api-YYYY-MM-DD.log // - Shared global file: all-logs-YYYY-MM-DD.log ``` -------------------------------- ### createNoopLogger() Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Creates a silent no-op logger singleton. ```APIDOC ## createNoopLogger() ### Description Creates a silent logger singleton that performs no operations, useful for testing or disabling logging. ### Signature `createNoopLogger(): Logger` ``` -------------------------------- ### Configure Context and Message Building Source: https://github.com/hiprax/logger/blob/main/_autodocs/configuration.md Customizes the log entry content via enrichment, message formatting, and request filtering. ```typescript createRequestLogger({ // Inject extra context into the log entry enrich: (req, res, durationMs) => { return { tenantId: req.headers["x-tenant-id"], userId: (req as any).user?.id, durationMs, }; }, // Custom log message (default: "METHOD URL STATUS DURATIONms (EVENT)") messageBuilder: (entry) => { return `${entry.method} ${entry.url} → ${entry.statusCode} (${entry.responseTimeMs.toFixed(2)}ms) [${entry.event}]`; }, // Skip logging for specific requests skip: (req, res) => { return req.url === "/health" || req.url === "/metrics"; }, }) ``` -------------------------------- ### Configure Environment-Aware Logging Source: https://github.com/hiprax/logger/blob/main/_autodocs/endpoints.md Controls logging behavior based on environment settings evaluated at middleware creation. ```typescript // Log only in production createRequestLogger({ loggingMode: "prod-only" }) // Log in dev or staging createRequestLogger({ loggingMode: { sources: ["DEPLOYMENT_STAGE"], allow: ["dev", "staging"], fallback: false, }, }) ``` -------------------------------- ### Promtail Configuration for Loki Source: https://github.com/hiprax/logger/blob/main/README.md Configure Promtail to scrape logs and parse JSON fields into labels for Grafana Loki. ```yaml # /etc/promtail/config.yml scrape_configs: - job_name: api static_configs: - targets: [localhost] labels: job: api __path__: /var/log/myapp/api-*.log pipeline_stages: - json: expressions: level: level timestamp: timestamp userId: userId - timestamp: source: timestamp format: 2006-01-02 15:04:05 location: UTC - labels: level: ``` -------------------------------- ### Datadog Agent Configuration Source: https://github.com/hiprax/logger/blob/main/README.md Configure the Datadog Agent to tail log files and process them as NDJSON. ```yaml # /etc/datadog-agent/conf.d/api.d/conf.yaml logs: - type: file path: /var/log/myapp/api-*.log service: api source: nodejs sourcecategory: hiprax-logger log_processing_rules: - type: multi_line name: ndjson_per_line pattern: \{ ``` -------------------------------- ### Configure Output Format Source: https://github.com/hiprax/logger/blob/main/_autodocs/configuration.md Sets the serialization format for log entries. JSON format is recommended for integration with log aggregation services. ```typescript createLogger({ // Pretty-print (human-readable, default) format: "pretty", // Newline-delimited JSON (NDJSON / JSON-Lines) // Suitable for Datadog, Loki, ELK, Splunk, Vector format: "json", }) ``` -------------------------------- ### HTTP Middleware Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Utilities for integrating logging into HTTP request/response cycles. ```APIDOC ## createRequestLogger(options?: RequestLoggerOptions) ### Description Creates a request/response logging middleware. ### Parameters - **options** (RequestLoggerOptions) - Optional - Configuration for the request logger. ``` -------------------------------- ### createRequestLogger Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-request-logger.md Creates an HTTP request/response logging middleware compatible with standard framework signatures. ```APIDOC ## createRequestLogger ### Description Creates an HTTP request/response logging middleware compatible with Express, Fastify, Koa, or any framework that uses the standard `(req, res, next)` signature. The middleware logs at `info`/`warn`/`error` depending on response status, supports header/body redaction, request-body truncation, and structured payloads for log shippers. ### Signature `function createRequestLogger(options?: RequestLoggerOptions): LoggableMiddleware` ### Parameters - **options** (RequestLoggerOptions) - Optional - Configuration object - **logger** (winston.Logger) - Optional - Custom logger instance - **level** (LogLevel | (statusCode: number) => LogLevel) - Optional - Override severity - **label** (string) - Optional - Appended to the auto-generated logger name - **messageBuilder** (function) - Optional - Custom function to build the final message string - **skip** (function) - Optional - Return true to skip logging for specific requests - **enrich** (function) - Optional - Inject extra context into the log entry - **includeRequestHeaders** (boolean | string[]) - Optional - Include request headers - **includeResponseHeaders** (boolean | string[]) - Optional - Include response headers - **includeRequestBody** (boolean) - Optional - Logs parsed request body - **maskBodyKeys** (string[]) - Optional - Keys replaced with [REDACTED] - **maskHeaderKeys** (string[] | false) - Optional - Header values to redact - **maskQueryKeys** (string[] | false) - Optional - Query-string param values to redact - **redactPaths** (string[]) - Optional - Dot-notation paths for surgical redaction - **maxBodyLength** (number) - Optional - Truncate serialized body length - **includeHttpContext** (boolean) - Optional - Attach structured RequestLogEntry payload - **loggingEnabled** (boolean) - Optional - Hard enable/disable switch - **loggingMode** (RequestLoggingMode) - Optional - Environment-aware control ### Return Value Returns a middleware function `(req, res, next) => void` that captures request metadata and logs the HTTP exchange upon completion. ### Throws - `RequestLoggerOptionError` (INVALID_LEVEL): When level is not in the npm-levels union. - `RequestLoggerOptionError` (INVALID_MASK): When mask option is not an array of strings or false. - `RequestLoggerOptionError` (INVALID_BODY_LIMIT): When maxBodyLength is not a positive number or Infinity. ``` -------------------------------- ### Filebeat Configuration for ELK Source: https://github.com/hiprax/logger/blob/main/README.md Configure Filebeat to parse NDJSON logs and ship them to Elasticsearch. ```yaml # /etc/filebeat/filebeat.yml filebeat.inputs: - type: filestream paths: - /var/log/myapp/api-*.log parsers: - ndjson: target: "" add_error_key: true processors: - timestamp: field: timestamp layouts: - "2006-01-02 15:04:05" timezone: UTC output.elasticsearch: hosts: ["localhost:9200"] ``` -------------------------------- ### Import logger in CommonJS Source: https://github.com/hiprax/logger/blob/main/README.md Use this syntax when working in environments that require CommonJS module loading. ```js const { createLogger } = require("@hiprax/logger"); ``` -------------------------------- ### Logger Management Methods Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Methods for creating, retrieving, and shutting down logger instances. ```APIDOC ## createLogger(options?: LoggerOptions) ### Description Creates or retrieves a cached logger instance. ### Parameters - **options** (LoggerOptions) - Optional - Configuration options for the logger. ## createNoopLogger() ### Description Creates a silent no-op logger singleton. ## resetLoggerRegistry() ### Description Clears the internal logger cache. ## shutdownLogger(logger: winston.Logger, options?: ShutdownOptions) ### Description Gracefully flushes a specific logger instance. ## shutdownAllLoggers(options?: ShutdownOptions) ### Description Flushes all cached loggers. ``` -------------------------------- ### createRequestLogger Source: https://github.com/hiprax/logger/blob/main/_autodocs/endpoints.md Initializes the request logger middleware with specific options for body handling and environment-based activation. ```APIDOC ## createRequestLogger(options) ### Description Initializes the request logger middleware. It supports body truncation to prevent log-flood attacks and environment-aware logging modes. ### Parameters - **includeRequestBody** (boolean) - Optional - Whether to include the request body in logs. - **maxBodyLength** (number | Infinity) - Optional - Maximum length for request bodies. Defaults to 3000. Truncates strings or replaces objects/arrays with a summary object if exceeded. - **loggingMode** (string | object) - Optional - Controls when logging is active. Can be a string ('prod-only') or an object defining sources, allowed values, and a fallback behavior. ### Usage Example ```typescript createRequestLogger({ includeRequestBody: true, maxBodyLength: 3000, loggingMode: "prod-only" }) ``` ``` -------------------------------- ### Configuring Package Exports Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md The package exports configuration for dual-module resolution, ensuring correct type declarations for both ESM and CJS consumers. ```json { "exports": { ".": { "import": { "types": "./dist/index.d.ts", "default": "./dist/index.mjs" }, "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } } } } ``` -------------------------------- ### Configure Environment-Aware Logging Source: https://github.com/hiprax/logger/blob/main/_autodocs/configuration.md Controls logging behavior based on environment presets or custom environment variable checks. ```typescript // Built-in presets createRequestLogger({ loggingMode: "always" }); // always log createRequestLogger({ loggingMode: "never" }); // never log createRequestLogger({ loggingMode: "dev-only" }); // log in dev/development/local createRequestLogger({ loggingMode: "prod-only" }); // log in prod/production/live createRequestLogger({ loggingMode: "test-only" }); // log in test/testing/qa/staging // Custom configuration createRequestLogger({ loggingMode: { sources: ["DEPLOYMENT_STAGE"], // env vars to check (priority order) allow: ["staging", "qa"], // case-insensitive values that enable logging fallback: false, // behavior when no env vars found }, }) // Hard override (checks first, before loggingMode) createRequestLogger({ loggingEnabled: process.env.LOG_REQUESTS === "true", }) ``` -------------------------------- ### Configure logger with redaction and timezones Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Enable metadata masking for sensitive keys and track multiple timezones. ```typescript const logger = createLogger({ moduleName: "security/failedLogins", extraTimezones: ["Europe/London", "America/New_York"], maskMetaKeys: ["password", "apiKey"], level: "info", }); logger.error("Login failed", { email: "user@example.com", password: "secret123", apiKey: "key-xyz", }); // Output includes password and apiKey as "[REDACTED]" ``` -------------------------------- ### Define RotationStrategy interface Source: https://github.com/hiprax/logger/blob/main/_autodocs/types.md Configuration schema for daily file rotation settings. ```typescript interface RotationStrategy { maxSize?: string; maxFiles?: string; datePattern?: string; zippedArchive?: boolean; } ``` -------------------------------- ### Configure JSON output for log shippers Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Set the output format to JSON and define keys to mask for log aggregation services. ```typescript const logger = createLogger({ moduleName: "api", format: "json", maskMetaKeys: ["authorization"], }); logger.info("Request processed", { userId: 42, authorization: "Bearer token" }); // Outputs: {"level":"info","message":"Request processed","timestamp":"2026-07-18 14:30:22","module":"api","userId":42,"authorization":"[REDACTED]"} ``` -------------------------------- ### Default rotation configuration object Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Displays the default values assigned to the RotationStrategy object. ```json { maxSize: "20m", maxFiles: "14d", datePattern: "YYYY-MM-DD", zippedArchive: false } ``` -------------------------------- ### Define custom context and message format Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-request-logger.md Use enrich and messageBuilder to inject custom metadata and define the log message structure. ```typescript app.use( createRequestLogger({ enrich: (req, res, durationMs) => ({ tenantId: req.headers["x-tenant-id"], userId: (req as any).user?.id, durationMs, }), messageBuilder: (entry) => `${entry.method} ${entry.url} → ${entry.statusCode} (${entry.responseTimeMs.toFixed(2)}ms)`, includeHttpContext: true, }), ); ``` -------------------------------- ### Configure JSON Output for Log Shippers Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Enable NDJSON formatting for compatibility with log aggregation services like Datadog or ELK. ```typescript const logger = createLogger({ moduleName: "api", format: "json", maskMetaKeys: ["password", "apiKey"], }); // Each line is valid NDJSON for Datadog, Loki, ELK, Splunk, Vector, etc. logger.info("Request processed", { userId: 42, status: "success" }); ``` -------------------------------- ### Per-logger shutdown in cleanup Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Shows how to shut down multiple specific logger instances concurrently using Promise.all. ```typescript const authLogger = createLogger({ moduleName: "auth" }); const dbLogger = createLogger({ moduleName: "db" }); // At application exit try { await Promise.all([ shutdownLogger(authLogger), shutdownLogger(dbLogger), ]); console.log("All loggers flushed"); } catch (err) { console.error("Flush failed:", err); } ``` -------------------------------- ### Configuring Log Directory Source: https://github.com/hiprax/logger/blob/main/_autodocs/configuration.md Override the default log directory path by passing an explicit option to createLogger or by reading from environment variables. ```typescript // Default: /logs // Override with explicit option: createLogger({ logDirectory: "/var/log/myapp" }) // Or read from environment if desired: createLogger({ logDirectory: process.env.LOG_DIR || "/var/log/myapp", }) ``` -------------------------------- ### Configure Header and Body Logging Source: https://github.com/hiprax/logger/blob/main/_autodocs/configuration.md Controls which headers and body content are included in logs, including size limits for the request body. ```typescript createRequestLogger({ // Include all request headers includeRequestHeaders: true, // Include specific request headers (allow-list) includeRequestHeaders: ["authorization", "x-tenant-id"], // Same for response headers includeResponseHeaders: ["content-type", "cache-control"], // Include parsed request body includeRequestBody: true, // Limit serialized body size (default: 3000 characters) maxBodyLength: 5000, // Unlimited body logging maxBodyLength: Infinity, }) ``` -------------------------------- ### createLogger() Source: https://github.com/hiprax/logger/blob/main/_autodocs/README.md Creates or retrieves a cached logger instance. ```APIDOC ## createLogger() ### Description Creates a new logger instance or retrieves an existing one from the internal cache. ### Signature `createLogger(): Logger` ``` -------------------------------- ### Configure module-scoped logger Source: https://github.com/hiprax/logger/blob/main/_autodocs/api-reference-logger.md Initialize a logger with a specific module name, custom log directory, and debug level. ```typescript const authLogger = createLogger({ moduleName: "auth", logDirectory: "/var/log/myapp", level: "debug", }); authLogger.warn("Suspicious login attempt", { ip: "192.168.1.1" }); ``` -------------------------------- ### RequestLoggerOptions Source: https://github.com/hiprax/logger/blob/main/_autodocs/types.md Configuration object passed to createRequestLogger() to control logging behavior. ```APIDOC ## RequestLoggerOptions ### Description Configuration object passed to createRequestLogger(). Controls what is logged, how it is redacted, and in which environments. ### Fields - **logger** (winston.Logger) - Optional - Custom logger or auto-created http/