@tanngo11/log 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/strapi.ts","../src/context.ts","../src/global.ts","../src/redact.ts","../src/error.ts","../src/normalize.ts","../src/request-id.ts","../src/http.ts"],"sourcesContent":["import { Writable } from \"node:stream\";\nimport { currentStore, recordErrorIn, runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, newRequestId, parseTraceparent, REQUEST_ID_RE, type HttpLogOptions } from \"./http\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\n/** The parts of a Koa/Strapi context the middlewares use. */\nexport interface KoaContextLike {\n method: string;\n url: string;\n status: number;\n state: Record<string, unknown>;\n get(name: string): string;\n set(name: string, value: string): void;\n /** Full matched route template, set by @koa/router (includes router prefixes such as /api). */\n _matchedRoute?: unknown;\n}\n\nexport type KoaMiddleware = (ctx: KoaContextLike, next: () => Promise<unknown>) => Promise<void>;\n\nexport interface StrapiRequestLoggerOptions extends HttpLogOptions {\n log: Logger;\n /**\n * Use a valid incoming x-request-id as request_id. Off by default: the server issues its own\n * id (Strapi apps often use it for audit rows) and records the caller's id as\n * upstream_request_id, which still links the logs of both services.\n */\n trustIncomingRequestId?: boolean;\n /** ctx.state key shared with the app's own correlation middleware. Default \"requestId\". */\n stateKey?: string;\n}\n\nfunction routeOf(ctx: KoaContextLike): string | undefined {\n if (typeof ctx._matchedRoute === \"string\") return ctx._matchedRoute;\n const path = (ctx.state.route as { path?: unknown } | undefined)?.path;\n return typeof path === \"string\" ? path : undefined;\n}\n\n/**\n * Replaces 'strapi::logger' (put it first in config/middlewares): opens the request context and\n * writes one http.request line per request.\n */\nexport function strapiRequestLogger(opts: StrapiRequestLoggerOptions): KoaMiddleware {\n const stateKey = opts.stateKey ?? \"requestId\";\n return async (ctx, next) => {\n const incoming = ctx.get(\"x-request-id\");\n const caller = incoming && REQUEST_ID_RE.test(incoming) ? incoming : undefined;\n const existing = ctx.state[stateKey];\n const requestId =\n typeof existing === \"string\" && existing ? existing : opts.trustIncomingRequestId && caller ? caller : newRequestId();\n // A UUID v4 here is kept by correlation middlewares that only replace invalid ids.\n if (ctx.state[stateKey] === undefined) ctx.state[stateKey] = requestId;\n ctx.set(\"X-Request-ID\", requestId);\n\n const fields: Fields = { request_id: requestId };\n if (caller && caller !== requestId) fields.upstream_request_id = caller;\n const trace = parseTraceparent(ctx.get(\"traceparent\"));\n if (trace) Object.assign(fields, trace);\n\n const start = performance.now();\n await runWithStore(fields, async (store) => {\n let failed = false;\n try {\n await next();\n } catch (err) {\n // Only reached when no error middleware handled it; Koa answers 500.\n failed = true;\n recordErrorIn(store, err);\n throw err;\n } finally {\n logHttpRequest(\n opts.log,\n {\n method: ctx.method,\n route: routeOf(ctx),\n path: ctx.url,\n status: failed ? 500 : ctx.status,\n duration_ms: performance.now() - start,\n err: store.error,\n fields: store.fields,\n },\n opts,\n );\n }\n });\n };\n}\n\n/**\n * Put right after 'strapi::errors'. Records thrown errors on the request's http.request line and\n * marks them, so the copy strapi::errors logs through strapi.log.error is not written twice.\n */\nexport function strapiErrorCapture(): KoaMiddleware {\n return async (_ctx, next) => {\n try {\n await next();\n } catch (err) {\n const store = currentStore();\n if (store) recordErrorIn(store, err);\n markLogged(err);\n throw err;\n }\n };\n}\n\nconst LEVELS: Record<string, Level> = {\n error: \"error\",\n warn: \"warn\",\n info: \"info\",\n http: \"debug\",\n verbose: \"debug\",\n debug: \"debug\",\n silly: \"trace\",\n};\n\nconst META_SKIP = new Set([\"level\", \"message\", \"stack\"]);\n\nfunction forward(log: Logger, info: Record<string, unknown>): void {\n // Already carried by the request's http.request line (see strapiErrorCapture).\n if (isErrorLike(info) && isLogged(info)) return;\n const level = LEVELS[String(info.level)] ?? \"info\";\n const fields: Fields = {};\n for (const [key, value] of Object.entries(info)) if (!META_SKIP.has(key)) fields[key] = value;\n\n let message: unknown = info.message;\n if (isErrorLike(info)) {\n fields.err = info;\n } else if (isErrorLike(message)) {\n if (isLogged(message)) return;\n fields.err = message;\n message = message.message;\n } else if (typeof info.stack === \"string\") {\n fields.err_stack = info.stack;\n }\n if ((level === \"warn\" || level === \"error\") && fields.event === undefined) fields.event = \"strapi.log\";\n log[level](typeof message === \"string\" ? message : String(message ?? \"\"), fields);\n}\n\n/**\n * Winston configuration for Strapi's config/logger.ts: every strapi.log.* call (app code and\n * framework) becomes a contract JSON line with the request context. Level filtering is left to\n * the logger (LOG_LEVEL).\n */\nexport function strapiLoggerConfig(log: Logger) {\n const transport = new Writable({\n objectMode: true,\n write(info: Record<string, unknown>, _encoding, callback) {\n try {\n forward(log, info);\n } finally {\n callback();\n }\n },\n });\n // winston requires a `log(info, callback)` method on stream transports; writes go through write().\n Object.assign(transport, {\n log(info: Record<string, unknown>, callback: () => void) {\n forward(log, info);\n callback();\n },\n });\n return {\n level: \"silly\",\n // Identity format: replaces Strapi's prettyPrint so the transport receives raw info objects.\n format: { transform: <T>(info: T): T => info },\n transports: [transport],\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { globalSingleton } from \"./global\";\nimport type { Fields } from \"./normalize\";\n\nexport interface ContextStore {\n fields: Fields;\n error?: unknown;\n /** Route template captured while the router still knew it (Express error path). */\n route?: string;\n parent?: ContextStore;\n}\n\nconst als = globalSingleton(\"als\", () => new AsyncLocalStorage<ContextStore>());\n\nexport const STORE_KEY: symbol = Symbol.for(\"@tanngo11/log.store\");\n\nexport function runWithStore<T>(fields: Fields, fn: (store: ContextStore) => T): T {\n const parent = als.getStore();\n const store: ContextStore = { fields: { ...parent?.fields, ...fields }, parent };\n return als.run(store, () => fn(store));\n}\n\nexport function withContext<T>(fields: Fields, fn: () => T): T {\n return runWithStore(fields, () => fn());\n}\n\nexport function currentStore(): ContextStore | undefined {\n return als.getStore();\n}\n\nexport function getContext(): Fields {\n return als.getStore()?.fields ?? {};\n}\n\n// Applies to the current context and every enclosing one, so a field added inside a nested\n// withContext/runJob still reaches the request's http.request line.\nexport function addContext(fields: Fields): void {\n for (let s = als.getStore(); s; s = s.parent) Object.assign(s.fields, fields);\n}\n\n// Sets the error on the store and on enclosing stores that have none yet.\nexport function recordErrorIn(store: ContextStore, err: unknown): void {\n store.error = err;\n for (let s = store.parent; s; s = s.parent) if (s.error === undefined) s.error = err;\n}\n\n// Marks the error that the current request/job summary line should carry. Does not write a line.\nexport function recordError(err: unknown): void {\n const store = als.getStore();\n if (store) recordErrorIn(store, err);\n}\n\nexport function attachStore(target: object, store: ContextStore): void {\n (target as Record<symbol, ContextStore>)[STORE_KEY] = store;\n}\n\nexport function storeOf(target: unknown): ContextStore | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n return (target as Record<symbol, ContextStore | undefined>)[STORE_KEY];\n}\n","// Singletons shared by every copy of this package loaded in the process (ESM and CJS builds,\n// or duplicated installs), so context and dedupe state never split.\nexport function globalSingleton<T>(name: string, make: () => T): T {\n const key = Symbol.for(`@tanngo11/log.${name}`);\n const g = globalThis as unknown as Record<symbol, T | undefined>;\n let value = g[key];\n if (value === undefined) {\n value = make();\n g[key] = value;\n }\n return value;\n}\n","// Redaction shared by the logger and the error serializer. The collector redacts again,\n// but it cannot see secrets inside JSON-encoded strings, so the app side must catch them.\n\nexport const DEFAULT_REDACT_KEYS = [\n \"password\", \"passwd\", \"pwd\", \"passphrase\", \"secret\", \"client_secret\",\n \"token\", \"access_token\", \"refresh_token\", \"id_token\", \"auth_token\",\n \"api_key\", \"apikey\", \"access_key\", \"secret_key\", \"private_key\",\n \"authorization\", \"cookie\", \"set_cookie\", \"session_id\", \"sessionid\",\n \"credential\", \"credentials\", \"dsn\", \"connection_string\", \"conn_string\", \"jwt\", \"bearer\",\n];\n\n/** Opt-in value patterns for `redactValues`. Not on by default: they can hit ordinary numbers. */\nexport const REDACT_PATTERNS = {\n /** Vietnamese mobile numbers: 0912345678, +84912345678, 84912345678. */\n phoneVN: /(?<![\\d+])(?:\\+?84|0)[35789]\\d{8}(?!\\d)/g,\n /** Visa, Mastercard, Amex, Discover-like card numbers, with optional spaces or dashes. */\n paymentCard: /(?<!\\d)(?:4\\d{3}|5[1-5]\\d{2}|2[2-7]\\d{2}|3[47]\\d{2}|6(?:011|5\\d{2}))(?:[ -]?\\d{4}){2}[ -]?\\d{1,4}(?!\\d)/g,\n /** IPv4 addresses. */\n ipv4: /(?<![\\d.])(?:\\d{1,3}\\.){3}\\d{1,3}(?![\\d.])/g,\n} as const;\n\n// Keys that only describe a secret (count, type, timestamps, flags) stay readable.\nconst SAFE_SUFFIXES = [\"_count\", \"_type\", \"_length\", \"_expires_at\", \"_expires_in\", \"_ttl\", \"_at\", \"_ms\", \"_enabled\"];\n\nexport const REDACTED = \"[REDACTED]\";\n\nexport function toSnakeCase(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase();\n}\n\nconst URL_CREDENTIALS_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/@:\"']+:[^\\s/@\"']+@/gi;\nconst BEARER_RE = /\\bBearer\\s+[A-Za-z0-9._~+/=-]+/gi;\nconst JWT_RE = /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,})/g;\n\nexport type KeyPattern = string | RegExp;\n\nexport interface RedactorOptions {\n /** Extra sensitive keys: names (matched like the defaults) or patterns tested on the snake_case key. */\n keys?: readonly KeyPattern[];\n /** Extra value patterns; every match inside any string becomes [REDACTED]. */\n values?: readonly RegExp[];\n}\n\nexport interface Redactor {\n isSensitive(key: string): boolean;\n /** Masks secrets and emails that appear inside free text. */\n scrub(s: string): string;\n /** JSON.stringify that redacts sensitive keys at any depth and never throws. */\n json(value: unknown): string;\n}\n\nfunction globalize(re: RegExp): RegExp {\n return re.flags.includes(\"g\") ? new RegExp(re.source, re.flags) : new RegExp(re.source, `${re.flags}g`);\n}\n\nexport function createRedactor(opts: RedactorOptions = {}): Redactor {\n const words = [...DEFAULT_REDACT_KEYS];\n const keyPatterns: RegExp[] = [];\n for (const k of opts.keys ?? []) {\n if (typeof k === \"string\") words.push(toSnakeCase(k));\n else keyPatterns.push(new RegExp(k.source, k.flags.replace(\"g\", \"\")));\n }\n const valuePatterns = (opts.values ?? []).map(globalize);\n\n const isSensitive = (key: string): boolean => {\n const k = toSnakeCase(key);\n if (keyPatterns.some((re) => re.test(k))) return true;\n if (!words.includes(k) && SAFE_SUFFIXES.some((s) => k.endsWith(s))) return false;\n return words.some((w) => k === w || k.startsWith(`${w}_`) || k.endsWith(`_${w}`) || k.includes(`_${w}_`));\n };\n\n const scrub = (s: string): string => {\n let out = s\n .replace(URL_CREDENTIALS_RE, `$1${REDACTED}@`)\n .replace(BEARER_RE, `Bearer ${REDACTED}`)\n .replace(JWT_RE, \"[REDACTED_JWT]\")\n .replace(EMAIL_RE, \"***@$1\");\n for (const re of valuePatterns) out = out.replace(re, REDACTED);\n return out;\n };\n\n const json = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n const text = JSON.stringify(value, (key, val: unknown) => {\n if (key && val !== null && val !== undefined && isSensitive(key)) return REDACTED;\n if (typeof val === \"bigint\") return val.toString();\n if (val instanceof Error) return { name: val.name, message: val.message };\n return val;\n });\n return text ?? String(value);\n } catch {\n return String(value);\n }\n };\n\n return { isSensitive, scrub, json };\n}\n\nexport const defaultRedactor: Redactor = createRedactor();\n","import { globalSingleton } from \"./global\";\nimport { defaultRedactor } from \"./redact\";\n\nexport interface ErrFields {\n err_type?: string;\n err_message?: string;\n err_code?: string;\n err_stack?: string;\n err_cause?: string;\n}\n\nconst MAX_CAUSE_DEPTH = 5;\n\nexport function isErrorLike(v: unknown): v is Error {\n if (v instanceof Error) return true;\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { message?: unknown }).message === \"string\" &&\n (\"stack\" in v || \"name\" in v)\n );\n}\n\nfunction errorType(e: Error): string {\n if (e.name && e.name !== \"Error\") return e.name;\n const ctor = (e as { constructor?: { name?: string } }).constructor?.name;\n return ctor && ctor !== \"Object\" ? ctor : \"Error\";\n}\n\nexport function serializeError(err: unknown): ErrFields {\n if (!isErrorLike(err)) {\n if (typeof err === \"string\") return { err_type: \"string\", err_message: err };\n return { err_type: typeof err, err_message: defaultRedactor.json(err) };\n }\n const e = err as Error & { code?: unknown; cause?: unknown };\n const out: ErrFields = { err_type: errorType(e), err_message: String(e.message ?? \"\") };\n if (e.code !== undefined && e.code !== null) out.err_code = String(e.code);\n if (typeof e.stack === \"string\") out.err_stack = e.stack;\n\n const causes: string[] = [];\n let cause = e.cause;\n while (cause !== undefined && cause !== null && causes.length < MAX_CAUSE_DEPTH) {\n if (isErrorLike(cause)) {\n causes.push(`${errorType(cause)}: ${cause.message}`);\n cause = (cause as { cause?: unknown }).cause;\n } else {\n causes.push(defaultRedactor.json(cause));\n cause = undefined;\n }\n }\n if (causes.length > 0) out.err_cause = causes.join(\" <- \");\n return out;\n}\n\nconst logged = globalSingleton(\"logged\", () => new WeakSet<object>());\n\n// Marks an error as already written, so a later boundary (e.g. Next's onRequestError)\n// does not log it a second time.\nexport function markLogged(err: unknown): void {\n if (typeof err === \"object\" && err !== null) logged.add(err);\n}\n\nexport function isLogged(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && logged.has(err);\n}\n","import { isErrorLike, serializeError } from \"./error\";\nimport type { Level } from \"./levels\";\nimport { REDACTED, toSnakeCase, type Redactor } from \"./redact\";\n\nexport { DEFAULT_REDACT_KEYS, toSnakeCase } from \"./redact\";\n\n/** Final per-field hook: return a replacement, or undefined to drop the field. */\nexport type RedactHook = (key: string, value: Primitive) => unknown;\n\nexport type Fields = Record<string, unknown>;\nexport type Primitive = string | number | boolean | null;\nexport type LogRecord = Record<string, Primitive>;\n\nexport interface NormalizeOptions {\n snakeCase: boolean;\n redactor: Redactor;\n hook?: RedactHook;\n}\n\n// Fields the redact hook never sees, so every line keeps its level, message and event.\nconst HOOK_EXEMPT = new Set([\"level\", \"message\", \"event\"]);\n\n// Keys owned by Vector (overwritten or deleted on ingest) or by the logger itself.\nexport const RESERVED_KEYS = new Set([\n \"project\", \"service\", \"vps\", \"version\", \"container_name\", \"container_id\", \"image\", \"stream\",\n \"_timestamp\", \"label\", \"host\", \"source_type\", \"msg\", \"lvl\", \"severity\", \"level\", \"message\",\n]);\n\nexport const MAX_LINE_BYTES = 16000;\nconst MAX_MESSAGE = 500;\nconst MAX_STACK = 4000;\nconst MAX_STRING = 1000;\nconst MAX_DEPTH = 3;\nconst TRUNCATED = \"…[truncated]\";\n\n// Fields kept when a line is too large.\nconst KEEP_ON_SHRINK = new Set([\n \"level\", \"message\", \"event\", \"request_id\", \"trace_id\", \"span_id\", \"job_name\", \"job_id\", \"job_attempt\",\n \"user_id\", \"tenant_id\", \"err_type\", \"err_message\", \"err_code\",\n]);\n\nexport function stripUrl(url: string): string {\n const noQuery = url.split(/[?#]/, 1)[0] ?? \"\";\n return noQuery.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]*@/i, \"$1\");\n}\n\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - TRUNCATED.length) + TRUNCATED : s;\n}\n\nfunction isPlainObject(v: unknown): v is Fields {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction isUrlKey(key: string): boolean {\n return key === \"http_path\" || key === \"http_url\" || key.endsWith(\"_url\");\n}\n\nfunction flattenInto(out: LogRecord, prefix: string, obj: Fields, depth: number, opts: NormalizeOptions): void {\n for (const [rawKey, value] of Object.entries(obj)) {\n const key = opts.snakeCase ? toSnakeCase(rawKey) : rawKey;\n const full = prefix ? `${prefix}_${key}` : key;\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") continue;\n if (value !== null && (opts.redactor.isSensitive(rawKey) || opts.redactor.isSensitive(full))) {\n out[full] = REDACTED;\n continue;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n out[full] = value;\n } else if (typeof value === \"number\") {\n out[full] = Number.isFinite(value) ? value : String(value);\n } else if (typeof value === \"bigint\") {\n out[full] = value.toString();\n } else if (value instanceof Date) {\n out[full] = Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n } else if (isErrorLike(value)) {\n out[full] = `${value.name}: ${value.message}`;\n } else if (isPlainObject(value) && depth < MAX_DEPTH - 1) {\n flattenInto(out, full, value, depth + 1, opts);\n } else {\n // Arrays, deep objects, class instances: stringified with sensitive keys redacted.\n out[full] = opts.redactor.json(value);\n }\n }\n}\n\nfunction finalize(key: string, value: Primitive, opts: NormalizeOptions): Primitive {\n if (typeof value !== \"string\") return value;\n const v = opts.redactor.scrub(isUrlKey(key) ? stripUrl(value) : value);\n return truncate(v, key === \"err_stack\" ? MAX_STACK : MAX_STRING);\n}\n\nexport function buildRecord(\n level: Level,\n message: unknown,\n sources: (Fields | undefined)[],\n opts: NormalizeOptions,\n): LogRecord {\n const merged: Fields = {};\n for (const source of sources) if (source) Object.assign(merged, source);\n\n let err: unknown;\n if (merged.err !== undefined && merged.err !== null) {\n err = merged.err;\n delete merged.err;\n } else if (isErrorLike(merged.error)) {\n err = merged.error;\n delete merged.error;\n }\n\n const flat: LogRecord = {};\n flattenInto(flat, \"\", merged, 0, opts);\n if (err !== undefined) Object.assign(flat, serializeError(err));\n\n const text = typeof message === \"string\" ? message : opts.redactor.json(message);\n const out: LogRecord = { level, message: truncate(opts.redactor.scrub(text), MAX_MESSAGE) };\n for (const [k, v] of Object.entries(flat)) {\n const key = RESERVED_KEYS.has(k) ? `app_${k}` : k;\n let value = finalize(key, v, opts);\n if (opts.hook && !HOOK_EXEMPT.has(key)) {\n const replaced = opts.hook(key, value);\n if (replaced === undefined) continue;\n value = typeof replaced === \"object\" && replaced !== null ? opts.redactor.json(replaced) : (replaced as Primitive);\n }\n out[key] = value;\n }\n return out;\n}\n\nfunction byteLength(s: string): number {\n // UTF-8 uses at most 3 bytes per UTF-16 code unit: skip encoding short lines.\n if (s.length * 3 <= MAX_LINE_BYTES) return s.length;\n return new TextEncoder().encode(s).length;\n}\n\nexport function serializeRecord(record: LogRecord): string {\n const line = JSON.stringify(record);\n if (byteLength(line) <= MAX_LINE_BYTES) return line;\n const small: LogRecord = {};\n for (const [k, v] of Object.entries(record)) {\n if (KEEP_ON_SHRINK.has(k) || k.startsWith(\"http_\")) small[k] = v;\n }\n small.log_truncated = true;\n return JSON.stringify(small);\n}\n","// No imports: this module is shared with the edge entry (next-edge).\nexport const REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport function newRequestId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction first(header?: string | string[] | null): string | undefined {\n return Array.isArray(header) ? header[0] : (header ?? undefined);\n}\n\nexport function resolveRequestId(header?: string | string[] | null): string {\n const value = first(header);\n return value && REQUEST_ID_RE.test(value) ? value : newRequestId();\n}\n\nexport function parseTraceparent(header?: string | string[] | null): { trace_id: string; span_id: string } | undefined {\n const value = first(header)?.trim().toLowerCase();\n const m = value ? TRACEPARENT_RE.exec(value) : null;\n if (!m) return undefined;\n const [, version, traceId, spanId] = m as unknown as [string, string, string, string];\n if (version === \"ff\" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined;\n return { trace_id: traceId, span_id: spanId };\n}\n","import { getContext } from \"./context\";\nimport { markLogged, serializeError } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport { stripUrl, type Fields } from \"./normalize\";\nimport { parseTraceparent, resolveRequestId } from \"./request-id\";\n\nexport { newRequestId, parseTraceparent, REQUEST_ID_RE, resolveRequestId } from \"./request-id\";\n\nexport type HeaderSource = Headers | Record<string, string | string[] | undefined>;\n\nfunction header(headers: HeaderSource, name: string): string | string[] | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n return (headers as Record<string, string | string[] | undefined>)[name];\n}\n\nexport function requestContextFields(headers: HeaderSource): { request_id: string; trace_id?: string; span_id?: string } {\n const out: { request_id: string; trace_id?: string; span_id?: string } = {\n request_id: resolveRequestId(header(headers, \"x-request-id\")),\n };\n const tp = parseTraceparent(header(headers, \"traceparent\"));\n if (tp) Object.assign(out, tp);\n return out;\n}\n\n// Headers to forward to services we own, so their logs share request_id / trace_id.\nexport function propagationHeaders(): Record<string, string> {\n const ctx = getContext();\n const out: Record<string, string> = {};\n if (typeof ctx.request_id === \"string\") out[\"x-request-id\"] = ctx.request_id;\n if (typeof ctx.trace_id === \"string\" && typeof ctx.span_id === \"string\") {\n out.traceparent = `00-${ctx.trace_id}-${ctx.span_id}-01`;\n }\n return out;\n}\n\nexport const DEFAULT_SKIP_PATHS: (string | RegExp)[] = [\n /^\\/(health|healthz|ready|readyz|livez)\\/?$/,\n \"/favicon.ico\",\n /^\\/_next\\/static\\//,\n];\n\nexport interface HttpLogOptions {\n skipPaths?: (string | RegExp)[];\n}\n\nexport interface HttpRequestInfo {\n method: string;\n route?: string;\n path: string;\n status: number;\n duration_ms?: number;\n err?: unknown;\n fields?: Fields;\n}\n\nexport function shouldSkip(method: string, path: string, skipPaths: (string | RegExp)[] = DEFAULT_SKIP_PATHS): boolean {\n if (method.toUpperCase() === \"OPTIONS\") return true;\n const p = stripUrl(path);\n return skipPaths.some((s) => (typeof s === \"string\" ? p === s : s.test(p)));\n}\n\n// Writes the one `http.request` summary line for an inbound request.\nexport function logHttpRequest(log: Logger, info: HttpRequestInfo, opts: HttpLogOptions = {}): void {\n if (shouldSkip(info.method, info.path, opts.skipPaths)) return;\n const level = info.status >= 500 ? \"error\" : info.status >= 400 ? \"warn\" : \"info\";\n const path = stripUrl(info.path);\n const errFields: Fields = {};\n if (info.err !== undefined && info.err !== null) {\n Object.assign(errFields, serializeError(info.err));\n if (info.status < 500) delete errFields.err_stack;\n markLogged(info.err);\n }\n // Route templates keep the message bounded; the raw path would make one message per URL.\n const message = info.route ? `${info.method} ${info.route} ${info.status}` : `${info.method} ${info.status}`;\n log[level](message, {\n ...info.fields,\n event: \"http.request\",\n http_method: info.method,\n http_route: info.route,\n http_path: path,\n http_status: info.status,\n duration_ms: info.duration_ms === undefined ? undefined : Math.round(info.duration_ms),\n ...errFields,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAyB;;;ACAzB,8BAAkC;;;ACE3B,SAAS,gBAAmB,MAAc,MAAkB;AACjE,QAAM,MAAM,uBAAO,IAAI,iBAAiB,IAAI,EAAE;AAC9C,QAAM,IAAI;AACV,MAAI,QAAQ,EAAE,GAAG;AACjB,MAAI,UAAU,QAAW;AACvB,YAAQ,KAAK;AACb,MAAE,GAAG,IAAI;AAAA,EACX;AACA,SAAO;AACT;;;ADCA,IAAM,MAAM,gBAAgB,OAAO,MAAM,IAAI,0CAAgC,CAAC;AAIvE,SAAS,aAAgB,QAAgB,IAAmC;AACjF,QAAM,SAAS,IAAI,SAAS;AAC5B,QAAM,QAAsB,EAAE,QAAQ,EAAE,GAAG,QAAQ,QAAQ,GAAG,OAAO,GAAG,OAAO;AAC/E,SAAO,IAAI,IAAI,OAAO,MAAM,GAAG,KAAK,CAAC;AACvC;AAMO,SAAS,eAAyC;AACvD,SAAO,IAAI,SAAS;AACtB;AAaO,SAAS,cAAc,OAAqB,KAAoB;AACrE,QAAM,QAAQ;AACd,WAAS,IAAI,MAAM,QAAQ,GAAG,IAAI,EAAE,OAAQ,KAAI,EAAE,UAAU,OAAW,GAAE,QAAQ;AACnF;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AG;AACzC,QAAM,QAAQ,OAAO,OAAO,KAAK,KAAK,CAAC,KAAK;AAC5C,QAAM,SAAiB,CAAC;AACxB,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,EAAG,KAAI,CAAC,UAAU,IAAI,GAAG,EAAG,QAAO,GAAG,IAAI;AAExF,MAAI,UAAmB,KAAK;AAC5B,MAAI,YAAY,IAAI,GAAG;AACrB,WAAO,MAAM;AAAA,EACf,WAAW,YAAY,OAAO,GAAG;AAC/B,QAAI,SAAS,OAAO,EAAG;AACvB,WAAO,MAAM;AACb,cAAU,QAAQ;AAAA,EACpB,WAAW,OAAO,KAAK,UAAU,UAAU;AACzC,WAAO,YAAY,KAAK;AAAA,EAC1B;AACA,OAAK,UAAU,UAAU,UAAU,YAAY,OAAO,UAAU,OAAW,QAAO,QAAQ;AAC1F,MAAI,KAAK,EAAE,OAAO,YAAY,WAAW,UAAU,OAAO,WAAW,EAAE,GAAG,MAAM;AAClF;AAOO,SAAS,mBAAmB,KAAa;AAC9C,QAAM,YAAY,IAAI,4BAAS;AAAA,IAC7B,YAAY;AAAA,IACZ,MAAM,MAA+B,WAAW,UAAU;AACxD,UAAI;AACF,gBAAQ,KAAK,IAAI;AAAA,MACnB,UAAE;AACA,iBAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF,CAAC;AAED,SAAO,OAAO,WAAW;AAAA,IACvB,IAAI,MAA+B,UAAsB;AACvD,cAAQ,KAAK,IAAI;AACjB,eAAS;AAAA,IACX;AAAA,EACF,CAAC;AACD,SAAO;AAAA,IACL,OAAO;AAAA;AAAA,IAEP,QAAQ,EAAE,WAAW,CAAI,SAAe,KAAK;AAAA,IAC7C,YAAY,CAAC,SAAS;AAAA,EACxB;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/strapi.ts","../src/context.ts","../src/global.ts","../src/redact.ts","../src/error.ts","../src/normalize.ts","../src/request-id.ts","../src/http.ts"],"sourcesContent":["import { Writable } from \"node:stream\";\nimport { currentStore, recordErrorIn, runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, newRequestId, parseTraceparent, REQUEST_ID_RE, type HttpLogOptions } from \"./http\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\n/** The parts of a Koa/Strapi context the middlewares use. */\nexport interface KoaContextLike {\n method: string;\n url: string;\n status: number;\n state: Record<string, unknown>;\n get(name: string): string;\n set(name: string, value: string): void;\n /** Full matched route template, set by @koa/router (includes router prefixes such as /api). */\n _matchedRoute?: unknown;\n}\n\nexport type KoaMiddleware = (ctx: KoaContextLike, next: () => Promise<unknown>) => Promise<void>;\n\nexport interface StrapiRequestLoggerOptions extends HttpLogOptions {\n log: Logger;\n /**\n * Use a valid incoming x-request-id as request_id. Off by default: the server issues its own\n * id (Strapi apps often use it for audit rows) and records the caller's id as\n * upstream_request_id, which still links the logs of both services.\n */\n trustIncomingRequestId?: boolean;\n /** ctx.state key shared with the app's own correlation middleware. Default \"requestId\". */\n stateKey?: string;\n}\n\nfunction routeOf(ctx: KoaContextLike): string | undefined {\n if (typeof ctx._matchedRoute === \"string\") return ctx._matchedRoute;\n const path = (ctx.state.route as { path?: unknown } | undefined)?.path;\n return typeof path === \"string\" ? path : undefined;\n}\n\n/**\n * Replaces 'strapi::logger' (put it first in config/middlewares): opens the request context and\n * writes one http.request line per request.\n */\nexport function strapiRequestLogger(opts: StrapiRequestLoggerOptions): KoaMiddleware {\n const stateKey = opts.stateKey ?? \"requestId\";\n return async (ctx, next) => {\n const incoming = ctx.get(\"x-request-id\");\n const caller = incoming && REQUEST_ID_RE.test(incoming) ? incoming : undefined;\n const existing = ctx.state[stateKey];\n const requestId =\n typeof existing === \"string\" && existing ? existing : opts.trustIncomingRequestId && caller ? caller : newRequestId();\n // A UUID v4 here is kept by correlation middlewares that only replace invalid ids.\n if (ctx.state[stateKey] === undefined) ctx.state[stateKey] = requestId;\n ctx.set(\"X-Request-ID\", requestId);\n\n const fields: Fields = { request_id: requestId };\n if (caller && caller !== requestId) fields.upstream_request_id = caller;\n const trace = parseTraceparent(ctx.get(\"traceparent\"));\n if (trace) Object.assign(fields, trace);\n\n const start = performance.now();\n await runWithStore(fields, async (store) => {\n let failed = false;\n try {\n await next();\n } catch (err) {\n // Only reached when no error middleware handled it; Koa answers 500.\n failed = true;\n recordErrorIn(store, err);\n throw err;\n } finally {\n logHttpRequest(\n opts.log,\n {\n method: ctx.method,\n route: routeOf(ctx),\n path: ctx.url,\n status: failed ? 500 : ctx.status,\n duration_ms: performance.now() - start,\n err: store.error,\n fields: store.fields,\n },\n opts,\n );\n }\n });\n };\n}\n\n/**\n * Put right after 'strapi::errors'. Records thrown errors on the request's http.request line and\n * marks them, so the copy strapi::errors logs through strapi.log.error is not written twice.\n */\nexport function strapiErrorCapture(): KoaMiddleware {\n return async (_ctx, next) => {\n try {\n await next();\n } catch (err) {\n const store = currentStore();\n if (store) recordErrorIn(store, err);\n markLogged(err);\n throw err;\n }\n };\n}\n\nconst LEVELS: Record<string, Level> = {\n error: \"error\",\n warn: \"warn\",\n info: \"info\",\n http: \"debug\",\n verbose: \"debug\",\n debug: \"debug\",\n silly: \"trace\",\n};\n\nconst META_SKIP = new Set([\"level\", \"message\", \"stack\"]);\n\nfunction forward(log: Logger, info: Record<string, unknown>): void {\n // Already carried by the request's http.request line (see strapiErrorCapture).\n if (isErrorLike(info) && isLogged(info)) return;\n const level = LEVELS[String(info.level)] ?? \"info\";\n const fields: Fields = {};\n for (const [key, value] of Object.entries(info)) if (!META_SKIP.has(key)) fields[key] = value;\n\n let message: unknown = info.message;\n if (isErrorLike(info)) {\n fields.err = info;\n } else if (isErrorLike(message)) {\n if (isLogged(message)) return;\n fields.err = message;\n message = message.message;\n } else if (typeof info.stack === \"string\") {\n fields.err_stack = info.stack;\n }\n if ((level === \"warn\" || level === \"error\") && fields.event === undefined) fields.event = \"strapi.log\";\n log[level](typeof message === \"string\" ? message : String(message ?? \"\"), fields);\n}\n\n/**\n * Winston configuration for Strapi's config/logger.ts: every strapi.log.* call (app code and\n * framework) becomes a contract JSON line with the request context. Level filtering is left to\n * the logger (LOG_LEVEL).\n */\nexport function strapiLoggerConfig(log: Logger) {\n // The winston logger that pipes into this transport; its level can change at runtime\n // (Strapi's data export/import commands set it to \"error\").\n let parent: { level?: string; levels?: Record<string, number> } | undefined;\n const allowed = (info: Record<string, unknown>): boolean => {\n const rank = parent?.levels?.[String(info.level)];\n const max = parent?.level === undefined ? undefined : parent.levels?.[parent.level];\n return rank === undefined || max === undefined || rank <= max;\n };\n const transport = new Writable({\n objectMode: true,\n write(info: Record<string, unknown>, _encoding, callback) {\n try {\n if (allowed(info)) forward(log, info);\n } finally {\n callback();\n }\n },\n });\n transport.on(\"pipe\", (source: unknown) => {\n parent = source as typeof parent;\n });\n // winston requires a `log(info, callback)` method on stream transports; writes go through write().\n Object.assign(transport, {\n log(info: Record<string, unknown>, callback: () => void) {\n forward(log, info);\n callback();\n },\n });\n return {\n level: \"silly\",\n // Identity format: replaces Strapi's prettyPrint so the transport receives raw info objects.\n format: { transform: <T>(info: T): T => info },\n transports: [transport],\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { globalSingleton } from \"./global\";\nimport type { Fields } from \"./normalize\";\n\nexport interface ContextStore {\n fields: Fields;\n error?: unknown;\n /** Route template captured while the router still knew it (Express error path). */\n route?: string;\n parent?: ContextStore;\n}\n\nconst als = globalSingleton(\"als\", () => new AsyncLocalStorage<ContextStore>());\n\nexport const STORE_KEY: symbol = Symbol.for(\"@tanngo11/log.store\");\n\nexport function runWithStore<T>(fields: Fields, fn: (store: ContextStore) => T): T {\n const parent = als.getStore();\n const store: ContextStore = { fields: { ...parent?.fields, ...fields }, parent };\n return als.run(store, () => fn(store));\n}\n\nexport function withContext<T>(fields: Fields, fn: () => T): T {\n return runWithStore(fields, () => fn());\n}\n\nexport function currentStore(): ContextStore | undefined {\n return als.getStore();\n}\n\nexport function getContext(): Fields {\n return als.getStore()?.fields ?? {};\n}\n\n// Applies to the current context and every enclosing one, so a field added inside a nested\n// withContext/runJob still reaches the request's http.request line.\nexport function addContext(fields: Fields): void {\n for (let s = als.getStore(); s; s = s.parent) Object.assign(s.fields, fields);\n}\n\n// Sets the error on the store and on enclosing stores that have none yet.\nexport function recordErrorIn(store: ContextStore, err: unknown): void {\n store.error = err;\n for (let s = store.parent; s; s = s.parent) if (s.error === undefined) s.error = err;\n}\n\n// Marks the error that the current request/job summary line should carry. Does not write a line.\nexport function recordError(err: unknown): void {\n const store = als.getStore();\n if (store) recordErrorIn(store, err);\n}\n\nexport function attachStore(target: object, store: ContextStore): void {\n (target as Record<symbol, ContextStore>)[STORE_KEY] = store;\n}\n\nexport function storeOf(target: unknown): ContextStore | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n return (target as Record<symbol, ContextStore | undefined>)[STORE_KEY];\n}\n","// Singletons shared by every copy of this package loaded in the process (ESM and CJS builds,\n// or duplicated installs), so context and dedupe state never split.\nexport function globalSingleton<T>(name: string, make: () => T): T {\n const key = Symbol.for(`@tanngo11/log.${name}`);\n const g = globalThis as unknown as Record<symbol, T | undefined>;\n let value = g[key];\n if (value === undefined) {\n value = make();\n g[key] = value;\n }\n return value;\n}\n","// Redaction shared by the logger and the error serializer. The collector redacts again,\n// but it cannot see secrets inside JSON-encoded strings, so the app side must catch them.\n\nexport const DEFAULT_REDACT_KEYS = [\n \"password\", \"passwd\", \"pwd\", \"passphrase\", \"secret\", \"client_secret\",\n \"token\", \"access_token\", \"refresh_token\", \"id_token\", \"auth_token\",\n \"api_key\", \"apikey\", \"access_key\", \"secret_key\", \"private_key\",\n \"authorization\", \"cookie\", \"set_cookie\", \"session_id\", \"sessionid\",\n \"credential\", \"credentials\", \"dsn\", \"connection_string\", \"conn_string\", \"jwt\", \"bearer\",\n];\n\n/** Opt-in value patterns for `redactValues`. Not on by default: they can hit ordinary numbers. */\nexport const REDACT_PATTERNS = {\n /** Vietnamese mobile numbers: 0912345678, +84912345678, 84912345678. */\n phoneVN: /(?<![\\d+])(?:\\+?84|0)[35789]\\d{8}(?!\\d)/g,\n /** Visa, Mastercard, Amex, Discover-like card numbers, with optional spaces or dashes. */\n paymentCard: /(?<!\\d)(?:4\\d{3}|5[1-5]\\d{2}|2[2-7]\\d{2}|3[47]\\d{2}|6(?:011|5\\d{2}))(?:[ -]?\\d{4}){2}[ -]?\\d{1,4}(?!\\d)/g,\n /** IPv4 addresses. */\n ipv4: /(?<![\\d.])(?:\\d{1,3}\\.){3}\\d{1,3}(?![\\d.])/g,\n} as const;\n\n// Keys that only describe a secret (count, type, timestamps, flags) stay readable.\nconst SAFE_SUFFIXES = [\"_count\", \"_type\", \"_length\", \"_expires_at\", \"_expires_in\", \"_ttl\", \"_at\", \"_ms\", \"_enabled\"];\n\nexport const REDACTED = \"[REDACTED]\";\n\nexport function toSnakeCase(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase();\n}\n\nconst URL_CREDENTIALS_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/@:\"']+:[^\\s/@\"']+@/gi;\nconst BEARER_RE = /\\bBearer\\s+[A-Za-z0-9._~+/=-]+/gi;\nconst JWT_RE = /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,})/g;\n\nexport type KeyPattern = string | RegExp;\n\nexport interface RedactorOptions {\n /** Extra sensitive keys: names (matched like the defaults) or patterns tested on the snake_case key. */\n keys?: readonly KeyPattern[];\n /** Extra value patterns; every match inside any string becomes [REDACTED]. */\n values?: readonly RegExp[];\n}\n\nexport interface Redactor {\n isSensitive(key: string): boolean;\n /** Masks secrets and emails that appear inside free text. */\n scrub(s: string): string;\n /** JSON.stringify that redacts sensitive keys at any depth and never throws. */\n json(value: unknown): string;\n}\n\nfunction globalize(re: RegExp): RegExp {\n return re.flags.includes(\"g\") ? new RegExp(re.source, re.flags) : new RegExp(re.source, `${re.flags}g`);\n}\n\nexport function createRedactor(opts: RedactorOptions = {}): Redactor {\n const words = [...DEFAULT_REDACT_KEYS];\n const keyPatterns: RegExp[] = [];\n for (const k of opts.keys ?? []) {\n if (typeof k === \"string\") words.push(toSnakeCase(k));\n else keyPatterns.push(new RegExp(k.source, k.flags.replace(\"g\", \"\")));\n }\n const valuePatterns = (opts.values ?? []).map(globalize);\n\n const isSensitive = (key: string): boolean => {\n const k = toSnakeCase(key);\n if (keyPatterns.some((re) => re.test(k))) return true;\n if (!words.includes(k) && SAFE_SUFFIXES.some((s) => k.endsWith(s))) return false;\n return words.some((w) => k === w || k.startsWith(`${w}_`) || k.endsWith(`_${w}`) || k.includes(`_${w}_`));\n };\n\n const scrub = (s: string): string => {\n let out = s\n .replace(URL_CREDENTIALS_RE, `$1${REDACTED}@`)\n .replace(BEARER_RE, `Bearer ${REDACTED}`)\n .replace(JWT_RE, \"[REDACTED_JWT]\")\n .replace(EMAIL_RE, \"***@$1\");\n for (const re of valuePatterns) out = out.replace(re, REDACTED);\n return out;\n };\n\n const json = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n const text = JSON.stringify(value, (key, val: unknown) => {\n if (key && val !== null && val !== undefined && isSensitive(key)) return REDACTED;\n if (typeof val === \"bigint\") return val.toString();\n if (val instanceof Error) return { name: val.name, message: val.message };\n return val;\n });\n return text ?? String(value);\n } catch {\n return String(value);\n }\n };\n\n return { isSensitive, scrub, json };\n}\n\nexport const defaultRedactor: Redactor = createRedactor();\n","import { globalSingleton } from \"./global\";\nimport { defaultRedactor } from \"./redact\";\n\nexport interface ErrFields {\n err_type?: string;\n err_message?: string;\n err_code?: string;\n err_stack?: string;\n err_cause?: string;\n}\n\nconst MAX_CAUSE_DEPTH = 5;\n\nexport function isErrorLike(v: unknown): v is Error {\n if (v instanceof Error) return true;\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { message?: unknown }).message === \"string\" &&\n (\"stack\" in v || \"name\" in v)\n );\n}\n\nfunction errorType(e: Error): string {\n if (e.name && e.name !== \"Error\") return e.name;\n const ctor = (e as { constructor?: { name?: string } }).constructor?.name;\n return ctor && ctor !== \"Object\" ? ctor : \"Error\";\n}\n\nexport function serializeError(err: unknown): ErrFields {\n if (!isErrorLike(err)) {\n if (typeof err === \"string\") return { err_type: \"string\", err_message: err };\n return { err_type: typeof err, err_message: defaultRedactor.json(err) };\n }\n const e = err as Error & { code?: unknown; cause?: unknown };\n const out: ErrFields = { err_type: errorType(e), err_message: String(e.message ?? \"\") };\n if (e.code !== undefined && e.code !== null) out.err_code = String(e.code);\n if (typeof e.stack === \"string\") out.err_stack = e.stack;\n\n const causes: string[] = [];\n let cause = e.cause;\n while (cause !== undefined && cause !== null && causes.length < MAX_CAUSE_DEPTH) {\n if (isErrorLike(cause)) {\n causes.push(`${errorType(cause)}: ${cause.message}`);\n cause = (cause as { cause?: unknown }).cause;\n } else {\n causes.push(defaultRedactor.json(cause));\n cause = undefined;\n }\n }\n if (causes.length > 0) out.err_cause = causes.join(\" <- \");\n return out;\n}\n\nconst logged = globalSingleton(\"logged\", () => new WeakSet<object>());\n\n// Marks an error as already written, so a later boundary (e.g. Next's onRequestError)\n// does not log it a second time.\nexport function markLogged(err: unknown): void {\n if (typeof err === \"object\" && err !== null) logged.add(err);\n}\n\nexport function isLogged(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && logged.has(err);\n}\n","import { isErrorLike, serializeError } from \"./error\";\nimport type { Level } from \"./levels\";\nimport { REDACTED, toSnakeCase, type Redactor } from \"./redact\";\n\nexport { DEFAULT_REDACT_KEYS, toSnakeCase } from \"./redact\";\n\n/** Final per-field hook: return a replacement, or undefined to drop the field. */\nexport type RedactHook = (key: string, value: Primitive) => unknown;\n\nexport type Fields = Record<string, unknown>;\nexport type Primitive = string | number | boolean | null;\nexport type LogRecord = Record<string, Primitive>;\n\nexport interface NormalizeOptions {\n snakeCase: boolean;\n redactor: Redactor;\n hook?: RedactHook;\n}\n\n// Fields the redact hook never sees, so every line keeps its level, message and event.\nconst HOOK_EXEMPT = new Set([\"level\", \"message\", \"event\"]);\n\n// Keys owned by Vector (overwritten or deleted on ingest) or by the logger itself.\nexport const RESERVED_KEYS = new Set([\n \"project\", \"service\", \"vps\", \"version\", \"container_name\", \"container_id\", \"image\", \"stream\",\n \"_timestamp\", \"label\", \"host\", \"source_type\", \"msg\", \"lvl\", \"severity\", \"level\", \"message\",\n]);\n\nexport const MAX_LINE_BYTES = 16000;\nconst MAX_MESSAGE = 500;\nconst MAX_STACK = 4000;\nconst MAX_STRING = 1000;\nconst MAX_DEPTH = 3;\nconst TRUNCATED = \"…[truncated]\";\n\n// Fields kept when a line is too large.\nconst KEEP_ON_SHRINK = new Set([\n \"level\", \"message\", \"event\", \"request_id\", \"trace_id\", \"span_id\", \"job_name\", \"job_id\", \"job_attempt\",\n \"user_id\", \"tenant_id\", \"err_type\", \"err_message\", \"err_code\",\n]);\n\nexport function stripUrl(url: string): string {\n const noQuery = url.split(/[?#]/, 1)[0] ?? \"\";\n return noQuery.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]*@/i, \"$1\");\n}\n\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - TRUNCATED.length) + TRUNCATED : s;\n}\n\nfunction isPlainObject(v: unknown): v is Fields {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction isUrlKey(key: string): boolean {\n return key === \"http_path\" || key === \"http_url\" || key.endsWith(\"_url\");\n}\n\nfunction flattenInto(out: LogRecord, prefix: string, obj: Fields, depth: number, opts: NormalizeOptions): void {\n for (const [rawKey, value] of Object.entries(obj)) {\n const key = opts.snakeCase ? toSnakeCase(rawKey) : rawKey;\n const full = prefix ? `${prefix}_${key}` : key;\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") continue;\n if (value !== null && (opts.redactor.isSensitive(rawKey) || opts.redactor.isSensitive(full))) {\n out[full] = REDACTED;\n continue;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n out[full] = value;\n } else if (typeof value === \"number\") {\n out[full] = Number.isFinite(value) ? value : String(value);\n } else if (typeof value === \"bigint\") {\n out[full] = value.toString();\n } else if (value instanceof Date) {\n out[full] = Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n } else if (isErrorLike(value)) {\n out[full] = `${value.name}: ${value.message}`;\n } else if (isPlainObject(value) && depth < MAX_DEPTH - 1) {\n flattenInto(out, full, value, depth + 1, opts);\n } else {\n // Arrays, deep objects, class instances: stringified with sensitive keys redacted.\n out[full] = opts.redactor.json(value);\n }\n }\n}\n\nfunction finalize(key: string, value: Primitive, opts: NormalizeOptions): Primitive {\n if (typeof value !== \"string\") return value;\n const v = opts.redactor.scrub(isUrlKey(key) ? stripUrl(value) : value);\n return truncate(v, key === \"err_stack\" ? MAX_STACK : MAX_STRING);\n}\n\nexport function buildRecord(\n level: Level,\n message: unknown,\n sources: (Fields | undefined)[],\n opts: NormalizeOptions,\n): LogRecord {\n const merged: Fields = {};\n for (const source of sources) if (source) Object.assign(merged, source);\n\n let err: unknown;\n if (merged.err !== undefined && merged.err !== null) {\n err = merged.err;\n delete merged.err;\n } else if (isErrorLike(merged.error)) {\n err = merged.error;\n delete merged.error;\n }\n\n const flat: LogRecord = {};\n flattenInto(flat, \"\", merged, 0, opts);\n if (err !== undefined) Object.assign(flat, serializeError(err));\n\n const text = typeof message === \"string\" ? message : opts.redactor.json(message);\n const out: LogRecord = { level, message: truncate(opts.redactor.scrub(text), MAX_MESSAGE) };\n for (const [k, v] of Object.entries(flat)) {\n const key = RESERVED_KEYS.has(k) ? `app_${k}` : k;\n let value = finalize(key, v, opts);\n if (opts.hook && !HOOK_EXEMPT.has(key)) {\n const replaced = opts.hook(key, value);\n if (replaced === undefined) continue;\n value = typeof replaced === \"object\" && replaced !== null ? opts.redactor.json(replaced) : (replaced as Primitive);\n }\n out[key] = value;\n }\n return out;\n}\n\nfunction byteLength(s: string): number {\n // UTF-8 uses at most 3 bytes per UTF-16 code unit: skip encoding short lines.\n if (s.length * 3 <= MAX_LINE_BYTES) return s.length;\n return new TextEncoder().encode(s).length;\n}\n\nexport function serializeRecord(record: LogRecord): string {\n const line = JSON.stringify(record);\n if (byteLength(line) <= MAX_LINE_BYTES) return line;\n const small: LogRecord = {};\n for (const [k, v] of Object.entries(record)) {\n if (KEEP_ON_SHRINK.has(k) || k.startsWith(\"http_\")) small[k] = v;\n }\n small.log_truncated = true;\n return JSON.stringify(small);\n}\n","// No imports: this module is shared with the edge entry (next-edge).\nexport const REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport function newRequestId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction first(header?: string | string[] | null): string | undefined {\n return Array.isArray(header) ? header[0] : (header ?? undefined);\n}\n\nexport function resolveRequestId(header?: string | string[] | null): string {\n const value = first(header);\n return value && REQUEST_ID_RE.test(value) ? value : newRequestId();\n}\n\nexport function parseTraceparent(header?: string | string[] | null): { trace_id: string; span_id: string } | undefined {\n const value = first(header)?.trim().toLowerCase();\n const m = value ? TRACEPARENT_RE.exec(value) : null;\n if (!m) return undefined;\n const [, version, traceId, spanId] = m as unknown as [string, string, string, string];\n if (version === \"ff\" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined;\n return { trace_id: traceId, span_id: spanId };\n}\n","import { getContext } from \"./context\";\nimport { markLogged, serializeError } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport { stripUrl, type Fields } from \"./normalize\";\nimport { parseTraceparent, resolveRequestId } from \"./request-id\";\n\nexport { newRequestId, parseTraceparent, REQUEST_ID_RE, resolveRequestId } from \"./request-id\";\n\nexport type HeaderSource = Headers | Record<string, string | string[] | undefined>;\n\nfunction header(headers: HeaderSource, name: string): string | string[] | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n return (headers as Record<string, string | string[] | undefined>)[name];\n}\n\nexport function requestContextFields(headers: HeaderSource): { request_id: string; trace_id?: string; span_id?: string } {\n const out: { request_id: string; trace_id?: string; span_id?: string } = {\n request_id: resolveRequestId(header(headers, \"x-request-id\")),\n };\n const tp = parseTraceparent(header(headers, \"traceparent\"));\n if (tp) Object.assign(out, tp);\n return out;\n}\n\n// Headers to forward to services we own, so their logs share request_id / trace_id.\nexport function propagationHeaders(): Record<string, string> {\n const ctx = getContext();\n const out: Record<string, string> = {};\n if (typeof ctx.request_id === \"string\") out[\"x-request-id\"] = ctx.request_id;\n if (typeof ctx.trace_id === \"string\" && typeof ctx.span_id === \"string\") {\n out.traceparent = `00-${ctx.trace_id}-${ctx.span_id}-01`;\n }\n return out;\n}\n\nexport const DEFAULT_SKIP_PATHS: (string | RegExp)[] = [\n /^\\/(health|healthz|ready|readyz|livez)\\/?$/,\n \"/favicon.ico\",\n /^\\/_next\\/static\\//,\n];\n\nexport interface HttpLogOptions {\n skipPaths?: (string | RegExp)[];\n}\n\nexport interface HttpRequestInfo {\n method: string;\n route?: string;\n path: string;\n status: number;\n duration_ms?: number;\n err?: unknown;\n fields?: Fields;\n}\n\nexport function shouldSkip(method: string, path: string, skipPaths: (string | RegExp)[] = DEFAULT_SKIP_PATHS): boolean {\n if (method.toUpperCase() === \"OPTIONS\") return true;\n const p = stripUrl(path);\n return skipPaths.some((s) => (typeof s === \"string\" ? p === s : s.test(p)));\n}\n\n// Writes the one `http.request` summary line for an inbound request.\nexport function logHttpRequest(log: Logger, info: HttpRequestInfo, opts: HttpLogOptions = {}): void {\n if (shouldSkip(info.method, info.path, opts.skipPaths)) return;\n const level = info.status >= 500 ? \"error\" : info.status >= 400 ? \"warn\" : \"info\";\n const path = stripUrl(info.path);\n const errFields: Fields = {};\n if (info.err !== undefined && info.err !== null) {\n Object.assign(errFields, serializeError(info.err));\n if (info.status < 500) delete errFields.err_stack;\n markLogged(info.err);\n }\n // Route templates keep the message bounded; the raw path would make one message per URL.\n const message = info.route ? `${info.method} ${info.route} ${info.status}` : `${info.method} ${info.status}`;\n log[level](message, {\n ...info.fields,\n event: \"http.request\",\n http_method: info.method,\n http_route: info.route,\n http_path: path,\n http_status: info.status,\n duration_ms: info.duration_ms === undefined ? undefined : Math.round(info.duration_ms),\n ...errFields,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAyB;;;ACAzB,8BAAkC;;;ACE3B,SAAS,gBAAmB,MAAc,MAAkB;AACjE,QAAM,MAAM,uBAAO,IAAI,iBAAiB,IAAI,EAAE;AAC9C,QAAM,IAAI;AACV,MAAI,QAAQ,EAAE,GAAG;AACjB,MAAI,UAAU,QAAW;AACvB,YAAQ,KAAK;AACb,MAAE,GAAG,IAAI;AAAA,EACX;AACA,SAAO;AACT;;;ADCA,IAAM,MAAM,gBAAgB,OAAO,MAAM,IAAI,0CAAgC,CAAC;AAIvE,SAAS,aAAgB,QAAgB,IAAmC;AACjF,QAAM,SAAS,IAAI,SAAS;AAC5B,QAAM,QAAsB,EAAE,QAAQ,EAAE,GAAG,QAAQ,QAAQ,GAAG,OAAO,GAAG,OAAO;AAC/E,SAAO,IAAI,IAAI,OAAO,MAAM,GAAG,KAAK,CAAC;AACvC;AAMO,SAAS,eAAyC;AACvD,SAAO,IAAI,SAAS;AACtB;AAaO,SAAS,cAAc,OAAqB,KAAoB;AACrE,QAAM,QAAQ;AACd,WAAS,IAAI,MAAM,QAAQ,GAAG,IAAI,EAAE,OAAQ,KAAI,EAAE,UAAU,OAAW,GAAE,QA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AI;AACjB,eAAS;AAAA,IACX;AAAA,EACF,CAAC;AACD,SAAO;AAAA,IACL,OAAO;AAAA;AAAA,IAEP,QAAQ,EAAE,WAAW,CAAI,SAAe,KAAK;AAAA,IAC7C,YAAY,CAAC,SAAS;AAAA,EACxB;AACF;","names":[]}
package/dist/strapi.js CHANGED
@@ -103,16 +103,25 @@ function forward(log, info) {
103
103
  log[level](typeof message === "string" ? message : String(message ?? ""), fields);
104
104
  }
