@webpieces/winston 0.4.394 → 0.4.396
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/README.md +23 -12
- package/package.json +3 -3
- package/src/WinstonConsoleFactory.d.ts +6 -2
- package/src/WinstonConsoleFactory.js +7 -3
- package/src/WinstonConsoleFactory.js.map +1 -1
- package/src/WinstonFactoryBase.d.ts +7 -7
- package/src/WinstonFactoryBase.js +13 -12
- package/src/WinstonFactoryBase.js.map +1 -1
- package/src/WinstonGcpFactory.d.ts +4 -2
- package/src/WinstonGcpFactory.js +5 -3
- package/src/WinstonGcpFactory.js.map +1 -1
- package/src/format.js +13 -1
- package/src/format.js.map +1 -1
- package/src/index.d.ts +13 -2
- package/src/index.js +14 -4
- package/src/index.js.map +1 -1
- package/src/WinstonFactoryOptions.d.ts +0 -24
- package/src/WinstonFactoryOptions.js +0 -26
- package/src/WinstonFactoryOptions.js.map +0 -1
package/README.md
CHANGED
|
@@ -16,26 +16,37 @@ Two factories, both auto-enriching every line with the logged context keys regis
|
|
|
16
16
|
## Usage
|
|
17
17
|
|
|
18
18
|
```ts
|
|
19
|
-
import {
|
|
19
|
+
import { ServiceInfo } from '@webpieces/core-util';
|
|
20
20
|
import { WinstonGcpFactory, WinstonConsoleFactory } from '@webpieces/winston';
|
|
21
|
-
import { RequestContextReader } from '@webpieces/core-context';
|
|
22
21
|
|
|
23
|
-
|
|
22
|
+
// FIRST: identify this service. Both factories read name+version in their CONSTRUCTOR, so this
|
|
23
|
+
// must come before you build one — a forgotten call throws at startup rather than shipping logs
|
|
24
|
+
// that cannot say which build emitted them.
|
|
25
|
+
ServiceInfo.setInfo('my-service', '2.1.0');
|
|
26
|
+
|
|
24
27
|
const loggerFactory = process.env.K_SERVICE
|
|
25
|
-
? new WinstonGcpFactory(
|
|
26
|
-
: new WinstonConsoleFactory(
|
|
28
|
+
? new WinstonGcpFactory()
|
|
29
|
+
: new WinstonConsoleFactory();
|
|
27
30
|
|
|
28
31
|
// Typically you pass loggerFactory to setupRuntime(new RuntimeSetupOptions(loggerFactory, ...)),
|
|
29
32
|
// which calls HeaderRegistry.configure(...) then LogManager.setFactory(loggerFactory) for you.
|
|
30
33
|
```
|
|
31
34
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
any node context package.
|
|
35
|
+
Both factories read the magic context **directly** from `RequestContext` on each line, so
|
|
36
|
+
nothing is threaded in: there is no `ContextReader` constructor argument.
|
|
35
37
|
|
|
36
38
|
## Options
|
|
37
39
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
-
|
|
41
|
-
|
|
40
|
+
There are none — both factories take no arguments.
|
|
41
|
+
|
|
42
|
+
- **Service name + version** — from `ServiceInfo.setInfo(...)` (see above), NOT factory options.
|
|
43
|
+
Every line carries `svcName` and `version`. They live in `@webpieces/core-util` because they
|
|
44
|
+
are facts about the SERVICE, not about winston: the bunyan backend reads the same values, and
|
|
45
|
+
`requestIdSource` reads the name (it records which service minted a request-id).
|
|
46
|
+
- **`version` is opaque** — a git SHA, a semver tag, a CI build number, whatever identifies your
|
|
47
|
+
build. webpieces neither parses nor derives it; your app decides where it comes from.
|
|
48
|
+
- **Local rendering** — neither `svcName` nor `version` renders in `WinstonConsoleFactory` output.
|
|
49
|
+
They earn their keep in GCP (filtering across many services and deploys); locally each service
|
|
50
|
+
logs to its own place and you can check git yourself, so on every line they are just noise.
|
|
51
|
+
- **Level** — there is deliberately no knob. webpieces does not filter by level; winston filters
|
|
52
|
+
at its own default.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/winston",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.396",
|
|
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.4.
|
|
27
|
-
"@webpieces/core-context": "0.4.
|
|
26
|
+
"@webpieces/core-util": "0.4.396",
|
|
27
|
+
"@webpieces/core-context": "0.4.396",
|
|
28
28
|
"winston": "3.11.0",
|
|
29
29
|
"logform": "2.7.0",
|
|
30
30
|
"safe-stable-stringify": "2.5.0"
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { WinstonFactoryBase } from './WinstonFactoryBase';
|
|
2
|
-
import { WinstonFactoryOptions } from './WinstonFactoryOptions';
|
|
3
2
|
/**
|
|
4
3
|
* WinstonConsoleFactory - the LOCAL developer backend. Colorized single-line
|
|
5
4
|
* pretty console output with the registered context keys as a bracketed prefix,
|
|
6
5
|
* for human reading — same enrichment as the GCP backend, different rendering.
|
|
7
6
|
* Matches the tested onetablet/monorepo-nx1 local logger.
|
|
7
|
+
*
|
|
8
|
+
* The service name + version come from {@link ServiceInfo} (this constructor reads them), but
|
|
9
|
+
* neither RENDERS locally: you already know which service you are running and can check git
|
|
10
|
+
* yourself, so they would be noise on every line. They still ship to GCP via the sibling
|
|
11
|
+
* {@link WinstonGcpFactory}. See LOCAL_STRUCTURAL_KEYS in ./format.
|
|
8
12
|
*/
|
|
9
13
|
export declare class WinstonConsoleFactory extends WinstonFactoryBase {
|
|
10
|
-
constructor(
|
|
14
|
+
constructor();
|
|
11
15
|
}
|
|
@@ -3,17 +3,21 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.WinstonConsoleFactory = void 0;
|
|
4
4
|
const winston_1 = require("winston");
|
|
5
5
|
const WinstonFactoryBase_1 = require("./WinstonFactoryBase");
|
|
6
|
-
const WinstonFactoryOptions_1 = require("./WinstonFactoryOptions");
|
|
7
6
|
const format_1 = require("./format");
|
|
8
7
|
/**
|
|
9
8
|
* WinstonConsoleFactory - the LOCAL developer backend. Colorized single-line
|
|
10
9
|
* pretty console output with the registered context keys as a bracketed prefix,
|
|
11
10
|
* for human reading — same enrichment as the GCP backend, different rendering.
|
|
12
11
|
* Matches the tested onetablet/monorepo-nx1 local logger.
|
|
12
|
+
*
|
|
13
|
+
* The service name + version come from {@link ServiceInfo} (this constructor reads them), but
|
|
14
|
+
* neither RENDERS locally: you already know which service you are running and can check git
|
|
15
|
+
* yourself, so they would be noise on every line. They still ship to GCP via the sibling
|
|
16
|
+
* {@link WinstonGcpFactory}. See LOCAL_STRUCTURAL_KEYS in ./format.
|
|
13
17
|
*/
|
|
14
18
|
class WinstonConsoleFactory extends WinstonFactoryBase_1.WinstonFactoryBase {
|
|
15
|
-
constructor(
|
|
16
|
-
super(winston_1.format.combine((0, format_1.bigIntSafeFormat)(), (0, format_1.injectContextFormat)(), (0, format_1.severityFormat)(), winston_1.format.colorize(), (0, format_1.localPrettyFormat)())
|
|
19
|
+
constructor() {
|
|
20
|
+
super(winston_1.format.combine((0, format_1.bigIntSafeFormat)(), (0, format_1.injectContextFormat)(), (0, format_1.severityFormat)(), winston_1.format.colorize(), (0, format_1.localPrettyFormat)()));
|
|
17
21
|
}
|
|
18
22
|
}
|
|
19
23
|
exports.WinstonConsoleFactory = WinstonConsoleFactory;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WinstonConsoleFactory.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/WinstonConsoleFactory.ts"],"names":[],"mappings":";;;AAAA,qCAAiC;AACjC,6DAA0D;AAC1D,
|
|
1
|
+
{"version":3,"file":"WinstonConsoleFactory.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/WinstonConsoleFactory.ts"],"names":[],"mappings":";;;AAAA,qCAAiC;AACjC,6DAA0D;AAC1D,qCAAoG;AAEpG;;;;;;;;;;GAUG;AACH,MAAa,qBAAsB,SAAQ,uCAAkB;IACzD;QACI,KAAK,CACD,gBAAM,CAAC,OAAO,CACV,IAAA,yBAAgB,GAAE,EAClB,IAAA,4BAAmB,GAAE,EACrB,IAAA,uBAAc,GAAE,EAChB,gBAAM,CAAC,QAAQ,EAAE,EACjB,IAAA,0BAAiB,GAAE,CACtB,CACJ,CAAC;IACN,CAAC;CACJ;AAZD,sDAYC","sourcesContent":["import { format } from 'winston';\nimport { WinstonFactoryBase } from './WinstonFactoryBase';\nimport { bigIntSafeFormat, injectContextFormat, localPrettyFormat, severityFormat } from './format';\n\n/**\n * WinstonConsoleFactory - the LOCAL developer backend. Colorized single-line\n * pretty console output with the registered context keys as a bracketed prefix,\n * for human reading — same enrichment as the GCP backend, different rendering.\n * Matches the tested onetablet/monorepo-nx1 local logger.\n *\n * The service name + version come from {@link ServiceInfo} (this constructor reads them), but\n * neither RENDERS locally: you already know which service you are running and can check git\n * yourself, so they would be noise on every line. They still ship to GCP via the sibling\n * {@link WinstonGcpFactory}. See LOCAL_STRUCTURAL_KEYS in ./format.\n */\nexport class WinstonConsoleFactory extends WinstonFactoryBase {\n constructor() {\n super(\n format.combine(\n bigIntSafeFormat(),\n injectContextFormat(),\n severityFormat(),\n format.colorize(),\n localPrettyFormat(),\n ),\n );\n }\n}\n"]}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { Format } from 'logform';
|
|
2
2
|
import type { Logger, LoggerFactory } from '@webpieces/core-util';
|
|
3
|
-
import { WinstonFactoryOptions } from './WinstonFactoryOptions';
|
|
4
3
|
/**
|
|
5
4
|
* WinstonFactoryBase - shared plumbing for the winston {@link LoggerFactory}
|
|
6
5
|
* backends. Builds ONE underlying winston logger (a single `Console` transport,
|
|
@@ -8,15 +7,16 @@ import { WinstonFactoryOptions } from './WinstonFactoryOptions';
|
|
|
8
7
|
* out a cached {@link WinstonLogger} per name (each a winston child carrying
|
|
9
8
|
* `loggerName`). Subclasses differ only in the format stack they pass up.
|
|
10
9
|
*
|
|
11
|
-
* Every line carries `svcName` from {@link ServiceInfo}.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
10
|
+
* Every line carries `svcName` + `version` from {@link ServiceInfo}. Neither used to be a property
|
|
11
|
+
* of the SERVICE: winston has no mandatory logger name (so this backend emitted none — a winston
|
|
12
|
+
* service was distinguishable only by GCP's own resource labels), and the version lived here as an
|
|
13
|
+
* optional `svcGitHash` factory option that bunyan had no counterpart for. Both now come from the
|
|
14
|
+
* ONE {@link ServiceInfo}, so the fields on your logs no longer depend on which logging library the
|
|
15
|
+
* app happened to pick. `version` is opaque — whatever string the app used to identify its build.
|
|
16
16
|
*/
|
|
17
17
|
export declare abstract class WinstonFactoryBase implements LoggerFactory {
|
|
18
18
|
private readonly base;
|
|
19
19
|
private readonly loggers;
|
|
20
|
-
protected constructor(finalFormat: Format
|
|
20
|
+
protected constructor(finalFormat: Format);
|
|
21
21
|
getLogger(name: string): Logger;
|
|
22
22
|
}
|
|
@@ -11,22 +11,23 @@ const WinstonLogger_1 = require("./WinstonLogger");
|
|
|
11
11
|
* out a cached {@link WinstonLogger} per name (each a winston child carrying
|
|
12
12
|
* `loggerName`). Subclasses differ only in the format stack they pass up.
|
|
13
13
|
*
|
|
14
|
-
* Every line carries `svcName` from {@link ServiceInfo}.
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
14
|
+
* Every line carries `svcName` + `version` from {@link ServiceInfo}. Neither used to be a property
|
|
15
|
+
* of the SERVICE: winston has no mandatory logger name (so this backend emitted none — a winston
|
|
16
|
+
* service was distinguishable only by GCP's own resource labels), and the version lived here as an
|
|
17
|
+
* optional `svcGitHash` factory option that bunyan had no counterpart for. Both now come from the
|
|
18
|
+
* ONE {@link ServiceInfo}, so the fields on your logs no longer depend on which logging library the
|
|
19
|
+
* app happened to pick. `version` is opaque — whatever string the app used to identify its build.
|
|
19
20
|
*/
|
|
20
21
|
class WinstonFactoryBase {
|
|
21
22
|
base;
|
|
22
23
|
loggers = new Map();
|
|
23
|
-
constructor(finalFormat
|
|
24
|
-
// Read at STARTUP (this ctor runs while booting), so a forgotten ServiceInfo.
|
|
25
|
-
// fails the deploy rather than shipping
|
|
26
|
-
const defaultMeta = {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
}
|
|
24
|
+
constructor(finalFormat) {
|
|
25
|
+
// Read at STARTUP (this ctor runs while booting), so a forgotten ServiceInfo.setInfo(...)
|
|
26
|
+
// fails the deploy rather than shipping logs that cannot say which build emitted them.
|
|
27
|
+
const defaultMeta = {
|
|
28
|
+
svcName: core_util_1.ServiceInfo.getName(),
|
|
29
|
+
version: core_util_1.ServiceInfo.getVersion(),
|
|
30
|
+
};
|
|
30
31
|
// No level set — we do NOT filter; that is winston's job (defaults to 'info').
|
|
31
32
|
this.base = (0, winston_1.createLogger)({
|
|
32
33
|
format: finalFormat,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WinstonFactoryBase.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/WinstonFactoryBase.ts"],"names":[],"mappings":";;;AAAA,qCAAmD;AAInD,oDAAmD;AACnD,mDAAgD;
|
|
1
|
+
{"version":3,"file":"WinstonFactoryBase.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/WinstonFactoryBase.ts"],"names":[],"mappings":";;;AAAA,qCAAmD;AAInD,oDAAmD;AACnD,mDAAgD;AAEhD;;;;;;;;;;;;;GAaG;AACH,MAAsB,kBAAkB;IACnB,IAAI,CAAc;IAClB,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAErD,YAAsB,WAAmB;QACrC,0FAA0F;QAC1F,uFAAuF;QACvF,MAAM,WAAW,GAA2B;YACxC,OAAO,EAAE,uBAAW,CAAC,OAAO,EAAE;YAC9B,OAAO,EAAE,uBAAW,CAAC,UAAU,EAAE;SACpC,CAAC;QAEF,+EAA+E;QAC/E,IAAI,CAAC,IAAI,GAAG,IAAA,sBAAY,EAAC;YACrB,MAAM,EAAE,WAAW;YACnB,WAAW,EAAE,WAAW;YACxB,UAAU,EAAE,CAAC,IAAI,oBAAU,CAAC,OAAO,EAAE,CAAC;YACtC,gBAAgB,EAAE,IAAI;YACtB,gBAAgB,EAAE,IAAI;SACzB,CAAC,CAAC;IACP,CAAC;IAED,SAAS,CAAC,IAAY;QAClB,IAAI,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,CAAC,MAAM,EAAE,CAAC;YACV,MAAM,GAAG,IAAI,6BAAa,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;YAClE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACnC,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AA9BD,gDA8BC","sourcesContent":["import { createLogger, transports } from 'winston';\nimport type { Logger as WinstonBase } from 'winston';\nimport type { Format } from 'logform';\nimport type { Logger, LoggerFactory } from '@webpieces/core-util';\nimport { ServiceInfo } from '@webpieces/core-util';\nimport { WinstonLogger } from './WinstonLogger';\n\n/**\n * WinstonFactoryBase - shared plumbing for the winston {@link LoggerFactory}\n * backends. Builds ONE underlying winston logger (a single `Console` transport,\n * handleExceptions/Rejections on) with the caller-chosen format stack, then hands\n * out a cached {@link WinstonLogger} per name (each a winston child carrying\n * `loggerName`). Subclasses differ only in the format stack they pass up.\n *\n * Every line carries `svcName` + `version` from {@link ServiceInfo}. Neither used to be a property\n * of the SERVICE: winston has no mandatory logger name (so this backend emitted none — a winston\n * service was distinguishable only by GCP's own resource labels), and the version lived here as an\n * optional `svcGitHash` factory option that bunyan had no counterpart for. Both now come from the\n * ONE {@link ServiceInfo}, so the fields on your logs no longer depend on which logging library the\n * app happened to pick. `version` is opaque — whatever string the app used to identify its build.\n */\nexport abstract class WinstonFactoryBase implements LoggerFactory {\n private readonly base: WinstonBase;\n private readonly loggers = new Map<string, Logger>();\n\n protected constructor(finalFormat: Format) {\n // Read at STARTUP (this ctor runs while booting), so a forgotten ServiceInfo.setInfo(...)\n // fails the deploy rather than shipping logs that cannot say which build emitted them.\n const defaultMeta: Record<string, string> = {\n svcName: ServiceInfo.getName(),\n version: ServiceInfo.getVersion(),\n };\n\n // No level set — we do NOT filter; that is winston's job (defaults to 'info').\n this.base = createLogger({\n format: finalFormat,\n defaultMeta: defaultMeta,\n transports: [new transports.Console()],\n handleExceptions: true,\n handleRejections: true,\n });\n }\n\n getLogger(name: string): Logger {\n let logger = this.loggers.get(name);\n if (!logger) {\n logger = new WinstonLogger(this.base.child({ loggerName: name }));\n this.loggers.set(name, logger);\n }\n return logger;\n }\n}\n"]}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { WinstonFactoryBase } from './WinstonFactoryBase';
|
|
2
|
-
import { WinstonFactoryOptions } from './WinstonFactoryOptions';
|
|
3
2
|
/**
|
|
4
3
|
* WinstonGcpFactory - the GCP/Cloud Run backend. Emits flat JSON to stdout; the
|
|
5
4
|
* Cloud Run / GKE logging agent natively parses it — `severity` + `message` lift
|
|
@@ -8,7 +7,10 @@ import { WinstonFactoryOptions } from './WinstonFactoryOptions';
|
|
|
8
7
|
* @google-cloud transport — correlation rides the webpieces context, read
|
|
9
8
|
* DIRECTLY from RequestContext on each line. This matches the tested-in-GCP
|
|
10
9
|
* onetablet/monorepo-nx1 core logger exactly.
|
|
10
|
+
*
|
|
11
|
+
* The service name + version come from {@link ServiceInfo}, which startup must have populated
|
|
12
|
+
* (this constructor reads them); they are NOT factory options.
|
|
11
13
|
*/
|
|
12
14
|
export declare class WinstonGcpFactory extends WinstonFactoryBase {
|
|
13
|
-
constructor(
|
|
15
|
+
constructor();
|
|
14
16
|
}
|
package/src/WinstonGcpFactory.js
CHANGED
|
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.WinstonGcpFactory = void 0;
|
|
4
4
|
const winston_1 = require("winston");
|
|
5
5
|
const WinstonFactoryBase_1 = require("./WinstonFactoryBase");
|
|
6
|
-
const WinstonFactoryOptions_1 = require("./WinstonFactoryOptions");
|
|
7
6
|
const format_1 = require("./format");
|
|
8
7
|
/**
|
|
9
8
|
* WinstonGcpFactory - the GCP/Cloud Run backend. Emits flat JSON to stdout; the
|
|
@@ -13,10 +12,13 @@ const format_1 = require("./format");
|
|
|
13
12
|
* @google-cloud transport — correlation rides the webpieces context, read
|
|
14
13
|
* DIRECTLY from RequestContext on each line. This matches the tested-in-GCP
|
|
15
14
|
* onetablet/monorepo-nx1 core logger exactly.
|
|
15
|
+
*
|
|
16
|
+
* The service name + version come from {@link ServiceInfo}, which startup must have populated
|
|
17
|
+
* (this constructor reads them); they are NOT factory options.
|
|
16
18
|
*/
|
|
17
19
|
class WinstonGcpFactory extends WinstonFactoryBase_1.WinstonFactoryBase {
|
|
18
|
-
constructor(
|
|
19
|
-
super(winston_1.format.combine((0, format_1.bigIntSafeFormat)(), (0, format_1.injectContextFormat)(), (0, format_1.severityFormat)(), winston_1.format.json())
|
|
20
|
+
constructor() {
|
|
21
|
+
super(winston_1.format.combine((0, format_1.bigIntSafeFormat)(), (0, format_1.injectContextFormat)(), (0, format_1.severityFormat)(), winston_1.format.json()));
|
|
20
22
|
}
|
|
21
23
|
}
|
|
22
24
|
exports.WinstonGcpFactory = WinstonGcpFactory;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WinstonGcpFactory.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/WinstonGcpFactory.ts"],"names":[],"mappings":";;;AAAA,qCAAiC;AACjC,6DAA0D;AAC1D,
|
|
1
|
+
{"version":3,"file":"WinstonGcpFactory.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/WinstonGcpFactory.ts"],"names":[],"mappings":";;;AAAA,qCAAiC;AACjC,6DAA0D;AAC1D,qCAAiF;AAEjF;;;;;;;;;;;GAWG;AACH,MAAa,iBAAkB,SAAQ,uCAAkB;IACrD;QACI,KAAK,CACD,gBAAM,CAAC,OAAO,CACV,IAAA,yBAAgB,GAAE,EAClB,IAAA,4BAAmB,GAAE,EACrB,IAAA,uBAAc,GAAE,EAChB,gBAAM,CAAC,IAAI,EAAE,CAChB,CACJ,CAAC;IACN,CAAC;CACJ;AAXD,8CAWC","sourcesContent":["import { format } from 'winston';\nimport { WinstonFactoryBase } from './WinstonFactoryBase';\nimport { bigIntSafeFormat, injectContextFormat, severityFormat } from './format';\n\n/**\n * WinstonGcpFactory - the GCP/Cloud Run backend. Emits flat JSON to stdout; the\n * Cloud Run / GKE logging agent natively parses it — `severity` + `message` lift\n * onto the LogEntry and every registered context key lands at top-level\n * jsonPayload.<name> (requestId, tenantId, …), filterable directly. There is NO\n * @google-cloud transport — correlation rides the webpieces context, read\n * DIRECTLY from RequestContext on each line. This matches the tested-in-GCP\n * onetablet/monorepo-nx1 core logger exactly.\n *\n * The service name + version come from {@link ServiceInfo}, which startup must have populated\n * (this constructor reads them); they are NOT factory options.\n */\nexport class WinstonGcpFactory extends WinstonFactoryBase {\n constructor() {\n super(\n format.combine(\n bigIntSafeFormat(),\n injectContextFormat(),\n severityFormat(),\n format.json(),\n ),\n );\n }\n}\n"]}
|
package/src/format.js
CHANGED
|
@@ -106,7 +106,19 @@ function severityFormat() {
|
|
|
106
106
|
}
|
|
107
107
|
// Fields that are rendered specially (or not at all) by the local pretty format,
|
|
108
108
|
// so they must not leak into the trailing "extra" JSON blob.
|
|
109
|
-
|
|
109
|
+
//
|
|
110
|
+
// `svcName` + `version` (the ServiceInfo defaultMeta fields) are here to be rendered NOT AT ALL:
|
|
111
|
+
// they earn their keep in GCP, where you filter across many services and deploys, but locally each
|
|
112
|
+
// service logs to its own place and you can check git yourself — so on every single line they are
|
|
113
|
+
// pure noise. GCP still gets both (this set only affects localPrettyFormat).
|
|
114
|
+
const LOCAL_STRUCTURAL_KEYS = new Set([
|
|
115
|
+
'level',
|
|
116
|
+
'message',
|
|
117
|
+
'severity',
|
|
118
|
+
'svcName',
|
|
119
|
+
'version',
|
|
120
|
+
'loggerName',
|
|
121
|
+
]);
|
|
110
122
|
/**
|
|
111
123
|
* Local-only human format: `[loggerName] [requestId=… tenantId=…] level: message { …extra }`.
|
|
112
124
|
* The registered context keys (already injected by injectContextFormat) render as
|
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,kDAwBC;AAMD,wCAKC;AAYD,8CAmCC;AAhKD;;;;;;;;;;;;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;IAC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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.buildStructuredLogFields. Values may be OBJECTS (the `api`\n // tag), so an object-valued key nests into jsonPayload.<name> (winston JSON-serializes the\n // whole record) rather than being dropped by the string-only buildLogFields. Caller-supplied\n // fields win on conflict.\n RequestContext.buildStructuredLogFields().forEach((value: string | object, 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 // Only STRING context values render in the bracket prefix. An object-valued key (the `api`\n // tag) would stringify to \"[object Object]\" here, so it is left out of the prefix and instead\n // falls into the trailing JSON blob below (readable), while GCP still gets it nested.\n const prefixBits: string[] = [];\n for (const name of contextNames) {\n const value = info[name];\n if (value != null && typeof value === 'string') {\n prefixBits.push(`${name}=${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)) {\n continue;\n }\n // A context key already shown in the bracket prefix (string value) is skipped; an\n // object-valued context key (api) was NOT shown there, so let it render as trailing JSON.\n if (contextNames.has(key) && typeof info[key] === 'string') {\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,kDAwBC;AAMD,wCAKC;AAwBD,8CAmCC;AA5KD;;;;;;;;;;;;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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,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,QAAQ,EAAE,CAAC;gBACzD,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.buildStructuredLogFields. Values may be OBJECTS (the `api`\n // tag), so an object-valued key nests into jsonPayload.<name> (winston JSON-serializes the\n // whole record) rather than being dropped by the string-only buildLogFields. Caller-supplied\n // fields win on conflict.\n RequestContext.buildStructuredLogFields().forEach((value: string | object, 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.\n//\n// `svcName` + `version` (the ServiceInfo defaultMeta fields) are here to be rendered NOT AT ALL:\n// they earn their keep in GCP, where you filter across many services and deploys, but locally each\n// service logs to its own place and you can check git yourself — so on every single line they are\n// pure noise. GCP still gets both (this set only affects localPrettyFormat).\nconst LOCAL_STRUCTURAL_KEYS = new Set<string>([\n 'level',\n 'message',\n 'severity',\n 'svcName',\n 'version',\n 'loggerName',\n]);\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 // Only STRING context values render in the bracket prefix. An object-valued key (the `api`\n // tag) would stringify to \"[object Object]\" here, so it is left out of the prefix and instead\n // falls into the trailing JSON blob below (readable), while GCP still gets it nested.\n const prefixBits: string[] = [];\n for (const name of contextNames) {\n const value = info[name];\n if (value != null && typeof value === 'string') {\n prefixBits.push(`${name}=${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)) {\n continue;\n }\n // A context key already shown in the bracket prefix (string value) is skipped; an\n // object-valued context key (api) was NOT shown there, so let it render as trailing JSON.\n if (contextNames.has(key) && typeof info[key] === 'string') {\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"]}
|
package/src/index.d.ts
CHANGED
|
@@ -5,22 +5,33 @@
|
|
|
5
5
|
* startup via `LogManager.setFactory(...)`:
|
|
6
6
|
*
|
|
7
7
|
* ```ts
|
|
8
|
+
* import { ServiceInfo } from '@webpieces/core-util';
|
|
8
9
|
* import { WinstonGcpFactory, WinstonConsoleFactory } from '@webpieces/winston';
|
|
9
10
|
*
|
|
11
|
+
* ServiceInfo.setInfo('my-service', '2.1.0'); // FIRST — the factories read it in their constructor
|
|
10
12
|
* const loggerFactory = process.env.K_SERVICE
|
|
11
13
|
* ? new WinstonGcpFactory() // Cloud Run → stdout JSON
|
|
12
14
|
* : new WinstonConsoleFactory(); // local → pretty console
|
|
13
15
|
* // hand to setupRuntime(new RuntimeSetupOptions(loggerFactory, ...))
|
|
14
16
|
* ```
|
|
15
17
|
*
|
|
18
|
+
* BREAKING (was `new WinstonFactoryOptions(svcGitHash)` passed to each factory): the version moved
|
|
19
|
+
* to `ServiceInfo.setInfo(name, version)` in @webpieces/core-util, because it is a fact about the
|
|
20
|
+
* SERVICE, not about winston — bunyan needs the same version and previously could not stamp one at
|
|
21
|
+
* all. It is also no longer presumed to be a git SHA: `version` is opaque, so a project deploying
|
|
22
|
+
* semver or CI build numbers is no longer misdescribed. Migration: delete the `WinstonFactoryOptions`
|
|
23
|
+
* import, call `ServiceInfo.setInfo(<name>, <the same hash>)` before building the factory, and drop
|
|
24
|
+
* the ctor argument. A forgotten call throws at startup. Note the field renamed `svcGitHash` →
|
|
25
|
+
* `version`, so GCP log filters/alerts on `jsonPayload.svcGitHash` must be updated.
|
|
26
|
+
*
|
|
16
27
|
* Both backends auto-enrich every line with the logged context keys, read
|
|
17
28
|
* DIRECTLY from the active RequestContext (@webpieces/core-context) on each line —
|
|
18
|
-
* no ContextReader is threaded in.
|
|
29
|
+
* no ContextReader is threaded in. Every line also carries `svcName` + `version` from ServiceInfo,
|
|
30
|
+
* though neither renders in the LOCAL pretty format (you know your own service, and can check git).
|
|
19
31
|
*
|
|
20
32
|
* @packageDocumentation
|
|
21
33
|
*/
|
|
22
34
|
export { WinstonGcpFactory } from './WinstonGcpFactory';
|
|
23
35
|
export { WinstonConsoleFactory } from './WinstonConsoleFactory';
|
|
24
|
-
export { WinstonFactoryOptions } from './WinstonFactoryOptions';
|
|
25
36
|
export { WinstonLogger, LEVEL_TO_WINSTON } from './WinstonLogger';
|
|
26
37
|
export { LEVEL_TO_SEVERITY, bigIntSafeFormat, injectContextFormat, severityFormat, localPrettyFormat, } from './format';
|
package/src/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.localPrettyFormat = exports.severityFormat = exports.injectContextFormat = exports.bigIntSafeFormat = exports.LEVEL_TO_SEVERITY = exports.LEVEL_TO_WINSTON = exports.WinstonLogger = exports.
|
|
3
|
+
exports.localPrettyFormat = exports.severityFormat = exports.injectContextFormat = exports.bigIntSafeFormat = exports.LEVEL_TO_SEVERITY = exports.LEVEL_TO_WINSTON = exports.WinstonLogger = exports.WinstonConsoleFactory = exports.WinstonGcpFactory = void 0;
|
|
4
4
|
/**
|
|
5
5
|
* @webpieces/winston
|
|
6
6
|
*
|
|
@@ -8,17 +8,29 @@ exports.localPrettyFormat = exports.severityFormat = exports.injectContextFormat
|
|
|
8
8
|
* startup via `LogManager.setFactory(...)`:
|
|
9
9
|
*
|
|
10
10
|
* ```ts
|
|
11
|
+
* import { ServiceInfo } from '@webpieces/core-util';
|
|
11
12
|
* import { WinstonGcpFactory, WinstonConsoleFactory } from '@webpieces/winston';
|
|
12
13
|
*
|
|
14
|
+
* ServiceInfo.setInfo('my-service', '2.1.0'); // FIRST — the factories read it in their constructor
|
|
13
15
|
* const loggerFactory = process.env.K_SERVICE
|
|
14
16
|
* ? new WinstonGcpFactory() // Cloud Run → stdout JSON
|
|
15
17
|
* : new WinstonConsoleFactory(); // local → pretty console
|
|
16
18
|
* // hand to setupRuntime(new RuntimeSetupOptions(loggerFactory, ...))
|
|
17
19
|
* ```
|
|
18
20
|
*
|
|
21
|
+
* BREAKING (was `new WinstonFactoryOptions(svcGitHash)` passed to each factory): the version moved
|
|
22
|
+
* to `ServiceInfo.setInfo(name, version)` in @webpieces/core-util, because it is a fact about the
|
|
23
|
+
* SERVICE, not about winston — bunyan needs the same version and previously could not stamp one at
|
|
24
|
+
* all. It is also no longer presumed to be a git SHA: `version` is opaque, so a project deploying
|
|
25
|
+
* semver or CI build numbers is no longer misdescribed. Migration: delete the `WinstonFactoryOptions`
|
|
26
|
+
* import, call `ServiceInfo.setInfo(<name>, <the same hash>)` before building the factory, and drop
|
|
27
|
+
* the ctor argument. A forgotten call throws at startup. Note the field renamed `svcGitHash` →
|
|
28
|
+
* `version`, so GCP log filters/alerts on `jsonPayload.svcGitHash` must be updated.
|
|
29
|
+
*
|
|
19
30
|
* Both backends auto-enrich every line with the logged context keys, read
|
|
20
31
|
* DIRECTLY from the active RequestContext (@webpieces/core-context) on each line —
|
|
21
|
-
* no ContextReader is threaded in.
|
|
32
|
+
* no ContextReader is threaded in. Every line also carries `svcName` + `version` from ServiceInfo,
|
|
33
|
+
* though neither renders in the LOCAL pretty format (you know your own service, and can check git).
|
|
22
34
|
*
|
|
23
35
|
* @packageDocumentation
|
|
24
36
|
*/
|
|
@@ -26,8 +38,6 @@ var WinstonGcpFactory_1 = require("./WinstonGcpFactory");
|
|
|
26
38
|
Object.defineProperty(exports, "WinstonGcpFactory", { enumerable: true, get: function () { return WinstonGcpFactory_1.WinstonGcpFactory; } });
|
|
27
39
|
var WinstonConsoleFactory_1 = require("./WinstonConsoleFactory");
|
|
28
40
|
Object.defineProperty(exports, "WinstonConsoleFactory", { enumerable: true, get: function () { return WinstonConsoleFactory_1.WinstonConsoleFactory; } });
|
|
29
|
-
var WinstonFactoryOptions_1 = require("./WinstonFactoryOptions");
|
|
30
|
-
Object.defineProperty(exports, "WinstonFactoryOptions", { enumerable: true, get: function () { return WinstonFactoryOptions_1.WinstonFactoryOptions; } });
|
|
31
41
|
var WinstonLogger_1 = require("./WinstonLogger");
|
|
32
42
|
Object.defineProperty(exports, "WinstonLogger", { enumerable: true, get: function () { return WinstonLogger_1.WinstonLogger; } });
|
|
33
43
|
Object.defineProperty(exports, "LEVEL_TO_WINSTON", { enumerable: true, get: function () { return WinstonLogger_1.LEVEL_TO_WINSTON; } });
|
package/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/index.ts"],"names":[],"mappings":";;;AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/index.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,yDAAwD;AAA/C,sHAAA,iBAAiB,OAAA;AAC1B,iEAAgE;AAAvD,8HAAA,qBAAqB,OAAA;AAC9B,iDAAkE;AAAzD,8GAAA,aAAa,OAAA;AAAE,iHAAA,gBAAgB,OAAA;AACxC,mCAMkB;AALd,2GAAA,iBAAiB,OAAA;AACjB,0GAAA,gBAAgB,OAAA;AAChB,6GAAA,mBAAmB,OAAA;AACnB,wGAAA,cAAc,OAAA;AACd,2GAAA,iBAAiB,OAAA","sourcesContent":["/**\n * @webpieces/winston\n *\n * Node-only winston {@link LoggerFactory} backends for webpieces. Install one at\n * startup via `LogManager.setFactory(...)`:\n *\n * ```ts\n * import { ServiceInfo } from '@webpieces/core-util';\n * import { WinstonGcpFactory, WinstonConsoleFactory } from '@webpieces/winston';\n *\n * ServiceInfo.setInfo('my-service', '2.1.0'); // FIRST — the factories read it in their constructor\n * const loggerFactory = process.env.K_SERVICE\n * ? new WinstonGcpFactory() // Cloud Run → stdout JSON\n * : new WinstonConsoleFactory(); // local → pretty console\n * // hand to setupRuntime(new RuntimeSetupOptions(loggerFactory, ...))\n * ```\n *\n * BREAKING (was `new WinstonFactoryOptions(svcGitHash)` passed to each factory): the version moved\n * to `ServiceInfo.setInfo(name, version)` in @webpieces/core-util, because it is a fact about the\n * SERVICE, not about winston — bunyan needs the same version and previously could not stamp one at\n * all. It is also no longer presumed to be a git SHA: `version` is opaque, so a project deploying\n * semver or CI build numbers is no longer misdescribed. Migration: delete the `WinstonFactoryOptions`\n * import, call `ServiceInfo.setInfo(<name>, <the same hash>)` before building the factory, and drop\n * the ctor argument. A forgotten call throws at startup. Note the field renamed `svcGitHash` →\n * `version`, so GCP log filters/alerts on `jsonPayload.svcGitHash` must be updated.\n *\n * Both backends auto-enrich every line with the logged context keys, read\n * DIRECTLY from the active RequestContext (@webpieces/core-context) on each line —\n * no ContextReader is threaded in. Every line also carries `svcName` + `version` from ServiceInfo,\n * though neither renders in the LOCAL pretty format (you know your own service, and can check git).\n *\n * @packageDocumentation\n */\nexport { WinstonGcpFactory } from './WinstonGcpFactory';\nexport { WinstonConsoleFactory } from './WinstonConsoleFactory';\nexport { WinstonLogger, LEVEL_TO_WINSTON } from './WinstonLogger';\nexport {\n LEVEL_TO_SEVERITY,\n bigIntSafeFormat,\n injectContextFormat,\n severityFormat,\n localPrettyFormat,\n} from './format';\n"]}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* WinstonFactoryOptions - tuning for the winston LoggerFactory backends.
|
|
3
|
-
*
|
|
4
|
-
* Data-only structure → a class, per CLAUDE.md.
|
|
5
|
-
*
|
|
6
|
-
* There is deliberately NO level knob: webpieces does not filter by level — that
|
|
7
|
-
* is winston's job (it filters at its own default). `svcGitHash` is optional, so a
|
|
8
|
-
* bare `new WinstonGcpFactory()` still works.
|
|
9
|
-
*/
|
|
10
|
-
export declare class WinstonFactoryOptions {
|
|
11
|
-
/**
|
|
12
|
-
* The running service's git commit SHA. When set, every line carries
|
|
13
|
-
* `jsonPayload.svcGitHash=<sha>` (winston defaultMeta) so operators can
|
|
14
|
-
* filter Cloud Logging by deployment.
|
|
15
|
-
*/
|
|
16
|
-
readonly svcGitHash?: string | undefined;
|
|
17
|
-
constructor(
|
|
18
|
-
/**
|
|
19
|
-
* The running service's git commit SHA. When set, every line carries
|
|
20
|
-
* `jsonPayload.svcGitHash=<sha>` (winston defaultMeta) so operators can
|
|
21
|
-
* filter Cloud Logging by deployment.
|
|
22
|
-
*/
|
|
23
|
-
svcGitHash?: string | undefined);
|
|
24
|
-
}
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WinstonFactoryOptions = void 0;
|
|
4
|
-
/**
|
|
5
|
-
* WinstonFactoryOptions - tuning for the winston LoggerFactory backends.
|
|
6
|
-
*
|
|
7
|
-
* Data-only structure → a class, per CLAUDE.md.
|
|
8
|
-
*
|
|
9
|
-
* There is deliberately NO level knob: webpieces does not filter by level — that
|
|
10
|
-
* is winston's job (it filters at its own default). `svcGitHash` is optional, so a
|
|
11
|
-
* bare `new WinstonGcpFactory()` still works.
|
|
12
|
-
*/
|
|
13
|
-
class WinstonFactoryOptions {
|
|
14
|
-
svcGitHash;
|
|
15
|
-
constructor(
|
|
16
|
-
/**
|
|
17
|
-
* The running service's git commit SHA. When set, every line carries
|
|
18
|
-
* `jsonPayload.svcGitHash=<sha>` (winston defaultMeta) so operators can
|
|
19
|
-
* filter Cloud Logging by deployment.
|
|
20
|
-
*/
|
|
21
|
-
svcGitHash) {
|
|
22
|
-
this.svcGitHash = svcGitHash;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
exports.WinstonFactoryOptions = WinstonFactoryOptions;
|
|
26
|
-
//# sourceMappingURL=WinstonFactoryOptions.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"WinstonFactoryOptions.js","sourceRoot":"","sources":["../../../../../packages/logging/winston/src/WinstonFactoryOptions.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;GAQG;AACH,MAAa,qBAAqB;IAOV;IANpB;IACI;;;;OAIG;IACa,UAAmB;QAAnB,eAAU,GAAV,UAAU,CAAS;IACpC,CAAC;CACP;AATD,sDASC","sourcesContent":["/**\n * WinstonFactoryOptions - tuning for the winston LoggerFactory backends.\n *\n * Data-only structure → a class, per CLAUDE.md.\n *\n * There is deliberately NO level knob: webpieces does not filter by level — that\n * is winston's job (it filters at its own default). `svcGitHash` is optional, so a\n * bare `new WinstonGcpFactory()` still works.\n */\nexport class WinstonFactoryOptions {\n constructor(\n /**\n * The running service's git commit SHA. When set, every line carries\n * `jsonPayload.svcGitHash=<sha>` (winston defaultMeta) so operators can\n * filter Cloud Logging by deployment.\n */\n public readonly svcGitHash?: string,\n ) {}\n}\n"]}
|