@webpieces/winston 0.3.316 → 0.3.317
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.
- package/package.json +3 -3
- package/src/format.js +5 -6
- package/src/format.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/winston",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.317",
|
|
4
4
|
"description": "Node-only winston LoggerFactory backends for webpieces: Console (local pretty) + GCP (Cloud Run stdout JSON), auto-enriched with HeaderRegistry context keys",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -23,8 +23,8 @@
|
|
|
23
23
|
"access": "public"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@webpieces/core-util": "0.3.
|
|
27
|
-
"@webpieces/core-context": "0.3.
|
|
26
|
+
"@webpieces/core-util": "0.3.317",
|
|
27
|
+
"@webpieces/core-context": "0.3.317",
|
|
28
28
|
"winston": "3.11.0",
|
|
29
29
|
"logform": "2.7.0",
|
|
30
30
|
"safe-stable-stringify": "2.5.0"
|
package/src/format.js
CHANGED
|
@@ -74,13 +74,12 @@ function injectContextFormat() {
|
|
|
74
74
|
let reportedMissingContext = false;
|
|
75
75
|
return (0, winston_1.format)((info) => {
|
|
76
76
|
if (core_context_1.RequestContext.isActive()) {
|
|
77
|
-
//
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
info[key.name] = key.maskIfSecured(value);
|
|
77
|
+
// ONE loop, in HeaderRegistry.buildLogFields. Caller-supplied fields win on conflict.
|
|
78
|
+
core_context_1.RequestContext.buildLogFields().forEach((value, name) => {
|
|
79
|
+
if (info[name] === undefined) {
|
|
80
|
+
info[name] = value;
|
|
82
81
|
}
|
|
83
|
-
}
|
|
82
|
+
});
|
|
84
83
|
}
|
|
85
84
|
else if (!reportedMissingContext) {
|
|
86
85
|
reportedMissingContext = true;
|
package/src/format.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/format.ts"],"names":[],"mappings":";;;AA6CA,4CAeC;AAkBD,kDAsBC;AAMD,wCAKC;AAYD,8CA2BC;AAtJD;;;;;;;;;;;;GAYG;AACH,qCAAiC;AAEjC,iEAAmE;AACnE,oDAAsD;AAEtD,0DAAyD;AAMzD,gFAAgF;AAChF,iFAAiF;AACjF,kFAAkF;AAClF,uDAAuD;AAC1C,QAAA,iBAAiB,GAA2B;IACrD,KAAK,EAAE,OAAO;IACd,OAAO,EAAE,OAAO;IAChB,KAAK,EAAE,OAAO;IACd,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,OAAO;CACjB,CAAC;AAEF;;;;;;;GAOG;AACH,SAAgB,gBAAgB;IAC5B,OAAO,IAAA,gBAAM,EAAC,CAAC,IAAuB,EAAE,EAAE;QACtC,OAAO,MAAM,CAAC,MAAM,CAChB,IAAI,EACJ,IAAI,CAAC,KAAK;QACN,kGAAkG;QAClG,IAAA,iCAAa,EAAC,IAAI,EAAE,CAAC,IAAY,EAAE,KAAc,EAAE,EAAE;YACjD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBAC5B,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;YAC5B,CAAC;YACD,OAAO,KAAK,CAAC;QACjB,CAAC,CAAE,CACN,CACJ,CAAC;IACN,CAAC,CAAC,EAAE,CAAC;AACT,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,oHAAoH;AACpH,SAAgB,mBAAmB;IAC/B,IAAI,sBAAsB,GAAG,KAAK,CAAC;IACnC,OAAO,IAAA,gBAAM,EAAC,CAAC,IAAuB,EAAE,EAAE;QACtC,IAAI,6BAAc,CAAC,QAAQ,EAAE,EAAE,CAAC;YAC5B,mFAAmF;YACnF,KAAK,MAA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AAG,UAAU,GAAG,MAAM,GAAG,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,OAAO,GAAG,OAAO,EAAE,CAAC;IAC5E,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["/**\n * The winston format layers that turn a raw webpieces log call into a\n * Cloud-Logging-ready structured record. Ported verbatim (behaviourally) from\n * the tested-in-GCP logger at\n * onetablet/monorepo-nx1 libraries/core-context/src/logger/format.ts, with the\n * one webpieces adaptation: context is read from the webpieces HeaderRegistry +\n * a ContextReader (rather than a hard-coded PLATFORM_HEADERS enum), so the exact\n * set of logged fields is whatever the app registered.\n *\n * Correlation rides the webpieces magic context (AsyncLocalStorage on the\n * server, via the ContextReader passed in) — NOT OpenTelemetry / trace-agent, so\n * nothing here imports a tracing agent.\n */\nimport { format } from 'winston';\nimport type { Format, TransformableInfo } from 'logform';\nimport { stringify as safeStringify } from 'safe-stable-stringify';\nimport { HeaderRegistry } from '@webpieces/core-util';\nimport type { ContextKey } from '@webpieces/core-util';\nimport { RequestContext } from '@webpieces/core-context';\n\n// JSON-shaped value (the widest thing a log field / replacer value can hold),\n// used instead of `any`/`unknown` which the code rules disallow.\ntype JsonValue = string | number | boolean | bigint | object | null | undefined;\n\n// winston level → GCP Cloud Logging severity. The Cloud Run / GKE logging agent\n// recognises top-level `severity` in stdout JSON; without this map it falls back\n// to \"DEFAULT\" which is unfilterable. webpieces `trace` maps onto winston `silly`\n// (see WinstonLogger), so both land at DEBUG severity.\nexport const LEVEL_TO_SEVERITY: Record<string, string> = {\n silly: 'DEBUG',\n verbose: 'DEBUG',\n debug: 'DEBUG',\n info: 'INFO',\n warn: 'WARNING',\n error: 'ERROR',\n};\n\n/**\n * Round-trip the record through safe-stable-stringify so circular references\n * (HTTP client/response cycles, request/response objects, framework execution\n * contexts) become \"[Circular]\" instead of crashing the log emit, and bigints\n * serialize as strings (JSON.stringify can't, and the bare safe-stringify output\n * wouldn't round-trip through JSON.parse). Symbol keys winston relies on are\n * untouched (JSON ignores them), so Object.assign only rewrites string fields.\n */\nexport function bigIntSafeFormat(): Format {\n return format((info: TransformableInfo) => {\n return Object.assign(\n info,\n JSON.parse(\n // webpieces-disable no-any-unknown -- safe-stable-stringify's Replacer types the value as unknown\n safeStringify(info, (_key: string, value: unknown) => {\n if (typeof value === 'bigint') {\n return value.toString();\n }\n return value;\n })!,\n ),\n );\n })();\n}\n\n/**\n * Inject every logged HeaderRegistry key present in the active RequestContext frame\n * into the record under its `name` (→ top-level jsonPayload.<name> in GCP, filterable\n * as jsonPayload.requestId, jsonPayload.tenantId, …). Values are read DIRECTLY from\n * RequestContext, secured keys masked via {@link ContextKey.maskIfSecured} — no\n * ContextReader. Caller-supplied fields on the record win on conflict. Runs on EVERY\n * winston call, including winston's own handleExceptions/handleRejections lines that\n * bypass the WinstonLogger wrapper.\n *\n * This mirrors the (duplicated, on purpose) inline logic in BunyanLogger: it must run\n * ONLY when a winston backend is installed, never for the plain ConsoleLogger. A log\n * line with no active RequestContext = a missing request-wrapping server filter; we\n * report that once (closure latch, via console.error so there is no re-entrancy back\n * into winston and no dependency on LogManager).\n */\n// webpieces-disable no-function-outside-class -- winston format(fn) factory; whole file is winston Format factories\nexport function injectContextFormat(): Format {\n let reportedMissingContext = false;\n return format((info: TransformableInfo) => {\n if (RequestContext.isActive()) {\n // getLoggedKeys() already returns only isLogged keys (precomputed at configure()).\n for (const key of HeaderRegistry.get().getLoggedKeys()) {\n const value = RequestContext.getHeader<string>(key);\n if (value !== undefined && info[key.name] === undefined) {\n info[key.name] = key.maskIfSecured(value);\n }\n }\n } else if (!reportedMissingContext) {\n reportedMissingContext = true;\n // This IS a logging backend; direct stderr for the framework-misconfig warning.\n console.error(\n 'Log emitted OUTSIDE RequestContext.run(...) — every request must be wrapped in ' +\n 'RequestContext.run() by a server filter. That filter appears to be missing: ' +\n 'correlation fields (requestId, tenant, ...) will be absent from logs. Reported once.',\n );\n }\n return info;\n })();\n}\n\n/**\n * Map the winston level onto a top-level `severity` field that the Cloud Logging\n * agent lifts onto the LogEntry.\n */\nexport function severityFormat(): Format {\n return format((info: TransformableInfo) => {\n info['severity'] = LEVEL_TO_SEVERITY[info.level] || info.level.toUpperCase();\n return info;\n })();\n}\n\n// Fields that are rendered specially (or not at all) by the local pretty format,\n// so they must not leak into the trailing \"extra\" JSON blob.\nconst LOCAL_STRUCTURAL_KEYS = new Set<string>(['level', 'message', 'severity', 'svcGitHash', 'loggerName']);\n\n/**\n * Local-only human format: `[loggerName] [requestId=… tenantId=…] level: message { …extra }`.\n * The registered context keys (already injected by injectContextFormat) render as\n * a bracketed prefix; anything else the caller attached renders as trailing JSON.\n * The set of context-key names is read lazily from the registry (first line).\n */\nexport function localPrettyFormat(): Format {\n let contextNames: Set<string> | undefined;\n return format.printf((info: TransformableInfo) => {\n if (!contextNames) {\n contextNames = new Set(HeaderRegistry.get().getLoggedKeys().map((k: ContextKey) => k.name));\n }\n const prefixBits: string[] = [];\n for (const name of contextNames) {\n const value = info[name];\n if (value != null) {\n prefixBits.push(`${name}=${String(value)}`);\n }\n }\n const prefix = prefixBits.length ? `[${prefixBits.join(' ')}] ` : '';\n const loggerName = info['loggerName'] ? `[${String(info['loggerName'])}] ` : '';\n\n const rest: Record<string, JsonValue> = {};\n for (const key of Object.keys(info)) {\n if (LOCAL_STRUCTURAL_KEYS.has(key) || contextNames.has(key)) {\n continue;\n }\n rest[key] = info[key] as JsonValue;\n }\n const restStr = Object.keys(rest).length ? ` ${safeStringify(rest)}` : '';\n\n return `${loggerName}${prefix}${info.level}: ${info.message}${restStr}`;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"format.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/format.ts"],"names":[],"mappings":";;;AA6CA,4CAeC;AAkBD,kDAqBC;AAMD,wCAKC;AAYD,8CA2BC;AArJD;;;;;;;;;;;;GAYG;AACH,qCAAiC;AAEjC,iEAAmE;AACnE,oDAAsD;AAEtD,0DAAyD;AAMzD,gFAAgF;AAChF,iFAAiF;A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AG,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;QACrE,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;QAEhF,MAAM,IAAI,GAA8B,EAAE,CAAC;QAC3C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAClC,IAAI,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;gBAC1D,SAAS;YACb,CAAC;YACD,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAc,CAAC;QACvC,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,IAAA,iCAAa,EAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAE1E,OAAO,GAAG,UAAU,GAAG,MAAM,GAAG,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,OAAO,GAAG,OAAO,EAAE,CAAC;IAC5E,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["/**\n * The winston format layers that turn a raw webpieces log call into a\n * Cloud-Logging-ready structured record. Ported verbatim (behaviourally) from\n * the tested-in-GCP logger at\n * onetablet/monorepo-nx1 libraries/core-context/src/logger/format.ts, with the\n * one webpieces adaptation: context is read from the webpieces HeaderRegistry +\n * a ContextReader (rather than a hard-coded PLATFORM_HEADERS enum), so the exact\n * set of logged fields is whatever the app registered.\n *\n * Correlation rides the webpieces magic context (AsyncLocalStorage on the\n * server, via the ContextReader passed in) — NOT OpenTelemetry / trace-agent, so\n * nothing here imports a tracing agent.\n */\nimport { format } from 'winston';\nimport type { Format, TransformableInfo } from 'logform';\nimport { stringify as safeStringify } from 'safe-stable-stringify';\nimport { HeaderRegistry } from '@webpieces/core-util';\nimport type { ContextKey } from '@webpieces/core-util';\nimport { RequestContext } from '@webpieces/core-context';\n\n// JSON-shaped value (the widest thing a log field / replacer value can hold),\n// used instead of `any`/`unknown` which the code rules disallow.\ntype JsonValue = string | number | boolean | bigint | object | null | undefined;\n\n// winston level → GCP Cloud Logging severity. The Cloud Run / GKE logging agent\n// recognises top-level `severity` in stdout JSON; without this map it falls back\n// to \"DEFAULT\" which is unfilterable. webpieces `trace` maps onto winston `silly`\n// (see WinstonLogger), so both land at DEBUG severity.\nexport const LEVEL_TO_SEVERITY: Record<string, string> = {\n silly: 'DEBUG',\n verbose: 'DEBUG',\n debug: 'DEBUG',\n info: 'INFO',\n warn: 'WARNING',\n error: 'ERROR',\n};\n\n/**\n * Round-trip the record through safe-stable-stringify so circular references\n * (HTTP client/response cycles, request/response objects, framework execution\n * contexts) become \"[Circular]\" instead of crashing the log emit, and bigints\n * serialize as strings (JSON.stringify can't, and the bare safe-stringify output\n * wouldn't round-trip through JSON.parse). Symbol keys winston relies on are\n * untouched (JSON ignores them), so Object.assign only rewrites string fields.\n */\nexport function bigIntSafeFormat(): Format {\n return format((info: TransformableInfo) => {\n return Object.assign(\n info,\n JSON.parse(\n // webpieces-disable no-any-unknown -- safe-stable-stringify's Replacer types the value as unknown\n safeStringify(info, (_key: string, value: unknown) => {\n if (typeof value === 'bigint') {\n return value.toString();\n }\n return value;\n })!,\n ),\n );\n })();\n}\n\n/**\n * Inject every logged HeaderRegistry key present in the active RequestContext frame\n * into the record under its `name` (→ top-level jsonPayload.<name> in GCP, filterable\n * as jsonPayload.requestId, jsonPayload.tenantId, …). Values are read DIRECTLY from\n * RequestContext, secured keys masked via {@link ContextKey.maskIfSecured} — no\n * ContextReader. Caller-supplied fields on the record win on conflict. Runs on EVERY\n * winston call, including winston's own handleExceptions/handleRejections lines that\n * bypass the WinstonLogger wrapper.\n *\n * This mirrors the (duplicated, on purpose) inline logic in BunyanLogger: it must run\n * ONLY when a winston backend is installed, never for the plain ConsoleLogger. A log\n * line with no active RequestContext = a missing request-wrapping server filter; we\n * report that once (closure latch, via console.error so there is no re-entrancy back\n * into winston and no dependency on LogManager).\n */\n// webpieces-disable no-function-outside-class -- winston format(fn) factory; whole file is winston Format factories\nexport function injectContextFormat(): Format {\n let reportedMissingContext = false;\n return format((info: TransformableInfo) => {\n if (RequestContext.isActive()) {\n // ONE loop, in HeaderRegistry.buildLogFields. Caller-supplied fields win on conflict.\n RequestContext.buildLogFields().forEach((value: string, name: string) => {\n if (info[name] === undefined) {\n info[name] = value;\n }\n });\n } else if (!reportedMissingContext) {\n reportedMissingContext = true;\n // This IS a logging backend; direct stderr for the framework-misconfig warning.\n console.error(\n 'Log emitted OUTSIDE RequestContext.run(...) — every request must be wrapped in ' +\n 'RequestContext.run() by a server filter. That filter appears to be missing: ' +\n 'correlation fields (requestId, tenant, ...) will be absent from logs. Reported once.',\n );\n }\n return info;\n })();\n}\n\n/**\n * Map the winston level onto a top-level `severity` field that the Cloud Logging\n * agent lifts onto the LogEntry.\n */\nexport function severityFormat(): Format {\n return format((info: TransformableInfo) => {\n info['severity'] = LEVEL_TO_SEVERITY[info.level] || info.level.toUpperCase();\n return info;\n })();\n}\n\n// Fields that are rendered specially (or not at all) by the local pretty format,\n// so they must not leak into the trailing \"extra\" JSON blob.\nconst LOCAL_STRUCTURAL_KEYS = new Set<string>(['level', 'message', 'severity', 'svcGitHash', 'loggerName']);\n\n/**\n * Local-only human format: `[loggerName] [requestId=… tenantId=…] level: message { …extra }`.\n * The registered context keys (already injected by injectContextFormat) render as\n * a bracketed prefix; anything else the caller attached renders as trailing JSON.\n * The set of context-key names is read lazily from the registry (first line).\n */\nexport function localPrettyFormat(): Format {\n let contextNames: Set<string> | undefined;\n return format.printf((info: TransformableInfo) => {\n if (!contextNames) {\n contextNames = new Set(HeaderRegistry.get().getLoggedKeys().map((k: ContextKey) => k.name));\n }\n const prefixBits: string[] = [];\n for (const name of contextNames) {\n const value = info[name];\n if (value != null) {\n prefixBits.push(`${name}=${String(value)}`);\n }\n }\n const prefix = prefixBits.length ? `[${prefixBits.join(' ')}] ` : '';\n const loggerName = info['loggerName'] ? `[${String(info['loggerName'])}] ` : '';\n\n const rest: Record<string, JsonValue> = {};\n for (const key of Object.keys(info)) {\n if (LOCAL_STRUCTURAL_KEYS.has(key) || contextNames.has(key)) {\n continue;\n }\n rest[key] = info[key] as JsonValue;\n }\n const restStr = Object.keys(rest).length ? ` ${safeStringify(rest)}` : '';\n\n return `${loggerName}${prefix}${info.level}: ${info.message}${restStr}`;\n });\n}\n"]}
|