@webpieces/bunyan 0.4.445 → 0.4.447
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/BunyanLogger.js +7 -11
- package/src/BunyanLogger.js.map +1 -1
- package/src/streams.js +7 -4
- package/src/streams.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/bunyan",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.447",
|
|
4
4
|
"description": "Node-only bunyan LoggerFactory backends for webpieces: Console (local pretty) + GCP (@google-cloud/logging-bunyan), 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.4.
|
|
27
|
-
"@webpieces/core-context": "0.4.
|
|
26
|
+
"@webpieces/core-util": "0.4.447",
|
|
27
|
+
"@webpieces/core-context": "0.4.447",
|
|
28
28
|
"bunyan": "1.8.15",
|
|
29
29
|
"@google-cloud/logging-bunyan": "5.1.0",
|
|
30
30
|
"@types/bunyan": "1.8.11"
|
package/src/BunyanLogger.js
CHANGED
|
@@ -50,17 +50,13 @@ class BunyanLogger {
|
|
|
50
50
|
}
|
|
51
51
|
buildFields(err) {
|
|
52
52
|
const fields = {};
|
|
53
|
-
//
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
// ONE loop, in HeaderRegistry.buildStructuredLogFields — the registry owns the keys and each
|
|
61
|
-
// ContextKey masks its own value. Values may be OBJECTS (the `api` tag), so an object-valued key
|
|
62
|
-
// nests into the structured payload (bunyan's GCP stream serializes fields) rather than being
|
|
63
|
-
// dropped by the string-only buildLogFields.
|
|
53
|
+
// Called UNCONDITIONALLY (no active-context short-circuit): buildStructuredLogFields returns the
|
|
54
|
+
// build `version` even with NO active RequestContext — plus the logged context keys when one IS
|
|
55
|
+
// active. Startup, background-job, and unwrapped-call lines are thus stamped with `version` too;
|
|
56
|
+
// an empty context is normal, not an error. (The in-process client's
|
|
57
|
+
// ApiClientFactory.requireActiveContext() still throws precisely when a request-path wrap is
|
|
58
|
+
// genuinely missing.) Values may be OBJECTS (the `api` tag), so an object-valued key nests into
|
|
59
|
+
// the structured payload rather than being dropped by the string-only buildLogFields.
|
|
64
60
|
core_context_1.RequestContext.buildStructuredLogFields().forEach((value, name) => {
|
|
65
61
|
fields[name] = value;
|
|
66
62
|
});
|
package/src/BunyanLogger.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BunyanLogger.js","sourceRoot":"","sources":["../../../../../packages/logging/bunyan/src/BunyanLogger.ts"],"names":[],"mappings":";;;AAEA,0DAAyD;AACzD,+CAA4C;AAE5C;;;;;;;;;GASG;AACH,SAAS,cAAc,CAAC,GAAU;IAC9B,OAAO,IAAI,yBAAW,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAa,YAAY;IACQ;IAA7B,YAA6B,MAAc;QAAd,WAAM,GAAN,MAAM,CAAQ;IAAG,CAAC;IAE/C,KAAK,CAAC,OAAe,EAAE,GAAW;QAC9B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,OAAe,EAAE,GAAW;QAC9B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED,IAAI,CAAC,OAAe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AC,OAAe,EAAE,GAAW;QAC7B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC;IACrD,CAAC;IAED,IAAI,CAAC,OAAe,EAAE,GAAW;QAC7B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC;IACrD,CAAC;IAED,KAAK,CAAC,OAAe,EAAE,GAAW;QAC9B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAEO,WAAW,CAAC,GAAW;QAC3B,MAAM,MAAM,GAAkD,EAAE,CAAC;QACjE,iGAAiG;QACjG,gGAAgG;QAChG,iGAAiG;QACjG,qEAAqE;QACrE,6FAA6F;QAC7F,gGAAgG;QAChG,sFAAsF;QACtF,6BAAc,CAAC,wBAAwB,EAAE,CAAC,OAAO,CAAC,CAAC,KAAsB,EAAE,IAAY,EAAE,EAAE;YACvF,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;QACzB,CAAC,CAAC,CAAC;QACH,IAAI,GAAG,EAAE,CAAC;YACN,MAAM,CAAC,KAAK,CAAC,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;QACxC,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AAxCD,oCAwCC","sourcesContent":["import type Logger from 'bunyan';\nimport type { Logger as WpLogger } from '@webpieces/core-util';\nimport { RequestContext } from '@webpieces/core-context';\nimport { LoggedError } from './LoggedError';\n\n/**\n * The error, whole. There is deliberately NO size guard here any more.\n *\n * This used to truncate an error over 100KB down to 5 stack frames and a 100-character message, to\n * keep one giant stack from blowing past Cloud Logging's per-entry limit. That traded the wrong\n * thing away: a stack trace big enough to trip the limit is precisely the one worth reading, and it\n * arrived pre-shredded. The GCP stream now SPLITS an oversized record across several complete\n * records instead (see ChunkingRawStream), so the whole stack survives and nothing is lost — which\n * makes truncating here strictly harmful.\n */\nfunction normalizeError(err: Error): LoggedError {\n return new LoggedError(err.name, err.message, err.stack);\n}\n\n/**\n * BunyanLogger - a webpieces {@link WpLogger} backed by a bunyan logger (one per\n * name, created as a bunyan child carrying `loggerName`). On every call it reads\n * the logged HeaderRegistry keys DIRECTLY from the active {@link RequestContext}\n * (secured values masked) into the bunyan fields object, and normalizes an optional\n * Error into `err: { name, message, stack }` — matching the tested trytami AppLogger.\n * The GCP stream then serializes those fields into the structured log payload.\n *\n * This context-reading is INLINED here (and duplicated in the winston logger) on\n * purpose: it must run ONLY when a bunyan/winston backend is installed, never for\n * the plain ConsoleLogger — so it does not belong on RequestContext.\n */\nexport class BunyanLogger implements WpLogger {\n constructor(private readonly bunyan: Logger) {}\n\n trace(message: string, err?: Error): void {\n this.bunyan.trace(this.buildFields(err), message);\n }\n\n debug(message: string, err?: Error): void {\n this.bunyan.debug(this.buildFields(err), message);\n }\n\n info(message: string, err?: Error): void {\n this.bunyan.info(this.buildFields(err), message);\n }\n\n warn(message: string, err?: Error): void {\n this.bunyan.warn(this.buildFields(err), message);\n }\n\n error(message: string, err?: Error): void {\n this.bunyan.error(this.buildFields(err), message);\n }\n\n private buildFields(err?: Error): Record<string, string | object | LoggedError> {\n const fields: Record<string, string | object | LoggedError> = {};\n // Called UNCONDITIONALLY (no active-context short-circuit): buildStructuredLogFields returns the\n // build `version` even with NO active RequestContext — plus the logged context keys when one IS\n // active. Startup, background-job, and unwrapped-call lines are thus stamped with `version` too;\n // an empty context is normal, not an error. (The in-process client's\n // ApiClientFactory.requireActiveContext() still throws precisely when a request-path wrap is\n // genuinely missing.) Values may be OBJECTS (the `api` tag), so an object-valued key nests into\n // the structured payload rather than being dropped by the string-only buildLogFields.\n RequestContext.buildStructuredLogFields().forEach((value: string | object, name: string) => {\n fields[name] = value;\n });\n if (err) {\n fields['err'] = normalizeError(err);\n }\n return fields;\n }\n}\n"]}
|
package/src/streams.js
CHANGED
|
@@ -16,11 +16,13 @@ const METHOD_FIELD = 'method';
|
|
|
16
16
|
// bunyan record fields that are structural / rendered specially, so they are not
|
|
17
17
|
// shown as context tags in the local console line.
|
|
18
18
|
//
|
|
19
|
-
// `
|
|
20
|
-
// record.
|
|
21
|
-
//
|
|
19
|
+
// `svcName` (the service) and `version` (the build) are ServiceInfo facts riding on EVERY record
|
|
20
|
+
// (stamped per-record by RequestContext.buildStructuredLogFields — the same map winston reads, so the
|
|
21
|
+
// two backends are symmetrical). `name` is bunyan's own mandatory root-logger field (a fixed
|
|
22
|
+
// placeholder). All three earn their keep in GCP, where you filter across many services and deploys,
|
|
23
|
+
// but locally each service logs to its own place and you can check git yourself — so as a tag on every
|
|
22
24
|
// single line they are pure noise. Listing them here is the bunyan twin of winston's
|
|
23
|
-
// LOCAL_STRUCTURAL_KEYS; GCP still gets
|
|
25
|
+
// LOCAL_STRUCTURAL_KEYS; GCP still gets them (that stream does its own formatting).
|
|
24
26
|
//
|
|
25
27
|
// `loggerName` (its own `[…]` bracket) and `controller`/`method` (the `[Controller.method]` bracket)
|
|
26
28
|
// are rendered specially too, so they are excluded here from the generic `key:value` tag loop.
|
|
@@ -28,6 +30,7 @@ const BUNYAN_STD_FIELDS = new Set([
|
|
|
28
30
|
'v',
|
|
29
31
|
'level',
|
|
30
32
|
'name',
|
|
33
|
+
'svcName',
|
|
31
34
|
'version',
|
|
32
35
|
'hostname',
|
|
33
36
|
'pid',
|
package/src/streams.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streams.js","sourceRoot":"","sources":["../../../../../packages/logging/bunyan/src/streams.ts"],"names":[],"mappings":";;AAiKA,0DAUC;AAWD,kDAWC;;AAjMD,mCAAkC;AAClC,4DAA4B;AAC5B,iEAA6D;AAC7D,oDAAsD;AAEtD,2DAAwD;AAOxD,qGAAqG;AACrG,4FAA4F;AAC5F,kGAAkG;AAClG,MAAM,gBAA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able } from 'stream';\nimport Logger from 'bunyan';\nimport { LoggingBunyan } from '@google-cloud/logging-bunyan';\nimport { ApiCallLogName } from '@webpieces/core-util';\nimport { LoggedError } from './LoggedError';\nimport { ChunkingRawStream } from './ChunkingRawStream';\n\n// A parsed bunyan JSON record: standard fields plus arbitrary injected context\n// tags. Values are whatever JSON holds.\ntype JsonValue = string | number | boolean | object | null;\ntype BunyanRecord = Record<string, JsonValue>;\n\n// The two context keys rendered SPECIALLY (as the compact `[Controller.method]` bracket) rather than\n// as `key:value` tags — they name WHICH CODE ran, the thing you grep for. Kept in sync with\n// WebpiecesCoreHeaders.CONTROLLER / .METHOD by name. They are excluded from the generic tag loop.\nconst CONTROLLER_FIELD = 'controller';\nconst METHOD_FIELD = 'method';\n\n// bunyan record fields that are structural / rendered specially, so they are not\n// shown as context tags in the local console line.\n//\n// `name` (the service) and `version` (the build) are ServiceInfo base fields riding on EVERY\n// record. They earn their keep in GCP, where you filter across many services and deploys, but\n// locally each service logs to its own place and you can check git yourself — so as a tag on every\n// single line they are pure noise. Listing them here is the bunyan twin of winston's\n// LOCAL_STRUCTURAL_KEYS; GCP still gets both (that stream does its own formatting).\n//\n// `loggerName` (its own `[…]` bracket) and `controller`/`method` (the `[Controller.method]` bracket)\n// are rendered specially too, so they are excluded here from the generic `key:value` tag loop.\nconst BUNYAN_STD_FIELDS = new Set<string>([\n 'v',\n 'level',\n 'name',\n 'version',\n 'hostname',\n 'pid',\n 'time',\n 'msg',\n 'src',\n 'err',\n 'loggerName',\n CONTROLLER_FIELD,\n METHOD_FIELD,\n]);\n\n// \"HH:MM:SS.mmm\" in LOCAL time — matching the winston backend (fecha 'HH:mm:ss.SSS') and the trytami\n// format this was tuned for (`Date.toTimeString()`, also local). Parsing the ISO to a Date and reading\n// local fields (rather than splitting the UTC ISO string) is what keeps the two backends byte-identical;\n// milliseconds are zero-padded to 3 digits (trytami's raw `getMilliseconds()` rendered 5ms as \".5\").\n// webpieces-disable no-function-outside-class -- bunyan render helper; whole file is bunyan stream/render factories\nfunction formatTime(iso: JsonValue): string {\n if (typeof iso !== 'string') {\n return '';\n }\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) {\n return iso;\n }\n const p2 = (n: number): string => String(n).padStart(2, '0');\n const p3 = (n: number): string => String(n).padStart(3, '0');\n return `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}.${p3(d.getMilliseconds())}`;\n}\n\n// The compact `[Controller.method]` bracket (or `[Controller]`, or '' when neither is present, e.g. a\n// startup / static / pre-route line). Empty controller drops the whole bracket.\n// webpieces-disable no-function-outside-class -- bunyan render helper; whole file is bunyan stream/render factories\nfunction formatControllerMethod(controller: JsonValue, method: JsonValue): string {\n if (typeof controller !== 'string' || controller.length === 0) {\n return '';\n }\n const suffix = typeof method === 'string' && method.length > 0 ? `.${method}` : '';\n return `[${controller}${suffix}]`;\n}\n\n// Build the ordered `key:value` context tags. When `fields` is given it is an app-chosen ALLOW-LIST:\n// only those keys render, in that order (specials skipped). When absent, every non-structural string\n// field renders in record order. Empty/object-valued fields are dropped either way.\n// webpieces-disable no-function-outside-class -- bunyan render helper; whole file is bunyan stream/render factories\nfunction buildTags(obj: BunyanRecord, fields?: string[]): string[] {\n const tags: string[] = [];\n const push = (key: string): void => {\n const value = obj[key];\n if (typeof value === 'object' || value == null) {\n return;\n }\n const str = String(value);\n if (str.length === 0) {\n return;\n }\n tags.push(`${key}:${str}`);\n };\n if (fields) {\n for (const key of fields) {\n if (key === CONTROLLER_FIELD || key === METHOD_FIELD || key === 'loggerName') {\n continue;\n }\n push(key);\n }\n } else {\n for (const key of Object.keys(obj)) {\n if (BUNYAN_STD_FIELDS.has(key)) {\n continue;\n }\n push(key);\n }\n }\n return tags;\n}\n\n/**\n * Render one bunyan JSON line as a human-readable, greppable console line:\n * `[LEVEL][time][Controller.method][loggerName][ctx tags]: message` plus multi-line error details.\n * Level FIRST, then time (the ordering the trytami format was tuned for). `controller`/`method` render\n * as a compact bracket, `loggerName` as its own bracket, and every other injected context key becomes a\n * `key:value` tag (optionally filtered/ordered by the app `fields` allow-list).\n */\n// webpieces-disable no-function-outside-class -- bunyan render helper; whole file is bunyan stream/render factories\nfunction writeConsole(line: string, fields?: string[]): void {\n const obj: BunyanRecord = JSON.parse(line);\n const levelName = (Logger.nameFromLevel[obj['level'] as number] ?? 'info').toUpperCase().padEnd(5);\n const time = formatTime(obj['time']);\n\n const controllerMethod = formatControllerMethod(obj[CONTROLLER_FIELD], obj[METHOD_FIELD]);\n // LogApiCall lines render as a self-describing [API.{side}.{phase}] bracket instead of the opaque\n // [LogApiCall]; every other line keeps its plain [loggerName] bracket.\n const loggerBracket = ApiCallLogName.bracket(obj['loggerName'], obj['api']);\n\n const tags = buildTags(obj, fields);\n const tagStr = tags.length > 0 ? tags.join(', ') : 'no-context';\n\n let message = `[${levelName}][${time}]${controllerMethod}${loggerBracket}[${tagStr}]: ${String(obj['msg'] ?? '')}`;\n\n const err = obj['err'] as LoggedError | undefined;\n if (err) {\n message += `\\nError Details:`;\n message += `\\n Message: ${err.message}`;\n message += `\\n Name: ${err.name}`;\n if (err.stack) {\n message += `\\n Stack Trace:\\n${err.stack}`;\n }\n }\n\n // This IS a logging backend (the console sink); direct stdout is intentional.\n console.log(message);\n}\n\n/**\n * The GCP stream: delegates ALL structured-JSON formatting (numeric level → GCP\n * severity, msg→message, trace/httpRequest fields, stripping name/hostname/pid)\n * to @google-cloud/logging-bunyan, exactly as the tested trytami service does.\n * Sends to the Cloud Logging API (needs ADC on the instance).\n *\n * Records pass through a {@link ChunkingRawStream} first, because Cloud Logging caps a LogEntry at\n * 256 KiB and rejects the whole `entries.write` call when one entry exceeds it — so a single fat\n * response body or stack trace can take a batch of good entries down with it. Oversized records are\n * SPLIT into several complete records sharing a `logChunk.uid` rather than lost or truncated.\n *\n * We do NOT filter by level — that is bunyan's job. The stream is created at\n * bunyan's default level ('info'); there is no webpieces level knob.\n */\n// webpieces-disable no-function-outside-class -- bunyan Stream factory; whole file is bunyan stream/render factories\nexport function createGoogleCloudStream(): Logger.Stream {\n const loggingBunyan = new LoggingBunyan();\n // stream('info') returns { level, type: 'raw', stream: loggingBunyan } — we keep bunyan's raw\n // contract and only interpose on the stream it writes records to.\n const gcp = loggingBunyan.stream('info');\n return {\n level: gcp.level,\n type: 'raw',\n stream: new ChunkingRawStream(loggingBunyan),\n };\n}\n\n/**\n * The local dev stream: human-readable text to stdout via {@link writeConsole}.\n * No level is set — bunyan filters at its own default ('info').\n *\n * `consoleFields`, when given, is the app-chosen ordered ALLOW-LIST of context keys to render in the\n * console line (hides noise like `requestPath` locally while GCP still gets every logged key). When\n * omitted, every non-structural context key renders in record order.\n */\n// webpieces-disable no-function-outside-class -- bunyan Stream factory; whole file is bunyan stream/render factories\nexport function createConsoleStream(consoleFields?: string[]): Logger.Stream {\n const writable = new Writable({\n write(chunk: Buffer | string, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {\n writeConsole(chunk.toString(), consoleFields);\n callback();\n },\n });\n return {\n name: 'console',\n stream: writable,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"streams.js","sourceRoot":"","sources":["../../../../../packages/logging/bunyan/src/streams.ts"],"names":[],"mappings":";;AAoKA,0DAUC;AAWD,kDAWC;;AApMD,mCAAkC;AAClC,4DAA4B;AAC5B,iEAA6D;AAC7D,oDAAsD;AAEtD,2DAAwD;AAOxD,qGAAqG;AACrG,4FAA4F;AAC5F,kGAAkG;AAClG,MAAM,gBAAgB,GAAG,YAAY,CAAC;AACtC,MAAM,YAAY,GAAG,QAAQ,CAAC;AAE9B,iFAAiF;AACjF,mDAAmD;AACnD,EAAE;AACF,iGAAiG;AACjG,sGAAsG;AACtG,6FAA6F;AAC7F,qGAAqG;AACrG,uGAAuG;AACvG,qFAAqF;AACrF,oFAAoF;AACpF,EAAE;AACF,qGAAqG;AACrG,+FAA+F;AAC/F,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAS;IACtC,GAAG;IACH,OAAO;IACP,MAAM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,IAAI,EAAE,CAAC;QACnC,IAAI,GAAG,CAAC,KAAK,EAAE,CAAC;YACZ,OAAO,IAAI,qBAAqB,GAAG,CAAC,KAAK,EAAE,CAAC;QAChD,CAAC;IACL,CAAC;IAED,8EAA8E;IAC9E,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACzB,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,qHAAqH;AACrH,SAAgB,uBAAuB;IACnC,MAAM,aAAa,GAAG,IAAI,8BAAa,EAAE,CAAC;IAC1C,8FAA8F;IAC9F,kEAAkE;IAClE,MAAM,GAAG,GAAG,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACzC,OAAO;QACH,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,IAAI,EAAE,KAAK;QACX,MAAM,EAAE,IAAI,qCAAiB,CAAC,aAAa,CAAC;KAC/C,CAAC;AACN,CAAC;AAED;;;;;;;GAOG;AACH,qHAAqH;AACrH,SAAgB,mBAAmB,CAAC,aAAwB;IACxD,MAAM,QAAQ,GAAG,IAAI,iBAAQ,CAAC;QAC1B,KAAK,CAAC,KAAsB,EAAE,SAAyB,EAAE,QAAwC;YAC7F,YAAY,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,aAAa,CAAC,CAAC;YAC9C,QAAQ,EAAE,CAAC;QACf,CAAC;KACJ,CAAC,CAAC;IACH,OAAO;QACH,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,QAAQ;KACnB,CAAC;AACN,CAAC","sourcesContent":["import { Writable } from 'stream';\nimport Logger from 'bunyan';\nimport { LoggingBunyan } from '@google-cloud/logging-bunyan';\nimport { ApiCallLogName } from '@webpieces/core-util';\nimport { LoggedError } from './LoggedError';\nimport { ChunkingRawStream } from './ChunkingRawStream';\n\n// A parsed bunyan JSON record: standard fields plus arbitrary injected context\n// tags. Values are whatever JSON holds.\ntype JsonValue = string | number | boolean | object | null;\ntype BunyanRecord = Record<string, JsonValue>;\n\n// The two context keys rendered SPECIALLY (as the compact `[Controller.method]` bracket) rather than\n// as `key:value` tags — they name WHICH CODE ran, the thing you grep for. Kept in sync with\n// WebpiecesCoreHeaders.CONTROLLER / .METHOD by name. They are excluded from the generic tag loop.\nconst CONTROLLER_FIELD = 'controller';\nconst METHOD_FIELD = 'method';\n\n// bunyan record fields that are structural / rendered specially, so they are not\n// shown as context tags in the local console line.\n//\n// `svcName` (the service) and `version` (the build) are ServiceInfo facts riding on EVERY record\n// (stamped per-record by RequestContext.buildStructuredLogFields — the same map winston reads, so the\n// two backends are symmetrical). `name` is bunyan's own mandatory root-logger field (a fixed\n// placeholder). All three earn their keep in GCP, where you filter across many services and deploys,\n// but locally each service logs to its own place and you can check git yourself — so as a tag on every\n// single line they are pure noise. Listing them here is the bunyan twin of winston's\n// LOCAL_STRUCTURAL_KEYS; GCP still gets them (that stream does its own formatting).\n//\n// `loggerName` (its own `[…]` bracket) and `controller`/`method` (the `[Controller.method]` bracket)\n// are rendered specially too, so they are excluded here from the generic `key:value` tag loop.\nconst BUNYAN_STD_FIELDS = new Set<string>([\n 'v',\n 'level',\n 'name',\n 'svcName',\n 'version',\n 'hostname',\n 'pid',\n 'time',\n 'msg',\n 'src',\n 'err',\n 'loggerName',\n CONTROLLER_FIELD,\n METHOD_FIELD,\n]);\n\n// \"HH:MM:SS.mmm\" in LOCAL time — matching the winston backend (fecha 'HH:mm:ss.SSS') and the trytami\n// format this was tuned for (`Date.toTimeString()`, also local). Parsing the ISO to a Date and reading\n// local fields (rather than splitting the UTC ISO string) is what keeps the two backends byte-identical;\n// milliseconds are zero-padded to 3 digits (trytami's raw `getMilliseconds()` rendered 5ms as \".5\").\n// webpieces-disable no-function-outside-class -- bunyan render helper; whole file is bunyan stream/render factories\nfunction formatTime(iso: JsonValue): string {\n if (typeof iso !== 'string') {\n return '';\n }\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) {\n return iso;\n }\n const p2 = (n: number): string => String(n).padStart(2, '0');\n const p3 = (n: number): string => String(n).padStart(3, '0');\n return `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}.${p3(d.getMilliseconds())}`;\n}\n\n// The compact `[Controller.method]` bracket (or `[Controller]`, or '' when neither is present, e.g. a\n// startup / static / pre-route line). Empty controller drops the whole bracket.\n// webpieces-disable no-function-outside-class -- bunyan render helper; whole file is bunyan stream/render factories\nfunction formatControllerMethod(controller: JsonValue, method: JsonValue): string {\n if (typeof controller !== 'string' || controller.length === 0) {\n return '';\n }\n const suffix = typeof method === 'string' && method.length > 0 ? `.${method}` : '';\n return `[${controller}${suffix}]`;\n}\n\n// Build the ordered `key:value` context tags. When `fields` is given it is an app-chosen ALLOW-LIST:\n// only those keys render, in that order (specials skipped). When absent, every non-structural string\n// field renders in record order. Empty/object-valued fields are dropped either way.\n// webpieces-disable no-function-outside-class -- bunyan render helper; whole file is bunyan stream/render factories\nfunction buildTags(obj: BunyanRecord, fields?: string[]): string[] {\n const tags: string[] = [];\n const push = (key: string): void => {\n const value = obj[key];\n if (typeof value === 'object' || value == null) {\n return;\n }\n const str = String(value);\n if (str.length === 0) {\n return;\n }\n tags.push(`${key}:${str}`);\n };\n if (fields) {\n for (const key of fields) {\n if (key === CONTROLLER_FIELD || key === METHOD_FIELD || key === 'loggerName') {\n continue;\n }\n push(key);\n }\n } else {\n for (const key of Object.keys(obj)) {\n if (BUNYAN_STD_FIELDS.has(key)) {\n continue;\n }\n push(key);\n }\n }\n return tags;\n}\n\n/**\n * Render one bunyan JSON line as a human-readable, greppable console line:\n * `[LEVEL][time][Controller.method][loggerName][ctx tags]: message` plus multi-line error details.\n * Level FIRST, then time (the ordering the trytami format was tuned for). `controller`/`method` render\n * as a compact bracket, `loggerName` as its own bracket, and every other injected context key becomes a\n * `key:value` tag (optionally filtered/ordered by the app `fields` allow-list).\n */\n// webpieces-disable no-function-outside-class -- bunyan render helper; whole file is bunyan stream/render factories\nfunction writeConsole(line: string, fields?: string[]): void {\n const obj: BunyanRecord = JSON.parse(line);\n const levelName = (Logger.nameFromLevel[obj['level'] as number] ?? 'info').toUpperCase().padEnd(5);\n const time = formatTime(obj['time']);\n\n const controllerMethod = formatControllerMethod(obj[CONTROLLER_FIELD], obj[METHOD_FIELD]);\n // LogApiCall lines render as a self-describing [API.{side}.{phase}] bracket instead of the opaque\n // [LogApiCall]; every other line keeps its plain [loggerName] bracket.\n const loggerBracket = ApiCallLogName.bracket(obj['loggerName'], obj['api']);\n\n const tags = buildTags(obj, fields);\n const tagStr = tags.length > 0 ? tags.join(', ') : 'no-context';\n\n let message = `[${levelName}][${time}]${controllerMethod}${loggerBracket}[${tagStr}]: ${String(obj['msg'] ?? '')}`;\n\n const err = obj['err'] as LoggedError | undefined;\n if (err) {\n message += `\\nError Details:`;\n message += `\\n Message: ${err.message}`;\n message += `\\n Name: ${err.name}`;\n if (err.stack) {\n message += `\\n Stack Trace:\\n${err.stack}`;\n }\n }\n\n // This IS a logging backend (the console sink); direct stdout is intentional.\n console.log(message);\n}\n\n/**\n * The GCP stream: delegates ALL structured-JSON formatting (numeric level → GCP\n * severity, msg→message, trace/httpRequest fields, stripping name/hostname/pid)\n * to @google-cloud/logging-bunyan, exactly as the tested trytami service does.\n * Sends to the Cloud Logging API (needs ADC on the instance).\n *\n * Records pass through a {@link ChunkingRawStream} first, because Cloud Logging caps a LogEntry at\n * 256 KiB and rejects the whole `entries.write` call when one entry exceeds it — so a single fat\n * response body or stack trace can take a batch of good entries down with it. Oversized records are\n * SPLIT into several complete records sharing a `logChunk.uid` rather than lost or truncated.\n *\n * We do NOT filter by level — that is bunyan's job. The stream is created at\n * bunyan's default level ('info'); there is no webpieces level knob.\n */\n// webpieces-disable no-function-outside-class -- bunyan Stream factory; whole file is bunyan stream/render factories\nexport function createGoogleCloudStream(): Logger.Stream {\n const loggingBunyan = new LoggingBunyan();\n // stream('info') returns { level, type: 'raw', stream: loggingBunyan } — we keep bunyan's raw\n // contract and only interpose on the stream it writes records to.\n const gcp = loggingBunyan.stream('info');\n return {\n level: gcp.level,\n type: 'raw',\n stream: new ChunkingRawStream(loggingBunyan),\n };\n}\n\n/**\n * The local dev stream: human-readable text to stdout via {@link writeConsole}.\n * No level is set — bunyan filters at its own default ('info').\n *\n * `consoleFields`, when given, is the app-chosen ordered ALLOW-LIST of context keys to render in the\n * console line (hides noise like `requestPath` locally while GCP still gets every logged key). When\n * omitted, every non-structural context key renders in record order.\n */\n// webpieces-disable no-function-outside-class -- bunyan Stream factory; whole file is bunyan stream/render factories\nexport function createConsoleStream(consoleFields?: string[]): Logger.Stream {\n const writable = new Writable({\n write(chunk: Buffer | string, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {\n writeConsole(chunk.toString(), consoleFields);\n callback();\n },\n });\n return {\n name: 'console',\n stream: writable,\n };\n}\n"]}
|