105
105
  function strapiLoggerConfig(log) {
106
+ let parent;
107
+ const allowed = (info) => {
108
+ const rank = parent?.levels?.[String(info.level)];
109
+ const max = parent?.level === void 0 ? void 0 : parent.levels?.[parent.level];
110
+ return rank === void 0 || max === void 0 || rank <= max;
111
+ };
106
112
  const transport = new Writable({
107
113
  objectMode: true,
108
114
  write(info, _encoding, callback) {
109
115
  try {
110
- forward(log, info);
116
+ if (allowed(info)) forward(log, info);
111
117
  } finally {
112
118
  callback();
113
119
  }
114
120
  }
115
121
  });
122
+ transport.on("pipe", (source) => {
123
+ parent = source;
124
+ });
116
125
  Object.assign(transport, {
117
126
  log(info, callback) {
118
127
  forward(log, info);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/strapi.ts"],"sourcesContent":["import { Writable } from \"node:stream\";\nimport { currentStore, recordErrorIn, runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, newRequestId, parseTraceparent, REQUEST_ID_RE, type HttpLogOptions } from \"./http\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\n/** The parts of a Koa/Strapi context the middlewares use. */\nexport interface KoaContextLike {\n method: string;\n url: string;\n status: number;\n state: Record<string, unknown>;\n get(name: string): string;\n set(name: string, value: string): void;\n /** Full matched route template, set by @koa/router (includes router prefixes such as /api). */\n _matchedRoute?: unknown;\n}\n\nexport type KoaMiddleware = (ctx: KoaContextLike, next: () => Promise<unknown>) => Promise<void>;\n\nexport interface StrapiRequestLoggerOptions extends HttpLogOptions {\n log: Logger;\n /**\n * Use a valid incoming x-request-id as request_id. Off by default: the server issues its own\n * id (Strapi apps often use it for audit rows) and records the caller's id as\n * upstream_request_id, which still links the logs of both services.\n */\n trustIncomingRequestId?: boolean;\n /** ctx.state key shared with the app's own correlation middleware. Default \"requestId\". */\n stateKey?: string;\n}\n\nfunction routeOf(ctx: KoaContextLike): string | undefined {\n if (typeof ctx._matchedRoute === \"string\") return ctx._matchedRoute;\n const path = (ctx.state.route as { path?: unknown } | undefined)?.path;\n return typeof path === \"string\" ? path : undefined;\n}\n\n/**\n * Replaces 'strapi::logger' (put it first in config/middlewares): opens the request context and\n * writes one http.request line per request.\n */\nexport function strapiRequestLogger(opts: StrapiRequestLoggerOptions): KoaMiddleware {\n const stateKey = opts.stateKey ?? \"requestId\";\n return async (ctx, next) => {\n const incoming = ctx.get(\"x-request-id\");\n const caller = incoming && REQUEST_ID_RE.test(incoming) ? incoming : undefined;\n const existing = ctx.state[stateKey];\n const requestId =\n typeof existing === \"string\" && existing ? existing : opts.trustIncomingRequestId && caller ? caller : newRequestId();\n // A UUID v4 here is kept by correlation middlewares that only replace invalid ids.\n if (ctx.state[stateKey] === undefined) ctx.state[stateKey] = requestId;\n ctx.set(\"X-Request-ID\", requestId);\n\n const fields: Fields = { request_id: requestId };\n if (caller && caller !== requestId) fields.upstream_request_id = caller;\n const trace = parseTraceparent(ctx.get(\"traceparent\"));\n if (trace) Object.assign(fields, trace);\n\n const start = performance.now();\n await runWithStore(fields, async (store) => {\n let failed = false;\n try {\n await next();\n } catch (err) {\n // Only reached when no error middleware handled it; Koa answers 500.\n failed = true;\n recordErrorIn(store, err);\n throw err;\n } finally {\n logHttpRequest(\n opts.log,\n {\n method: ctx.method,\n route: routeOf(ctx),\n path: ctx.url,\n status: failed ? 500 : ctx.status,\n duration_ms: performance.now() - start,\n err: store.error,\n fields: store.fields,\n },\n opts,\n );\n }\n });\n };\n}\n\n/**\n * Put right after 'strapi::errors'. Records thrown errors on the request's http.request line and\n * marks them, so the copy strapi::errors logs through strapi.log.error is not written twice.\n */\nexport function strapiErrorCapture(): KoaMiddleware {\n return async (_ctx, next) => {\n try {\n await next();\n } catch (err) {\n const store = currentStore();\n if (store) recordErrorIn(store, err);\n markLogged(err);\n throw err;\n }\n };\n}\n\nconst LEVELS: Record<string, Level> = {\n error: \"error\",\n warn: \"warn\",\n info: \"info\",\n http: \"debug\",\n verbose: \"debug\",\n debug: \"debug\",\n silly: \"trace\",\n};\n\nconst META_SKIP = new Set([\"level\", \"message\", \"stack\"]);\n\nfunction forward(log: Logger, info: Record<string, unknown>): void {\n // Already carried by the request's http.request line (see strapiErrorCapture).\n if (isErrorLike(info) && isLogged(info)) return;\n const level = LEVELS[String(info.level)] ?? \"info\";\n const fields: Fields = {};\n for (const [key, value] of Object.entries(info)) if (!META_SKIP.has(key)) fields[key] = value;\n\n let message: unknown = info.message;\n if (isErrorLike(info)) {\n fields.err = info;\n } else if (isErrorLike(message)) {\n if (isLogged(message)) return;\n fields.err = message;\n message = message.message;\n } else if (typeof info.stack === \"string\") {\n fields.err_stack = info.stack;\n }\n if ((level === \"warn\" || level === \"error\") && fields.event === undefined) fields.event = \"strapi.log\";\n log[level](typeof message === \"string\" ? message : String(message ?? \"\"), fields);\n}\n\n/**\n * Winston configuration for Strapi's config/logger.ts: every strapi.log.* call (app code and\n * framework) becomes a contract JSON line with the request context. Level filtering is left to\n * the logger (LOG_LEVEL).\n */\nexport function strapiLoggerConfig(log: Logger) {\n const transport = new Writable({\n objectMode: true,\n write(info: Record<string, unknown>, _encoding, callback) {\n try {\n forward(log, info);\n } finally {\n callback();\n }\n },\n });\n // winston requires a `log(info, callback)` method on stream transports; writes go through write().\n Object.assign(transport, {\n log(info: Record<string, unknown>, callback: () => void) {\n forward(log, info);\n callback();\n },\n });\n return {\n level: \"silly\",\n // Identity format: replaces Strapi's prettyPrint so the transport receives raw info objects.\n format: { transform: <T>(info: T): T => info },\n transports: [transport],\n };\n}\n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M,YAAY,IAAI,SAAS;AAAA,IAC7B,YAAY;AAAA,IACZ,MAAM,MAA+B,WAAW,UAAU;AACxD,UAAI;AACF,gBAAQ,KAAK,IAAI;AAAA,MACnB,UAAE;AACA,iBAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF,CAAC;AAED,SAAO,OAAO,WAAW;AAAA,IACvB,IAAI,MAA+B,UAAsB;AACvD,cAAQ,KAAK,IAAI;AACjB,eAAS;AAAA,IACX;AAAA,EACF,CAAC;AACD,SAAO;AAAA,IACL,OAAO;AAAA;AAAA,IAEP,QAAQ,EAAE,WAAW,CAAI,SAAe,KAAK;AAAA,IAC7C,YAAY,CAAC,SAAS;AAAA,EACxB;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/strapi.ts"],"sourcesContent":["import { Writable } from \"node:stream\";\nimport { currentStore, recordErrorIn, runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, newRequestId, parseTraceparent, REQUEST_ID_RE, type HttpLogOptions } from \"./http\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\n/** The parts of a Koa/Strapi context the middlewares use. */\nexport interface KoaContextLike {\n method: string;\n url: string;\n status: number;\n state: Record<string, unknown>;\n get(name: string): string;\n set(name: string, value: string): void;\n /** Full matched route template, set by @koa/router (includes router prefixes such as /api). */\n _matchedRoute?: unknown;\n}\n\nexport type KoaMiddleware = (ctx: KoaContextLike, next: () => Promise<unknown>) => Promise<void>;\n\nexport interface StrapiRequestLoggerOptions extends HttpLogOptions {\n log: Logger;\n /**\n * Use a valid incoming x-request-id as request_id. Off by default: the server issues its own\n * id (Strapi apps often use it for audit rows) and records the caller's id as\n * upstream_request_id, which still links the logs of both services.\n */\n trustIncomingRequestId?: boolean;\n /** ctx.state key shared with the app's own correlation middleware. Default \"requestId\". */\n stateKey?: string;\n}\n\nfunction routeOf(ctx: KoaContextLike): string | undefined {\n if (typeof ctx._matchedRoute === \"string\") return ctx._matchedRoute;\n const path = (ctx.state.route as { path?: unknown } | undefined)?.path;\n return typeof path === \"string\" ? path : undefined;\n}\n\n/**\n * Replaces 'strapi::logger' (put it first in config/middlewares): opens the request context and\n * writes one http.request line per request.\n */\nexport function strapiRequestLogger(opts: StrapiRequestLoggerOptions): KoaMiddleware {\n const stateKey = opts.stateKey ?? \"requestId\";\n return async (ctx, next) => {\n const incoming = ctx.get(\"x-request-id\");\n const caller = incoming && REQUEST_ID_RE.test(incoming) ? incoming : undefined;\n const existing = ctx.state[stateKey];\n const requestId =\n typeof existing === \"string\" && existing ? existing : opts.trustIncomingRequestId && caller ? caller : newRequestId();\n // A UUID v4 here is kept by correlation middlewares that only replace invalid ids.\n if (ctx.state[stateKey] === undefined) ctx.state[stateKey] = requestId;\n ctx.set(\"X-Request-ID\", requestId);\n\n const fields: Fields = { request_id: requestId };\n if (caller && caller !== requestId) fields.upstream_request_id = caller;\n const trace = parseTraceparent(ctx.get(\"traceparent\"));\n if (trace) Object.assign(fields, trace);\n\n const start = performance.now();\n await runWithStore(fields, async (store) => {\n let failed = false;\n try {\n await next();\n } catch (err) {\n // Only reached when no error middleware handled it; Koa answers 500.\n failed = true;\n recordErrorIn(store, err);\n throw err;\n } finally {\n logHttpRequest(\n opts.log,\n {\n method: ctx.method,\n route: routeOf(ctx),\n path: ctx.url,\n status: failed ? 500 : ctx.status,\n duration_ms: performance.now() - start,\n err: store.error,\n fields: store.fields,\n },\n opts,\n );\n }\n });\n };\n}\n\n/**\n * Put right after 'strapi::errors'. Records thrown errors on the request's http.request line and\n * marks them, so the copy strapi::errors logs through strapi.log.error is not written twice.\n */\nexport function strapiErrorCapture(): KoaMiddleware {\n return async (_ctx, next) => {\n try {\n await next();\n } catch (err) {\n const store = currentStore();\n if (store) recordErrorIn(store, err);\n markLogged(err);\n throw err;\n }\n };\n}\n\nconst LEVELS: Record<string, Level> = {\n error: \"error\",\n warn: \"warn\",\n info: \"info\",\n http: \"debug\",\n verbose: \"debug\",\n debug: \"debug\",\n silly: \"trace\",\n};\n\nconst META_SKIP = new Set([\"level\", \"message\", \"stack\"]);\n\nfunction forward(log: Logger, info: Record<string, unknown>): void {\n // Already carried by the request's http.request line (see strapiErrorCapture).\n if (isErrorLike(info) && isLogged(info)) return;\n const level = LEVELS[String(info.level)] ?? \"info\";\n const fields: Fields = {};\n for (const [key, value] of Object.entries(info)) if (!META_SKIP.has(key)) fields[key] = value;\n\n let message: unknown = info.message;\n if (isErrorLike(info)) {\n fields.err = info;\n } else if (isErrorLike(message)) {\n if (isLogged(message)) return;\n fields.err = message;\n message = message.message;\n } else if (typeof info.stack === \"string\") {\n fields.err_stack = info.stack;\n }\n if ((level === \"warn\" || level === \"error\") && fields.event === undefined) fields.event = \"strapi.log\";\n log[level](typeof message === \"string\" ? message : String(message ?? \"\"), fields);\n}\n\n/**\n * Winston configuration for Strapi's config/logger.ts: every strapi.log.* call (app code and\n * framework) becomes a contract JSON line with the request context. Level filtering is left to\n * the logger (LOG_LEVEL).\n */\nexport function strapiLoggerConfig(log: Logger) {\n // The winston logger that pipes into this transport; its level can change at runtime\n // (Strapi's data export/import commands set it to \"error\").\n let parent: { level?: string; levels?: Record<string, number> } | undefined;\n const allowed = (info: Record<string, unknown>): boolean => {\n const rank = parent?.levels?.[String(info.level)];\n const max = parent?.level === undefined ? undefined : parent.levels?.[parent.level];\n return rank === undefined || max === undefined || rank <= max;\n };\n const transport = new Writable({\n objectMode: true,\n write(info: Record<string, unknown>, _encoding, callback) {\n try {\n if (allowed(info)) forward(log, info);\n } finally {\n callback();\n }\n },\n });\n transport.on(\"pipe\", (source: unknown) => {\n parent = source as typeof parent;\n });\n // winston requires a `log(info, callback)` method on stream transports; writes go through write().\n Object.assign(transport, {\n log(info: Record<string, unknown>, callback: () => void) {\n forward(log, info);\n callback();\n },\n });\n return {\n level: \"silly\",\n // Identity format: replaces Strapi's prettyPrint so the transport receives raw info objects.\n format: { transform: <T>(info: T): T => info },\n transports: [transport],\n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9C,MAAI;AACJ,QAAM,UAAU,CAAC,SAA2C;AAC1D,UAAM,OAAO,QAAQ,SAAS,OAAO,KAAK,KAAK,CAAC;AAChD,UAAM,MAAM,QAAQ,UAAU,SAAY,SAAY,OAAO,SAAS,OAAO,KAAK;AAClF,WAAO,SAAS,UAAa,QAAQ,UAAa,QAAQ;AAAA,EAC5D;AACA,QAAM,YAAY,IAAI,SAAS;AAAA,IAC7B,YAAY;AAAA,IACZ,MAAM,MAA+B,WAAW,UAAU;AACxD,UAAI;AACF,YAAI,QAAQ,IAAI,EAAG,SAAQ,KAAK,IAAI;AAAA,MACtC,UAAE;AACA,iBAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF,CAAC;AACD,YAAU,GAAG,QAAQ,CAAC,WAAoB;AACxC,aAAS;AAAA,EACX,CAAC;AAED,SAAO,OAAO,WAAW;AAAA,IACvB,IAAI,MAA+B,UAAsB;AACvD,cAAQ,KAAK,IAAI;AACjB,eAAS;AAAA,IACX;AAAA,EACF,CAAC;AACD,SAAO;AAAA,IACL,OAAO;AAAA;AAAA,IAEP,QAAQ,EAAE,WAAW,CAAI,SAAe,KAAK;AAAA,IAC7C,YAAY,CAAC,SAAS;AAAA,EACxB;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanngo11/log",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "Structured JSON logging for Node services, implementing log contract v1",
5
5
  "license": "MIT",
6
6
  "repository": {