@webpieces/bunyan 0.4.405 → 0.4.407

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/bunyan",
3
- "version": "0.4.405",
3
+ "version": "0.4.407",
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.405",
27
- "@webpieces/core-context": "0.4.405",
26
+ "@webpieces/core-util": "0.4.407",
27
+ "@webpieces/core-context": "0.4.407",
28
28
  "bunyan": "1.8.15",
29
29
  "@google-cloud/logging-bunyan": "5.1.0",
30
30
  "@types/bunyan": "1.8.11"
package/src/streams.js CHANGED
@@ -6,6 +6,7 @@ const tslib_1 = require("tslib");
6
6
  const stream_1 = require("stream");
7
7
  const bunyan_1 = tslib_1.__importDefault(require("bunyan"));
8
8
  const logging_bunyan_1 = require("@google-cloud/logging-bunyan");
9
+ const core_util_1 = require("@webpieces/core-util");
9
10
  const ChunkingRawStream_1 = require("./ChunkingRawStream");
10
11
  // The two context keys rendered SPECIALLY (as the compact `[Controller.method]` bracket) rather than
11
12
  // as `key:value` tags — they name WHICH CODE ran, the thing you grep for. Kept in sync with
@@ -113,7 +114,9 @@ function writeConsole(line, fields) {
113
114
  const levelName = (bunyan_1.default.nameFromLevel[obj['level']] ?? 'info').toUpperCase().padEnd(5);
114
115
  const time = formatTime(obj['time']);
115
116
  const controllerMethod = formatControllerMethod(obj[CONTROLLER_FIELD], obj[METHOD_FIELD]);
116
- const loggerBracket = obj['loggerName'] ? `[${String(obj['loggerName'])}]` : '';
117
+ // LogApiCall lines render as a self-describing [API.{side}.{phase}] bracket instead of the opaque
118
+ // [LogApiCall]; every other line keeps its plain [loggerName] bracket.
119
+ const loggerBracket = core_util_1.ApiCallLogName.bracket(obj['loggerName'], obj['api']);
117
120
  const tags = buildTags(obj, fields);
118
121
  const tagStr = tags.length > 0 ? tags.join(', ') : 'no-context';
119
122
  let message = `[${levelName}][${time}]${controllerMethod}${loggerBracket}[${tagStr}]: ${String(obj['msg'] ?? '')}`;
@@ -1 +1 @@
1
- {"version":3,"file":"streams.js","sourceRoot":"","sources":["../../../../../packages/logging/bunyan/src/streams.ts"],"names":[],"mappings":";;AA8JA,0DAUC;AAWD,kDAWC;;AA9LD,mCAAkC;AAClC,4DAA4B;AAC5B,iEAA6D;AAE7D,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,6FAA6F;AAC7F,8FAA8F;AAC9F,mGAAmG;AACnG,qFAAqF;AACrF,oFAAoF;AACpF,EAAE;AACF,qGAAqG;AACrG,+FAA+F;AAC/F,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAS;IACtC,GAAG;IACH,OAAO;IACP,MAAM;IACN,SAAS;IACT,UAAU;IACV,KAAK;IACL,MAAM;IACN,KAAK;IACL,KAAK;IACL,KAAK;IACL,YAAY;IACZ,gBAAgB;IAChB,YAAY;CACf,CAAC,CAAC;AAEH,qGAAqG;AACrG,uGAAuG;AACvG,yGAAyG;AACzG,qGAAqG;AACrG,oHAAoH;AACpH,SAAS,UAAU,CAAC,GAAc;IAC9B,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC1B,OAAO,EAAE,CAAC;IACd,CAAC;IACD,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;IACxB,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,EAAE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G,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 { 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 const loggerBracket = obj['loggerName'] ? `[${String(obj['loggerName'])}]` : '';\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":";;AAiKA,0DAUC;AAWD,kDAWC;;AAjMD,mCAAkC;AAClC,4DAA4B;AAC5B,iEAA6D;AAC7D,oDAAsD;AAEtD,2DAAwD;AAOxD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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// `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"]}