@softistx/telemetry-logging 0.0.0-stage → 0.3.3
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/LICENSE +21 -0
- package/README.md +184 -2
- package/dist/bridge/format.d.ts +62 -0
- package/dist/bridge/format.d.ts.map +1 -0
- package/dist/bridge/info.d.ts +31 -0
- package/dist/bridge/info.d.ts.map +1 -0
- package/dist/bridge/levels.d.ts +30 -0
- package/dist/bridge/levels.d.ts.map +1 -0
- package/dist/bridge/origin.d.ts +18 -0
- package/dist/bridge/origin.d.ts.map +1 -0
- package/dist/bridge/transport.d.ts +87 -0
- package/dist/bridge/transport.d.ts.map +1 -0
- package/dist/export/winston.d.ts +44 -0
- package/dist/export/winston.d.ts.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +273 -0
- package/dist/index.js.map +15 -0
- package/package.json +70 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Steve Tsala
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,185 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/telemetry-logging
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The [winston](https://www.npmjs.com/package/winston) bridge for
|
|
4
|
+
[`@softistx/telemetry`](https://www.npmjs.com/package/@softistx/telemetry), in both
|
|
5
|
+
directions — and never both at once on the same logger.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
bun add @softistx/telemetry @softistx/telemetry-logging winston
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Most applications already log. This is for those: it connects the logger you
|
|
12
|
+
have to the traces you are adding, without a rewrite and without running two
|
|
13
|
+
pipes.
|
|
14
|
+
|
|
15
|
+
## Trace ids on the lines you already write
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import winston from 'winston';
|
|
19
|
+
import { telemetryFormat } from '@softistx/telemetry-logging';
|
|
20
|
+
|
|
21
|
+
const logger = winston.createLogger({
|
|
22
|
+
format: winston.format.combine(telemetryFormat(), winston.format.json()),
|
|
23
|
+
transports: [new winston.transports.Console()],
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Every line now carries `traceId` and `spanId`, plus the attributes in scope —
|
|
28
|
+
what `span()` and `withAttributes()` were given. That is the whole cost of
|
|
29
|
+
making a log search and a trace view answer each other.
|
|
30
|
+
|
|
31
|
+
Put it **before** the format that renders the line (`json()`, `printf()`,
|
|
32
|
+
`simple()`), or the fields will be added to something already turned into a
|
|
33
|
+
string. Outside any span it adds nothing at all, rather than a null: a field
|
|
34
|
+
that is present and empty is one a dashboard has to filter out. An ambient
|
|
35
|
+
attribute never replaces a field the call site set — `orderId` on the line means
|
|
36
|
+
that order.
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
telemetryFormat({ traceField: 'trace_id', spanField: 'span_id', attributes: false })
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## winston lines into the pipeline
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { telemetryTransport } from '@softistx/telemetry-logging';
|
|
46
|
+
|
|
47
|
+
logger.add(telemetryTransport({ source: 'CheckoutService' }));
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Now the lines go wherever the telemetry's exporters go — OTLP, Mongo, a file —
|
|
51
|
+
with no call site changed. `level` and `message` become the record; everything
|
|
52
|
+
else the caller passed becomes attributes, and the span open at the time is
|
|
53
|
+
attached.
|
|
54
|
+
|
|
55
|
+
| | default | |
|
|
56
|
+
| --- | --- | --- |
|
|
57
|
+
| `source` | `winston` | what the lines are attributed to |
|
|
58
|
+
| `telemetry` | in scope, else installed | |
|
|
59
|
+
| `fallback` | `info` | what a level this library does not know becomes |
|
|
60
|
+
| `level` | the logger's | winston's own option, honoured here |
|
|
61
|
+
| `silent` | `false` | winston's own option |
|
|
62
|
+
| `handleExceptions` | `false` | whether a line from winston's `exceptionHandlers` is collected |
|
|
63
|
+
|
|
64
|
+
A line also has to clear the **telemetry's** `minimum`, not only winston's
|
|
65
|
+
level: two floors, because winston's decides what the logger writes at all and
|
|
66
|
+
the telemetry's decides what the pipeline keeps. An `Error` — as the message, as
|
|
67
|
+
`error` in the meta, or as the `stack` that `format.errors()` leaves behind —
|
|
68
|
+
becomes the record's `ErrorInfo`, so it reaches OTLP as `exception.type` and
|
|
69
|
+
`exception.stacktrace` rather than as text on an attribute. The attributes in
|
|
70
|
+
scope come along too, under whatever the line already carried.
|
|
71
|
+
|
|
72
|
+
A level winston knows and this does not — `crit` from a `syslog` level set, a
|
|
73
|
+
custom one — becomes `info`, and the direction matters: mapped to `debug` it
|
|
74
|
+
would be dropped by a pipeline with the default `minimum`, and a line that
|
|
75
|
+
disappears is worse than one recorded a shade too loudly. For the same reason a
|
|
76
|
+
line at a level the logger's own table does not know is **kept**, where
|
|
77
|
+
`winston-transport` drops it.
|
|
78
|
+
|
|
79
|
+
## Telemetry signals into a winston already in place
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { winstonExporter } from '@softistx/telemetry-logging';
|
|
83
|
+
|
|
84
|
+
createTelemetry('checkout', {
|
|
85
|
+
exporters: [winstonExporter({ logger })],
|
|
86
|
+
}).install();
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
For an application whose log shipping is solved — a rotation, a syslog
|
|
90
|
+
transport, a vendor's agent — and that wants `log.info(...)` from this library to
|
|
91
|
+
land in the same place as everything else.
|
|
92
|
+
|
|
93
|
+
Spans are **off** by default. A span is a duration and a set of attributes,
|
|
94
|
+
which is a poor fit for a line of text, and turning every one of them into a log
|
|
95
|
+
line is how a cheap trace becomes an expensive log bill. `spans: true` when the
|
|
96
|
+
lines are what you have; a **failed span is written at `error`** whatever
|
|
97
|
+
`spanSeverity` says, because that is the line somebody is looking for.
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
winstonExporter({ logger, spans: true, spanSeverity: 'debug' })
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Not both on the same logger
|
|
104
|
+
|
|
105
|
+
```
|
|
106
|
+
logger ──(transport)──▶ pipeline ──(exporter)──▶ logger ──▶ …
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
That is a loop, and a loop here does not crash: it spins, quietly, at whatever
|
|
110
|
+
rate the process can manage. `winstonExporter` **refuses it at construction**
|
|
111
|
+
when it can see the transport on the logger it was handed. What construction
|
|
112
|
+
cannot see — two loggers pointing at each other, or a transport added afterwards
|
|
113
|
+
— is caught on the line itself: every line this library writes into winston
|
|
114
|
+
carries a mark, and the transport drops a line that has it.
|
|
115
|
+
|
|
116
|
+
Pick a direction. The transport is for *collecting* winston into the pipeline;
|
|
117
|
+
the exporter is for *writing* the pipeline into winston. Both is neither.
|
|
118
|
+
|
|
119
|
+
## `@nxgt/shared-logging`
|
|
120
|
+
|
|
121
|
+
It needs nothing extra here. Its `Logger` **is** winston's own, so
|
|
122
|
+
`telemetryFormat()`, `telemetryTransport()` and `winstonExporter({ logger })`
|
|
123
|
+
all apply to it unchanged.
|
|
124
|
+
|
|
125
|
+
## API
|
|
126
|
+
|
|
127
|
+
| | |
|
|
128
|
+
| --- | --- |
|
|
129
|
+
| `telemetryFormat(options)`, `FormatOptions`, `TelemetryFormat` | the format |
|
|
130
|
+
| `telemetryTransport(options)`, `TelemetryTransport`, `TransportOptions` | the transport |
|
|
131
|
+
| `winstonExporter(options)`, `WinstonExporterOptions`, `WinstonLike` | the exporter |
|
|
132
|
+
| `severityOf(level, fallback)`, `levelOf(severity)` | the two directions of the mapping |
|
|
133
|
+
| `SEVERITY_OF_LEVEL`, `LEVEL_OF_SEVERITY` | the tables behind them |
|
|
134
|
+
| `FROM_TELEMETRY` | the mark that breaks the loop |
|
|
135
|
+
| `LogInfo` | what winston passes a format and a transport |
|
|
136
|
+
|
|
137
|
+
## Traps
|
|
138
|
+
|
|
139
|
+
- **The format goes first.** After `json()` or `printf()` the line is already a
|
|
140
|
+
string, and the fields are added to something nothing will read.
|
|
141
|
+
- **`winston` is an optional peer, and nothing here imports it.** The format is
|
|
142
|
+
a plain object with `transform`, and the transport extends `node:stream`'s
|
|
143
|
+
`Writable` — which is exactly what `winston-transport` does. This package has
|
|
144
|
+
**no runtime dependency**, so it installs in a workspace that has no winston
|
|
145
|
+
at all.
|
|
146
|
+
- **A transport's `level` is enforced by the transport, not by the logger.**
|
|
147
|
+
winston pipes every line to every transport and each one filters. This does
|
|
148
|
+
the filtering the way `winston-transport` does, on `Symbol.for('level')` and
|
|
149
|
+
the logger's own level table, which it learns from Node's `pipe` event — with
|
|
150
|
+
one deliberate difference, the unknown level above. A spec runs both
|
|
151
|
+
transports on the same logger and asserts they keep the same lines.
|
|
152
|
+
- **Uncaught exceptions are not collected unless you ask.** A line from
|
|
153
|
+
winston's `exceptionHandlers` carries `exception: true`, and a transport
|
|
154
|
+
without `handleExceptions` ignores it — winston's rule, followed here.
|
|
155
|
+
Turning it on also puts this transport in winston's list of exception
|
|
156
|
+
handlers, and winston then waits up to three seconds for each of them to emit
|
|
157
|
+
`finish` before the process exits. A `process.on('uncaughtException')` that
|
|
158
|
+
calls `log.error` and awaits `telemetry.close()` costs no exit delay.
|
|
159
|
+
- **A per-transport `format` is not supported.** winston lets a transport carry
|
|
160
|
+
its own; this one does not, because the record is built from the line's
|
|
161
|
+
fields and a format that rendered them to a string would leave nothing to
|
|
162
|
+
build from. Put the format on the logger, after `telemetryFormat()`.
|
|
163
|
+
- **A line's own fields become attributes, including big ones.** Whatever is
|
|
164
|
+
passed to `logger.info('…', meta)` is coerced through this library's scalar
|
|
165
|
+
rule; an object becomes its rendering. If a line carries something large or
|
|
166
|
+
secret, it carried it before this package too — but it now leaves the process
|
|
167
|
+
by a second route.
|
|
168
|
+
- **Nothing here is sampled.** Logs never are, in this library; a winston line
|
|
169
|
+
that lands in the pipeline is exported whether or not its trace was sampled.
|
|
170
|
+
It still carries the `traceId`.
|
|
171
|
+
- **The exporter writes through winston's single-argument `log`.** The
|
|
172
|
+
three-argument `log(level, message, meta)` tests the message against
|
|
173
|
+
`/%[scdjifoO%]/` and, when it matches, treats the meta as printf arguments —
|
|
174
|
+
which means a span named `GET /files/%s` would arrive with no `traceId`, no
|
|
175
|
+
attributes, and none of the mark that stops this bridge looping.
|
|
176
|
+
- **A transport that throws would take the line down for every other transport
|
|
177
|
+
on the logger.** This one cannot throw: the whole write is guarded, and a
|
|
178
|
+
broken pipeline costs the telemetry, not the log.
|
|
179
|
+
- **The exporter writes synchronously through `logger.log`.** Whether the line
|
|
180
|
+
has reached a file or a socket when `export` returns is winston's business,
|
|
181
|
+
not this library's — `telemetry.close()` drains the pipeline, not winston.
|
|
182
|
+
|
|
183
|
+
## License
|
|
184
|
+
|
|
185
|
+
MIT
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What winston hands a format, and what a format hands back.
|
|
3
|
+
*
|
|
4
|
+
* Declared here rather than imported from `logform`, because the whole point of
|
|
5
|
+
* this package is that it works with winston installed and does not require it
|
|
6
|
+
* at build time. It is the shape winston actually passes: a mutable object with
|
|
7
|
+
* `level` and `message`, and whatever else the caller put in it.
|
|
8
|
+
*/
|
|
9
|
+
export interface LogInfo {
|
|
10
|
+
level: string;
|
|
11
|
+
message: any;
|
|
12
|
+
/**
|
|
13
|
+
* Symbols too, because winston keeps two of its own there — `Symbol.for('level')`
|
|
14
|
+
* for the level before any format coloured it, and `Symbol.for('message')` for
|
|
15
|
+
* the rendered line. A string-only index signature is not assignable to
|
|
16
|
+
* logform's `TransformableInfo`, which is what `combine` takes.
|
|
17
|
+
*/
|
|
18
|
+
[field: string | symbol]: any;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A winston format, as winston consumes one: an object with `transform`.
|
|
22
|
+
*
|
|
23
|
+
* `combine(...)` calls `format.transform(info, format.options)` and nothing
|
|
24
|
+
* else, so this is the whole contract. Not importing `winston.format` is what
|
|
25
|
+
* keeps this package installable in a service that has winston in one workspace
|
|
26
|
+
* and not in another.
|
|
27
|
+
*/
|
|
28
|
+
export interface TelemetryFormat {
|
|
29
|
+
readonly options: Record<string, unknown>;
|
|
30
|
+
transform(info: LogInfo): LogInfo;
|
|
31
|
+
}
|
|
32
|
+
export interface FormatOptions {
|
|
33
|
+
/** Default `traceId`. */
|
|
34
|
+
readonly traceField?: string;
|
|
35
|
+
/** Default `spanId`. */
|
|
36
|
+
readonly spanField?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Whether the attributes in scope — what `span()` and `withAttributes()`
|
|
39
|
+
* were given — are copied onto the line too. Default `true`.
|
|
40
|
+
*/
|
|
41
|
+
readonly attributes?: boolean;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Puts the current `traceId` and `spanId` on every line winston writes.
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* winston.createLogger({
|
|
48
|
+
* format: winston.format.combine(telemetryFormat(), winston.format.json()),
|
|
49
|
+
* });
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* This is the half of the bridge that costs nothing to adopt: an application
|
|
53
|
+
* keeps the logger it has, the lines keep the shape they have, and every one of
|
|
54
|
+
* them gains the id that ties it to a trace. Put it **before** the format that
|
|
55
|
+
* renders the line — `json()`, `printf()`, `simple()` — or the fields will be
|
|
56
|
+
* added to something already turned into a string.
|
|
57
|
+
*
|
|
58
|
+
* Outside any span it adds nothing, rather than a null or an empty string: a
|
|
59
|
+
* field that is present and empty is one a dashboard has to filter out.
|
|
60
|
+
*/
|
|
61
|
+
export declare function telemetryFormat(options?: FormatOptions): TelemetryFormat;
|
|
62
|
+
//# sourceMappingURL=format.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../src/bridge/format.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,MAAM,WAAW,OAAO;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,GAAG,CAAC;IACb;;;;;OAKG;IACH,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,GAAG,CAAC;CAC9B;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC1C,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC;CAClC;AAED,MAAM,WAAW,aAAa;IAC7B,yBAAyB;IACzB,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,wBAAwB;IACxB,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,aAAkB,GAAG,eAAe,CAwB5E"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type Attributes, type ErrorInfo } from '@softistx/telemetry';
|
|
2
|
+
import type { LogInfo } from './format';
|
|
3
|
+
/**
|
|
4
|
+
* Where winston keeps the line's level *before* any format coloured it.
|
|
5
|
+
*
|
|
6
|
+
* `Symbol.for`, not a fresh symbol: it is the same registry entry `logform`
|
|
7
|
+
* uses, and reading it is how every winston transport decides what to keep.
|
|
8
|
+
*/
|
|
9
|
+
export declare const LEVEL: unique symbol;
|
|
10
|
+
/**
|
|
11
|
+
* The line's text.
|
|
12
|
+
*
|
|
13
|
+
* winston's `message` is whatever was passed — a string, an object, an `Error`.
|
|
14
|
+
* `attributesOf` would render an object to a string eventually, but the name of
|
|
15
|
+
* a log record is the thing a human reads first, so it is worth one explicit
|
|
16
|
+
* pass.
|
|
17
|
+
*/
|
|
18
|
+
export declare function message(info: LogInfo): string;
|
|
19
|
+
/**
|
|
20
|
+
* The failure a line is about, if it is about one.
|
|
21
|
+
*
|
|
22
|
+
* winston takes an `Error` three ways — as the message, as `error` in the meta,
|
|
23
|
+
* and as a `stack` string that `format.errors()` left behind — and an exporter
|
|
24
|
+
* needs it as an `ErrorInfo` or it is only text. Without this, an OTLP consumer
|
|
25
|
+
* gets no `exception.type` for a line that was written with an exception in
|
|
26
|
+
* hand, which is the one field an exception dashboard queries on.
|
|
27
|
+
*/
|
|
28
|
+
export declare function failureOf(info: LogInfo, stackTraces: boolean): ErrorInfo | undefined;
|
|
29
|
+
/** Everything the caller added, through the coercion that never refuses. */
|
|
30
|
+
export declare function rest(info: LogInfo): Attributes;
|
|
31
|
+
//# sourceMappingURL=info.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"info.d.ts","sourceRoot":"","sources":["../../src/bridge/info.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,UAAU,EAEf,KAAK,SAAS,EAEd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAkBxC;;;;;GAKG;AACH,eAAO,MAAM,KAAK,eAAsB,CAAC;AAEzC;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAY7C;AAED;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CACxB,IAAI,EAAE,OAAO,EACb,WAAW,EAAE,OAAO,GAClB,SAAS,GAAG,SAAS,CAmBvB;AAQD,4EAA4E;AAC5E,wBAAgB,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,UAAU,CAQ9C"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Severity } from '@softistx/telemetry';
|
|
2
|
+
/**
|
|
3
|
+
* winston's npm levels, and the four this library has.
|
|
4
|
+
*
|
|
5
|
+
* The mapping is lossy in one direction on purpose. `Severity` has four levels
|
|
6
|
+
* because a log level is a *routing* decision and four is as many as anybody
|
|
7
|
+
* routes on; winston's `http`, `verbose` and `silly` are shades of the two it
|
|
8
|
+
* already has, so they land on `info` and `debug` rather than inventing
|
|
9
|
+
* severities nothing downstream would understand.
|
|
10
|
+
*
|
|
11
|
+
* A level winston was configured with but that is not listed here — a custom
|
|
12
|
+
* level set, `syslog`'s `notice`, `crit`, `emerg` — is **not** guessed at. See
|
|
13
|
+
* {@link severityOf}.
|
|
14
|
+
*/
|
|
15
|
+
export declare const SEVERITY_OF_LEVEL: Readonly<Record<string, Severity>>;
|
|
16
|
+
/** The npm level a signal is written at, going the other way. */
|
|
17
|
+
export declare const LEVEL_OF_SEVERITY: Readonly<Record<Severity, string>>;
|
|
18
|
+
/**
|
|
19
|
+
* What a winston level means here, or the fallback.
|
|
20
|
+
*
|
|
21
|
+
* The fallback is **`info`**, and it matters which way it errs: a custom level
|
|
22
|
+
* mapped down to `debug` would be dropped by a pipeline with the default
|
|
23
|
+
* `minimum`, and a line that disappears is worse than one recorded a shade too
|
|
24
|
+
* loudly. A `syslog` logger's `crit` arriving as `info` is visible and wrong;
|
|
25
|
+
* as `debug` it is invisible and wrong.
|
|
26
|
+
*/
|
|
27
|
+
export declare function severityOf(level: string, fallback?: Severity): Severity;
|
|
28
|
+
/** The winston level for a severity. Total: every severity has one. */
|
|
29
|
+
export declare function levelOf(severity: Severity): string;
|
|
30
|
+
//# sourceMappingURL=levels.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"levels.d.ts","sourceRoot":"","sources":["../../src/bridge/levels.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,iBAAiB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAQhE,CAAC;AAEF,iEAAiE;AACjE,eAAO,MAAM,iBAAiB,EAAE,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,CAKhE,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CACzB,KAAK,EAAE,MAAM,EACb,QAAQ,GAAE,QAAiB,GACzB,QAAQ,CAMV;AAED,uEAAuE;AACvE,wBAAgB,OAAO,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAElD"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The mark a line carries when this library is what wrote it into winston.
|
|
3
|
+
*
|
|
4
|
+
* It exists because the two halves of this bridge point at each other. A logger
|
|
5
|
+
* with a {@link telemetryTransport} sends its lines to the pipeline; a
|
|
6
|
+
* {@link winstonExporter} sends the pipeline's signals to a logger. Both on the
|
|
7
|
+
* same logger is a loop, and a loop here does not crash — it spins, quietly,
|
|
8
|
+
* at whatever rate the process can manage.
|
|
9
|
+
*
|
|
10
|
+
* `winstonExporter` refuses that wiring when it can see it, at construction.
|
|
11
|
+
* This mark is what catches the shapes it cannot see: two loggers pointing at
|
|
12
|
+
* each other, or a transport added after the exporter was built. It is a
|
|
13
|
+
* string key rather than a symbol because it has to survive `JSON.stringify` —
|
|
14
|
+
* winston's `json()` format, a transport that serialises, `logform`'s
|
|
15
|
+
* splat — anywhere the line may be copied before it comes back round.
|
|
16
|
+
*/
|
|
17
|
+
export declare const FROM_TELEMETRY = "nxgt.telemetry.origin";
|
|
18
|
+
//# sourceMappingURL=origin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"origin.d.ts","sourceRoot":"","sources":["../../src/bridge/origin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,cAAc,0BAA0B,CAAC"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { Writable } from 'node:stream';
|
|
2
|
+
import { type Severity, type Telemetry } from '@softistx/telemetry';
|
|
3
|
+
import type { LogInfo } from './format';
|
|
4
|
+
export interface TransportOptions {
|
|
5
|
+
/** The source every line is attributed to. Default `winston`. */
|
|
6
|
+
readonly source?: string;
|
|
7
|
+
/**
|
|
8
|
+
* The telemetry to write to. Default: the one in scope when the line is
|
|
9
|
+
* written, and the installed one otherwise.
|
|
10
|
+
*/
|
|
11
|
+
readonly telemetry?: Telemetry;
|
|
12
|
+
/** What a level this library does not know becomes. Default `info`. */
|
|
13
|
+
readonly fallback?: Severity;
|
|
14
|
+
/** winston's own option: the lowest level this transport receives. */
|
|
15
|
+
readonly level?: string;
|
|
16
|
+
/** winston's own option: a transport that is silent receives nothing. */
|
|
17
|
+
readonly silent?: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Whether a line winston's `exceptionHandlers` produced is collected too.
|
|
20
|
+
* Default `false`, which is winston's own default for a transport.
|
|
21
|
+
*
|
|
22
|
+
* It is off for a reason worth knowing. Turning it on puts this transport in
|
|
23
|
+
* winston's list of exception handlers, and winston then waits for each of
|
|
24
|
+
* them to emit `finish` before letting the process exit — up to three
|
|
25
|
+
* seconds. A `process.on('uncaughtException')` that calls `log.error` and
|
|
26
|
+
* awaits `telemetry.close()` is the direct route, and costs no exit delay.
|
|
27
|
+
*/
|
|
28
|
+
readonly handleExceptions?: boolean;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A winston transport that writes every line into the telemetry pipeline.
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* logger.add(telemetryTransport());
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* The other half of the bridge, for an application that already logs through
|
|
38
|
+
* winston and wants those lines exported the way its spans are — to OTLP, to
|
|
39
|
+
* Mongo, to a file — without rewriting a single call site.
|
|
40
|
+
*
|
|
41
|
+
* It extends `node:stream`'s `Writable` rather than `winston-transport`, which
|
|
42
|
+
* is the same thing winston-transport does and means **this package has no
|
|
43
|
+
* runtime dependency**: it is installable in a workspace that does not have
|
|
44
|
+
* winston at all. What winston requires of a transport is a writable stream in
|
|
45
|
+
* object mode with a `log(info, next)` of arity two, and that is what this is.
|
|
46
|
+
*/
|
|
47
|
+
export declare class TelemetryTransport extends Writable {
|
|
48
|
+
readonly source: string;
|
|
49
|
+
readonly level?: string;
|
|
50
|
+
/** Set by winston when this is piped to a logger, and used to honour `level`. */
|
|
51
|
+
levels: Readonly<Record<string, number>> | undefined;
|
|
52
|
+
/** The logger this is attached to, which is where a default level comes from. */
|
|
53
|
+
parent: {
|
|
54
|
+
readonly level?: string;
|
|
55
|
+
} | undefined;
|
|
56
|
+
silent: boolean;
|
|
57
|
+
readonly handleExceptions: boolean;
|
|
58
|
+
private readonly telemetry;
|
|
59
|
+
private readonly fallback;
|
|
60
|
+
constructor(options?: TransportOptions);
|
|
61
|
+
/**
|
|
62
|
+
* Arity two, which is what winston checks to decide this is a modern
|
|
63
|
+
* transport rather than a legacy one it has to wrap.
|
|
64
|
+
*/
|
|
65
|
+
log(info: LogInfo, next: () => void): void;
|
|
66
|
+
_write(info: LogInfo, _encoding: BufferEncoding, next: (error?: Error | null) => void): void;
|
|
67
|
+
/**
|
|
68
|
+
* The level filter, the way winston-transport applies it.
|
|
69
|
+
*
|
|
70
|
+
* The level to compare against is the transport's own, falling back to the
|
|
71
|
+
* logger's, and the comparison is on winston's *numbers* — where a lower
|
|
72
|
+
* number is more severe. `info[Symbol.for('level')]` is the line's level
|
|
73
|
+
* before any format coloured it, which is why it is read rather than
|
|
74
|
+
* `info.level`.
|
|
75
|
+
*/
|
|
76
|
+
private wanted;
|
|
77
|
+
private post;
|
|
78
|
+
private record;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* A winston transport, as an instance.
|
|
82
|
+
*
|
|
83
|
+
* `telemetryTransport()` reads better at a call site than `new
|
|
84
|
+
* TelemetryTransport()`, and matches how every other integration here is built.
|
|
85
|
+
*/
|
|
86
|
+
export declare function telemetryTransport(options?: TransportOptions): TelemetryTransport;
|
|
87
|
+
//# sourceMappingURL=transport.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/bridge/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAON,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAWxC,MAAM,WAAW,gBAAgB;IAChC,iEAAiE;IACjE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC;IAC/B,uEAAuE;IACvE,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAC7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import type { Exporter, Severity } from '@softistx/telemetry';
|
|
2
|
+
/**
|
|
3
|
+
* What this exporter needs of a logger.
|
|
4
|
+
*
|
|
5
|
+
* Structural, so that `winston.Logger`, a child logger, and
|
|
6
|
+
* `@nxgt/shared-logging`'s `Logger` — which *is* winston's — all fit without
|
|
7
|
+
* this package importing any of them.
|
|
8
|
+
*/
|
|
9
|
+
export interface WinstonLike {
|
|
10
|
+
log(info: Record<string, unknown>): unknown;
|
|
11
|
+
readonly transports?: readonly unknown[];
|
|
12
|
+
}
|
|
13
|
+
export interface WinstonExporterOptions {
|
|
14
|
+
/** The logger the signals are written to. */
|
|
15
|
+
readonly logger: WinstonLike;
|
|
16
|
+
/** Whether spans are written as lines too. Default `false`. */
|
|
17
|
+
readonly spans?: boolean;
|
|
18
|
+
/** The level a span is written at. Default `info`. */
|
|
19
|
+
readonly spanSeverity?: Severity;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Telemetry signals into a winston logger that is already there.
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* createTelemetry('checkout', {
|
|
26
|
+
* exporters: [winstonExporter({ logger })],
|
|
27
|
+
* }).install();
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* For an application whose log shipping is solved — a file rotation, a syslog
|
|
31
|
+
* transport, a vendor's — and that wants `log.info(...)` from this library to
|
|
32
|
+
* land in the same place as everything else, rather than a second pipe to
|
|
33
|
+
* operate.
|
|
34
|
+
*
|
|
35
|
+
* Spans are **off** by default. A span is a duration and a set of attributes,
|
|
36
|
+
* which is a poor fit for a line of text, and turning every one of them into a
|
|
37
|
+
* log line is how a cheap trace becomes an expensive log bill. `spans: true`
|
|
38
|
+
* when the lines are what you have.
|
|
39
|
+
*
|
|
40
|
+
* A **failed span is always written at `error`**, whatever `spanSeverity` says.
|
|
41
|
+
* That is the line somebody is looking for.
|
|
42
|
+
*/
|
|
43
|
+
export declare function winstonExporter(options: WinstonExporterOptions): Exporter;
|
|
44
|
+
//# sourceMappingURL=winston.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"winston.d.ts","sourceRoot":"","sources":["../../src/export/winston.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,QAAQ,EAGR,QAAQ,EAGR,MAAM,qBAAqB,CAAC;AAK7B;;;;;;GAMG;AACH,MAAM,WAAW,WAAW;IAC3B,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC;IAC5C,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,OAAO,EAAE,CAAC;CACzC;AAED,MAAM,WAAW,sBAAsB;IACtC,6CAA6C;IAC7C,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,+DAA+D;IAC/D,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,sDAAsD;IACtD,QAAQ,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC;CACjC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,QAAQ,CAyBzE"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// src/bridge/format.ts
|
|
2
|
+
import { currentAttributes, currentSpan } from "@softistx/telemetry";
|
|
3
|
+
function telemetryFormat(options = {}) {
|
|
4
|
+
const traceField = options.traceField ?? "traceId";
|
|
5
|
+
const spanField = options.spanField ?? "spanId";
|
|
6
|
+
const withAttributes = options.attributes ?? true;
|
|
7
|
+
return {
|
|
8
|
+
options: {},
|
|
9
|
+
transform(info) {
|
|
10
|
+
try {
|
|
11
|
+
if (withAttributes)
|
|
12
|
+
stamp(info, currentAttributes());
|
|
13
|
+
const span = currentSpan();
|
|
14
|
+
if (span === undefined)
|
|
15
|
+
return info;
|
|
16
|
+
info[traceField] = span.traceId;
|
|
17
|
+
info[spanField] = span.spanId;
|
|
18
|
+
} catch {}
|
|
19
|
+
return info;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function stamp(info, attributes) {
|
|
24
|
+
for (const [name, value] of Object.entries(attributes)) {
|
|
25
|
+
if (!(name in info))
|
|
26
|
+
info[name] = value;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
// src/bridge/levels.ts
|
|
30
|
+
var SEVERITY_OF_LEVEL = {
|
|
31
|
+
error: "error",
|
|
32
|
+
warn: "warn",
|
|
33
|
+
info: "info",
|
|
34
|
+
http: "info",
|
|
35
|
+
verbose: "debug",
|
|
36
|
+
debug: "debug",
|
|
37
|
+
silly: "debug"
|
|
38
|
+
};
|
|
39
|
+
var LEVEL_OF_SEVERITY = {
|
|
40
|
+
debug: "debug",
|
|
41
|
+
info: "info",
|
|
42
|
+
warn: "warn",
|
|
43
|
+
error: "error"
|
|
44
|
+
};
|
|
45
|
+
function severityOf(level, fallback = "info") {
|
|
46
|
+
if (typeof level !== "string")
|
|
47
|
+
return fallback;
|
|
48
|
+
return SEVERITY_OF_LEVEL[uncoloured(level).trim().toLowerCase()] ?? fallback;
|
|
49
|
+
}
|
|
50
|
+
function levelOf(severity) {
|
|
51
|
+
return LEVEL_OF_SEVERITY[severity] ?? "info";
|
|
52
|
+
}
|
|
53
|
+
var ESCAPE = "\x1B";
|
|
54
|
+
var ANSI = /\x1b\[[0-9;]*m/g;
|
|
55
|
+
function uncoloured(level) {
|
|
56
|
+
return level.includes(ESCAPE) ? level.replace(ANSI, "") : level;
|
|
57
|
+
}
|
|
58
|
+
// src/bridge/origin.ts
|
|
59
|
+
var FROM_TELEMETRY = "nxgt.telemetry.origin";
|
|
60
|
+
// src/bridge/transport.ts
|
|
61
|
+
import { Writable } from "node:stream";
|
|
62
|
+
import {
|
|
63
|
+
currentAttributes as currentAttributes2,
|
|
64
|
+
currentSpan as currentSpan2,
|
|
65
|
+
meetsSeverity,
|
|
66
|
+
mergeAttributes,
|
|
67
|
+
resolveTelemetry
|
|
68
|
+
} from "@softistx/telemetry";
|
|
69
|
+
|
|
70
|
+
// src/bridge/info.ts
|
|
71
|
+
import {
|
|
72
|
+
attributesOf,
|
|
73
|
+
errorInfo
|
|
74
|
+
} from "@softistx/telemetry";
|
|
75
|
+
var OWN = new Set([
|
|
76
|
+
"level",
|
|
77
|
+
"message",
|
|
78
|
+
"stack",
|
|
79
|
+
"exception"
|
|
80
|
+
]);
|
|
81
|
+
var LEVEL = Symbol.for("level");
|
|
82
|
+
function message(info) {
|
|
83
|
+
const text = info.message;
|
|
84
|
+
if (typeof text === "string")
|
|
85
|
+
return text;
|
|
86
|
+
if (text instanceof Error)
|
|
87
|
+
return text.message;
|
|
88
|
+
if (text === undefined || text === null)
|
|
89
|
+
return "";
|
|
90
|
+
try {
|
|
91
|
+
return typeof text === "object" ? JSON.stringify(text) : String(text);
|
|
92
|
+
} catch {
|
|
93
|
+
return String(text);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function failureOf(info, stackTraces) {
|
|
97
|
+
if (info.message instanceof Error)
|
|
98
|
+
return errorInfo(info.message, stackTraces);
|
|
99
|
+
if (info["error"] instanceof Error)
|
|
100
|
+
return errorInfo(info["error"], stackTraces);
|
|
101
|
+
if (typeof info["stack"] !== "string" || info["stack"] === "")
|
|
102
|
+
return;
|
|
103
|
+
const rebuilt = {
|
|
104
|
+
type: typeOf(info["stack"]),
|
|
105
|
+
message: message(info)
|
|
106
|
+
};
|
|
107
|
+
return stackTraces ? { ...rebuilt, stackTrace: info["stack"] } : rebuilt;
|
|
108
|
+
}
|
|
109
|
+
function typeOf(stack) {
|
|
110
|
+
const named = /^([A-Za-z_$][\w$]*(?:Error|Exception))\b/.exec(stack);
|
|
111
|
+
return named?.[1] ?? "Error";
|
|
112
|
+
}
|
|
113
|
+
function rest(info) {
|
|
114
|
+
const carried = {};
|
|
115
|
+
for (const [name, value] of Object.entries(info)) {
|
|
116
|
+
if (!OWN.has(name))
|
|
117
|
+
carried[name] = value;
|
|
118
|
+
}
|
|
119
|
+
return attributesOf(carried);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// src/bridge/transport.ts
|
|
123
|
+
class TelemetryTransport extends Writable {
|
|
124
|
+
source;
|
|
125
|
+
level;
|
|
126
|
+
levels;
|
|
127
|
+
parent;
|
|
128
|
+
silent;
|
|
129
|
+
handleExceptions;
|
|
130
|
+
telemetry;
|
|
131
|
+
fallback;
|
|
132
|
+
constructor(options = {}) {
|
|
133
|
+
super({ objectMode: true });
|
|
134
|
+
this.source = options.source ?? "winston";
|
|
135
|
+
if (options.level !== undefined)
|
|
136
|
+
this.level = options.level;
|
|
137
|
+
this.silent = options.silent ?? false;
|
|
138
|
+
this.handleExceptions = options.handleExceptions ?? false;
|
|
139
|
+
this.telemetry = options.telemetry;
|
|
140
|
+
this.fallback = options.fallback ?? "info";
|
|
141
|
+
this.once("pipe", (logger) => {
|
|
142
|
+
this.levels ??= logger.levels;
|
|
143
|
+
this.parent ??= logger;
|
|
144
|
+
});
|
|
145
|
+
this.on("unpipe", () => {
|
|
146
|
+
this.parent = undefined;
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
log(info, next) {
|
|
150
|
+
try {
|
|
151
|
+
this.post(info);
|
|
152
|
+
} catch {}
|
|
153
|
+
next();
|
|
154
|
+
}
|
|
155
|
+
_write(info, _encoding, next) {
|
|
156
|
+
if (this.silent || !this.wanted(info)) {
|
|
157
|
+
next();
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (info["exception"] === true && !this.handleExceptions) {
|
|
161
|
+
next();
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
this.log(info, () => next());
|
|
165
|
+
}
|
|
166
|
+
wanted(info) {
|
|
167
|
+
const level = this.level || this.parent?.level;
|
|
168
|
+
if (!level || this.levels === undefined)
|
|
169
|
+
return true;
|
|
170
|
+
const wrote = this.levels[String(info[LEVEL] ?? info.level)];
|
|
171
|
+
const floor = this.levels[level];
|
|
172
|
+
if (wrote === undefined || floor === undefined)
|
|
173
|
+
return true;
|
|
174
|
+
return floor >= wrote;
|
|
175
|
+
}
|
|
176
|
+
post(info) {
|
|
177
|
+
if (info[FROM_TELEMETRY] === true)
|
|
178
|
+
return;
|
|
179
|
+
const telemetry = this.telemetry ?? resolveTelemetry();
|
|
180
|
+
if (telemetry === undefined)
|
|
181
|
+
return;
|
|
182
|
+
const severity = severityOf(info.level, this.fallback);
|
|
183
|
+
if (!meetsSeverity(severity, telemetry.minimum))
|
|
184
|
+
return;
|
|
185
|
+
telemetry.emit(this.record(info, severity, telemetry.stackTraces));
|
|
186
|
+
}
|
|
187
|
+
record(info, severity, stackTraces) {
|
|
188
|
+
const span = currentSpan2();
|
|
189
|
+
const failure = failureOf(info, stackTraces);
|
|
190
|
+
return {
|
|
191
|
+
type: "log",
|
|
192
|
+
at: Date.now(),
|
|
193
|
+
severity,
|
|
194
|
+
name: message(info),
|
|
195
|
+
source: this.source,
|
|
196
|
+
attributes: mergeAttributes(currentAttributes2(), rest(info)),
|
|
197
|
+
...span === undefined ? {} : { span },
|
|
198
|
+
...failure === undefined ? {} : { error: failure }
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function telemetryTransport(options = {}) {
|
|
203
|
+
return new TelemetryTransport(options);
|
|
204
|
+
}
|
|
205
|
+
// src/export/winston.ts
|
|
206
|
+
function winstonExporter(options) {
|
|
207
|
+
refuseTheLoop(options.logger);
|
|
208
|
+
const spans = options.spans ?? false;
|
|
209
|
+
const spanSeverity = options.spanSeverity ?? "info";
|
|
210
|
+
return {
|
|
211
|
+
export(_resource, batch) {
|
|
212
|
+
for (const signal of batch) {
|
|
213
|
+
if (signal.type === "log") {
|
|
214
|
+
write(options.logger, levelOf(signal.severity), signal.name, meta(signal));
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (!spans)
|
|
218
|
+
continue;
|
|
219
|
+
const severity = signal.status === "error" ? "error" : spanSeverity;
|
|
220
|
+
write(options.logger, levelOf(severity), signal.name, spanMeta(signal));
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function refuseTheLoop(logger) {
|
|
226
|
+
const found = logger.transports?.some((transport) => transport instanceof TelemetryTransport);
|
|
227
|
+
if (found !== true)
|
|
228
|
+
return;
|
|
229
|
+
throw new Error("[telemetry] this logger already has a telemetryTransport(), so exporting " + "to it would be a loop: its lines go to the pipeline, and the pipeline " + "would write them back to it. Use one direction or the other — the " + "transport to collect winston lines, or winstonExporter to write " + "signals — not both on the same logger.");
|
|
230
|
+
}
|
|
231
|
+
function write(logger, level, message, meta) {
|
|
232
|
+
try {
|
|
233
|
+
logger.log({ ...meta, level, message });
|
|
234
|
+
} catch {}
|
|
235
|
+
}
|
|
236
|
+
function meta(signal) {
|
|
237
|
+
return {
|
|
238
|
+
...signal.attributes,
|
|
239
|
+
[FROM_TELEMETRY]: true,
|
|
240
|
+
source: signal.source,
|
|
241
|
+
...signal.span === undefined ? {} : { traceId: signal.span.traceId, spanId: signal.span.spanId }
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
function spanMeta(signal) {
|
|
245
|
+
return {
|
|
246
|
+
...signal.attributes,
|
|
247
|
+
[FROM_TELEMETRY]: true,
|
|
248
|
+
kind: signal.kind,
|
|
249
|
+
status: signal.status,
|
|
250
|
+
durationMs: signal.endedAt - signal.startedAt,
|
|
251
|
+
traceId: signal.context.traceId,
|
|
252
|
+
spanId: signal.context.spanId,
|
|
253
|
+
...signal.parent === undefined ? {} : { parentSpanId: signal.parent },
|
|
254
|
+
...signal.error === undefined ? {} : {
|
|
255
|
+
"exception.type": signal.error.type,
|
|
256
|
+
...signal.error.message === undefined ? {} : { "exception.message": signal.error.message }
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
export {
|
|
261
|
+
FROM_TELEMETRY,
|
|
262
|
+
LEVEL_OF_SEVERITY,
|
|
263
|
+
SEVERITY_OF_LEVEL,
|
|
264
|
+
TelemetryTransport,
|
|
265
|
+
levelOf,
|
|
266
|
+
severityOf,
|
|
267
|
+
telemetryFormat,
|
|
268
|
+
telemetryTransport,
|
|
269
|
+
winstonExporter
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
//# debugId=55BA21733E7F2D3064756E2164756E21
|
|
273
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/bridge/format.ts", "../src/bridge/levels.ts", "../src/bridge/origin.ts", "../src/bridge/transport.ts", "../src/bridge/info.ts", "../src/export/winston.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { currentAttributes, currentSpan } from '@softistx/telemetry';\n\n/**\n * What winston hands a format, and what a format hands back.\n *\n * Declared here rather than imported from `logform`, because the whole point of\n * this package is that it works with winston installed and does not require it\n * at build time. It is the shape winston actually passes: a mutable object with\n * `level` and `message`, and whatever else the caller put in it.\n */\nexport interface LogInfo {\n\tlevel: string;\n\tmessage: any;\n\t/**\n\t * Symbols too, because winston keeps two of its own there — `Symbol.for('level')`\n\t * for the level before any format coloured it, and `Symbol.for('message')` for\n\t * the rendered line. A string-only index signature is not assignable to\n\t * logform's `TransformableInfo`, which is what `combine` takes.\n\t */\n\t[field: string | symbol]: any;\n}\n\n/**\n * A winston format, as winston consumes one: an object with `transform`.\n *\n * `combine(...)` calls `format.transform(info, format.options)` and nothing\n * else, so this is the whole contract. Not importing `winston.format` is what\n * keeps this package installable in a service that has winston in one workspace\n * and not in another.\n */\nexport interface TelemetryFormat {\n\treadonly options: Record<string, unknown>;\n\ttransform(info: LogInfo): LogInfo;\n}\n\nexport interface FormatOptions {\n\t/** Default `traceId`. */\n\treadonly traceField?: string;\n\t/** Default `spanId`. */\n\treadonly spanField?: string;\n\t/**\n\t * Whether the attributes in scope — what `span()` and `withAttributes()`\n\t * were given — are copied onto the line too. Default `true`.\n\t */\n\treadonly attributes?: boolean;\n}\n\n/**\n * Puts the current `traceId` and `spanId` on every line winston writes.\n *\n * ```ts\n * winston.createLogger({\n * format: winston.format.combine(telemetryFormat(), winston.format.json()),\n * });\n * ```\n *\n * This is the half of the bridge that costs nothing to adopt: an application\n * keeps the logger it has, the lines keep the shape they have, and every one of\n * them gains the id that ties it to a trace. Put it **before** the format that\n * renders the line — `json()`, `printf()`, `simple()` — or the fields will be\n * added to something already turned into a string.\n *\n * Outside any span it adds nothing, rather than a null or an empty string: a\n * field that is present and empty is one a dashboard has to filter out.\n */\nexport function telemetryFormat(options: FormatOptions = {}): TelemetryFormat {\n\tconst traceField = options.traceField ?? 'traceId';\n\tconst spanField = options.spanField ?? 'spanId';\n\tconst withAttributes = options.attributes ?? true;\n\n\treturn {\n\t\toptions: {},\n\t\ttransform(info: LogInfo): LogInfo {\n\t\t\t// A format runs on the way to every transport, on every line. It\n\t\t\t// cannot be the reason a line is lost, so nothing in here throws.\n\t\t\ttry {\n\t\t\t\tif (withAttributes) stamp(info, currentAttributes());\n\n\t\t\t\tconst span = currentSpan();\n\t\t\t\tif (span === undefined) return info;\n\n\t\t\t\tinfo[traceField] = span.traceId;\n\t\t\t\tinfo[spanField] = span.spanId;\n\t\t\t} catch {\n\t\t\t\t// A caller's own field stays whatever it already was.\n\t\t\t}\n\t\t\treturn info;\n\t\t},\n\t};\n}\n\n/**\n * The attributes in scope, but never over a field the caller set.\n *\n * A line that says `orderId: 'o-1'` means that order, and an ambient attribute\n * of the same name replacing it would be a lie told quietly.\n */\nfunction stamp(info: LogInfo, attributes: Record<string, unknown>): void {\n\tfor (const [name, value] of Object.entries(attributes)) {\n\t\tif (!(name in info)) info[name] = value;\n\t}\n}\n",
|
|
6
|
+
"import type { Severity } from '@softistx/telemetry';\n\n/**\n * winston's npm levels, and the four this library has.\n *\n * The mapping is lossy in one direction on purpose. `Severity` has four levels\n * because a log level is a *routing* decision and four is as many as anybody\n * routes on; winston's `http`, `verbose` and `silly` are shades of the two it\n * already has, so they land on `info` and `debug` rather than inventing\n * severities nothing downstream would understand.\n *\n * A level winston was configured with but that is not listed here — a custom\n * level set, `syslog`'s `notice`, `crit`, `emerg` — is **not** guessed at. See\n * {@link severityOf}.\n */\nexport const SEVERITY_OF_LEVEL: Readonly<Record<string, Severity>> = {\n\terror: 'error',\n\twarn: 'warn',\n\tinfo: 'info',\n\thttp: 'info',\n\tverbose: 'debug',\n\tdebug: 'debug',\n\tsilly: 'debug',\n};\n\n/** The npm level a signal is written at, going the other way. */\nexport const LEVEL_OF_SEVERITY: Readonly<Record<Severity, string>> = {\n\tdebug: 'debug',\n\tinfo: 'info',\n\twarn: 'warn',\n\terror: 'error',\n};\n\n/**\n * What a winston level means here, or the fallback.\n *\n * The fallback is **`info`**, and it matters which way it errs: a custom level\n * mapped down to `debug` would be dropped by a pipeline with the default\n * `minimum`, and a line that disappears is worse than one recorded a shade too\n * loudly. A `syslog` logger's `crit` arriving as `info` is visible and wrong;\n * as `debug` it is invisible and wrong.\n */\nexport function severityOf(\n\tlevel: string,\n\tfallback: Severity = 'info',\n): Severity {\n\tif (typeof level !== 'string') return fallback;\n\t// winston's `colorize` format rewrites `level` in place, escape codes and\n\t// all, and a logger that colourises before this transport is a normal\n\t// configuration rather than a mistake.\n\treturn SEVERITY_OF_LEVEL[uncoloured(level).trim().toLowerCase()] ?? fallback;\n}\n\n/** The winston level for a severity. Total: every severity has one. */\nexport function levelOf(severity: Severity): string {\n\treturn LEVEL_OF_SEVERITY[severity] ?? 'info';\n}\n\nconst ESCAPE = '\\x1b';\n// biome-ignore lint/suspicious/noControlCharactersInRegex: an escape sequence is made of control characters, which is the thing being removed\nconst ANSI = /\\x1b\\[[0-9;]*m/g;\n\nfunction uncoloured(level: string): string {\n\treturn level.includes(ESCAPE) ? level.replace(ANSI, '') : level;\n}\n",
|
|
7
|
+
"/**\n * The mark a line carries when this library is what wrote it into winston.\n *\n * It exists because the two halves of this bridge point at each other. A logger\n * with a {@link telemetryTransport} sends its lines to the pipeline; a\n * {@link winstonExporter} sends the pipeline's signals to a logger. Both on the\n * same logger is a loop, and a loop here does not crash — it spins, quietly,\n * at whatever rate the process can manage.\n *\n * `winstonExporter` refuses that wiring when it can see it, at construction.\n * This mark is what catches the shapes it cannot see: two loggers pointing at\n * each other, or a transport added after the exporter was built. It is a\n * string key rather than a symbol because it has to survive `JSON.stringify` —\n * winston's `json()` format, a transport that serialises, `logform`'s\n * splat — anywhere the line may be copied before it comes back round.\n */\nexport const FROM_TELEMETRY = 'nxgt.telemetry.origin';\n",
|
|
8
|
+
"import { Writable } from 'node:stream';\nimport {\n\tcurrentAttributes,\n\tcurrentSpan,\n\ttype LogRecord,\n\tmeetsSeverity,\n\tmergeAttributes,\n\tresolveTelemetry,\n\ttype Severity,\n\ttype Telemetry,\n} from '@softistx/telemetry';\nimport type { LogInfo } from './format';\nimport { failureOf, LEVEL, message, rest } from './info';\nimport { severityOf } from './levels';\nimport { FROM_TELEMETRY } from './origin';\n\n/** What a logger looks like from inside the transport it pipes into. */\ninterface WinstonSource {\n\treadonly level?: string;\n\treadonly levels?: Readonly<Record<string, number>>;\n}\n\nexport interface TransportOptions {\n\t/** The source every line is attributed to. Default `winston`. */\n\treadonly source?: string;\n\t/**\n\t * The telemetry to write to. Default: the one in scope when the line is\n\t * written, and the installed one otherwise.\n\t */\n\treadonly telemetry?: Telemetry;\n\t/** What a level this library does not know becomes. Default `info`. */\n\treadonly fallback?: Severity;\n\t/** winston's own option: the lowest level this transport receives. */\n\treadonly level?: string;\n\t/** winston's own option: a transport that is silent receives nothing. */\n\treadonly silent?: boolean;\n\t/**\n\t * Whether a line winston's `exceptionHandlers` produced is collected too.\n\t * Default `false`, which is winston's own default for a transport.\n\t *\n\t * It is off for a reason worth knowing. Turning it on puts this transport in\n\t * winston's list of exception handlers, and winston then waits for each of\n\t * them to emit `finish` before letting the process exit — up to three\n\t * seconds. A `process.on('uncaughtException')` that calls `log.error` and\n\t * awaits `telemetry.close()` is the direct route, and costs no exit delay.\n\t */\n\treadonly handleExceptions?: boolean;\n}\n\n/**\n * A winston transport that writes every line into the telemetry pipeline.\n *\n * ```ts\n * logger.add(telemetryTransport());\n * ```\n *\n * The other half of the bridge, for an application that already logs through\n * winston and wants those lines exported the way its spans are — to OTLP, to\n * Mongo, to a file — without rewriting a single call site.\n *\n * It extends `node:stream`'s `Writable` rather than `winston-transport`, which\n * is the same thing winston-transport does and means **this package has no\n * runtime dependency**: it is installable in a workspace that does not have\n * winston at all. What winston requires of a transport is a writable stream in\n * object mode with a `log(info, next)` of arity two, and that is what this is.\n */\nexport class TelemetryTransport extends Writable {\n\treadonly source: string;\n\treadonly level?: string;\n\t/** Set by winston when this is piped to a logger, and used to honour `level`. */\n\tlevels: Readonly<Record<string, number>> | undefined;\n\t/** The logger this is attached to, which is where a default level comes from. */\n\tparent: { readonly level?: string } | undefined;\n\tsilent: boolean;\n\treadonly handleExceptions: boolean;\n\tprivate readonly telemetry: Telemetry | undefined;\n\tprivate readonly fallback: Severity;\n\n\tconstructor(options: TransportOptions = {}) {\n\t\tsuper({ objectMode: true });\n\t\tthis.source = options.source ?? 'winston';\n\t\tif (options.level !== undefined) this.level = options.level;\n\t\tthis.silent = options.silent ?? false;\n\t\tthis.handleExceptions = options.handleExceptions ?? false;\n\t\tthis.telemetry = options.telemetry;\n\t\tthis.fallback = options.fallback ?? 'info';\n\n\t\t// How winston-transport learns its logger, and the only way to: a\n\t\t// logger pipes itself into its transports, and Node's `Writable` emits\n\t\t// `pipe` with the source. Without this, `level` on a transport would be\n\t\t// a field nothing reads — winston does the filtering *in the transport*,\n\t\t// not before it.\n\t\tthis.once('pipe', (logger: WinstonSource) => {\n\t\t\tthis.levels ??= logger.levels;\n\t\t\tthis.parent ??= logger;\n\t\t});\n\t\t// `logger.remove(transport)` unpipes. Left pointing at the old logger,\n\t\t// `parent` would keep filtering by a level that is no longer anybody's.\n\t\tthis.on('unpipe', () => {\n\t\t\tthis.parent = undefined;\n\t\t});\n\t}\n\n\t/**\n\t * Arity two, which is what winston checks to decide this is a modern\n\t * transport rather than a legacy one it has to wrap.\n\t */\n\tlog(info: LogInfo, next: () => void): void {\n\t\ttry {\n\t\t\tthis.post(info);\n\t\t} catch {\n\t\t\t// A transport that throws takes down the line for every *other*\n\t\t\t// transport too. Writing a log must not be able to fail.\n\t\t}\n\t\tnext();\n\t}\n\n\toverride _write(\n\t\tinfo: LogInfo,\n\t\t_encoding: BufferEncoding,\n\t\tnext: (error?: Error | null) => void,\n\t): void {\n\t\tif (this.silent || !this.wanted(info)) {\n\t\t\tnext();\n\t\t\treturn;\n\t\t}\n\t\tif (info['exception'] === true && !this.handleExceptions) {\n\t\t\tnext();\n\t\t\treturn;\n\t\t}\n\t\tthis.log(info, () => next());\n\t}\n\n\t/**\n\t * The level filter, the way winston-transport applies it.\n\t *\n\t * The level to compare against is the transport's own, falling back to the\n\t * logger's, and the comparison is on winston's *numbers* — where a lower\n\t * number is more severe. `info[Symbol.for('level')]` is the line's level\n\t * before any format coloured it, which is why it is read rather than\n\t * `info.level`.\n\t */\n\tprivate wanted(info: LogInfo): boolean {\n\t\t// `||` rather than `??`, which is winston's own: a transport with\n\t\t// `level: ''` falls back to the logger's there, and must here too.\n\t\tconst level = this.level || this.parent?.level;\n\t\tif (!level || this.levels === undefined) return true;\n\n\t\tconst wrote = this.levels[String(info[LEVEL] ?? info.level)];\n\t\tconst floor = this.levels[level];\n\t\t// **Deliberately not winston's answer here.** `winston-transport` compares\n\t\t// against `undefined`, which is `false`, so a line at a level the table\n\t\t// does not know is dropped. This keeps it: a level nobody declared is\n\t\t// somebody's mistake, and losing the line is how the mistake stays\n\t\t// invisible. Everything else in this method is winston's rule exactly.\n\t\tif (wrote === undefined || floor === undefined) return true;\n\n\t\treturn floor >= wrote;\n\t}\n\n\tprivate post(info: LogInfo): void {\n\t\t// A line this library wrote into winston, coming back round. Posting it\n\t\t// would be an infinite loop that looks like a busy service.\n\t\tif (info[FROM_TELEMETRY] === true) return;\n\n\t\tconst telemetry = this.telemetry ?? resolveTelemetry();\n\t\tif (telemetry === undefined) return;\n\n\t\tconst severity = severityOf(info.level, this.fallback);\n\t\t// The pipeline's floor, the same one `log.*` clears. winston has already\n\t\t// applied its own; this is the telemetry's, and a service that set\n\t\t// `minimum: 'error'` means it for every route into the pipeline.\n\t\tif (!meetsSeverity(severity, telemetry.minimum)) return;\n\n\t\ttelemetry.emit(this.record(info, severity, telemetry.stackTraces));\n\t}\n\n\tprivate record(\n\t\tinfo: LogInfo,\n\t\tseverity: Severity,\n\t\tstackTraces: boolean,\n\t): LogRecord {\n\t\tconst span = currentSpan();\n\t\tconst failure = failureOf(info, stackTraces);\n\n\t\treturn {\n\t\t\ttype: 'log',\n\t\t\tat: Date.now(),\n\t\t\tseverity,\n\t\t\tname: message(info),\n\t\t\tsource: this.source,\n\t\t\t// The attributes in scope, under the line's own — which is the\n\t\t\t// inheritance rule everywhere else in this library, and a field the\n\t\t\t// call site set must still win.\n\t\t\tattributes: mergeAttributes(currentAttributes(), rest(info)),\n\t\t\t...(span === undefined ? {} : { span }),\n\t\t\t...(failure === undefined ? {} : { error: failure }),\n\t\t};\n\t}\n}\n\n/**\n * A winston transport, as an instance.\n *\n * `telemetryTransport()` reads better at a call site than `new\n * TelemetryTransport()`, and matches how every other integration here is built.\n */\nexport function telemetryTransport(\n\toptions: TransportOptions = {},\n): TelemetryTransport {\n\treturn new TelemetryTransport(options);\n}\n",
|
|
9
|
+
"import {\n\ttype Attributes,\n\tattributesOf,\n\ttype ErrorInfo,\n\terrorInfo,\n} from '@softistx/telemetry';\nimport type { LogInfo } from './format';\n\n/**\n * winston's own fields, which become the record rather than attributes.\n *\n * `stack` is here because `format.errors()` puts it on the line, and it belongs\n * in the record's `ErrorInfo` where an exporter knows what it is — as\n * `exception.stacktrace` on the wire — rather than as a free-text attribute\n * nothing queries. `exception` is winston's own flag for a line its\n * `exceptionHandlers` produced.\n */\nconst OWN: ReadonlySet<string> = new Set([\n\t'level',\n\t'message',\n\t'stack',\n\t'exception',\n]);\n\n/**\n * Where winston keeps the line's level *before* any format coloured it.\n *\n * `Symbol.for`, not a fresh symbol: it is the same registry entry `logform`\n * uses, and reading it is how every winston transport decides what to keep.\n */\nexport const LEVEL = Symbol.for('level');\n\n/**\n * The line's text.\n *\n * winston's `message` is whatever was passed — a string, an object, an `Error`.\n * `attributesOf` would render an object to a string eventually, but the name of\n * a log record is the thing a human reads first, so it is worth one explicit\n * pass.\n */\nexport function message(info: LogInfo): string {\n\tconst text = info.message;\n\tif (typeof text === 'string') return text;\n\tif (text instanceof Error) return text.message;\n\tif (text === undefined || text === null) return '';\n\n\ttry {\n\t\treturn typeof text === 'object' ? JSON.stringify(text) : String(text);\n\t} catch {\n\t\t// A circular object, or a getter that throws. The line still arrives.\n\t\treturn String(text);\n\t}\n}\n\n/**\n * The failure a line is about, if it is about one.\n *\n * winston takes an `Error` three ways — as the message, as `error` in the meta,\n * and as a `stack` string that `format.errors()` left behind — and an exporter\n * needs it as an `ErrorInfo` or it is only text. Without this, an OTLP consumer\n * gets no `exception.type` for a line that was written with an exception in\n * hand, which is the one field an exception dashboard queries on.\n */\nexport function failureOf(\n\tinfo: LogInfo,\n\tstackTraces: boolean,\n): ErrorInfo | undefined {\n\tif (info.message instanceof Error)\n\t\treturn errorInfo(info.message, stackTraces);\n\tif (info['error'] instanceof Error)\n\t\treturn errorInfo(info['error'], stackTraces);\n\tif (typeof info['stack'] !== 'string' || info['stack'] === '')\n\t\treturn undefined;\n\n\t// `format.errors()` flattens the error onto the line and keeps only the\n\t// stack, so this is what is left to rebuild from.\n\tconst rebuilt: ErrorInfo = {\n\t\ttype: typeOf(info['stack']),\n\t\tmessage: message(info),\n\t};\n\t// Named rather than spread: a spread into an object literal turns off the\n\t// excess-property check, which is what would let a misspelled field through\n\t// — and `stackTrace` is easy to write as `stack`, which is what winston\n\t// calls it.\n\treturn stackTraces ? { ...rebuilt, stackTrace: info['stack'] } : rebuilt;\n}\n\n/** `TypeError: bad` is a `TypeError`; anything unrecognisable is an `Error`. */\nfunction typeOf(stack: string): string {\n\tconst named = /^([A-Za-z_$][\\w$]*(?:Error|Exception))\\b/.exec(stack);\n\treturn named?.[1] ?? 'Error';\n}\n\n/** Everything the caller added, through the coercion that never refuses. */\nexport function rest(info: LogInfo): Attributes {\n\tconst carried: Record<string, unknown> = {};\n\n\tfor (const [name, value] of Object.entries(info)) {\n\t\tif (!OWN.has(name)) carried[name] = value;\n\t}\n\n\treturn attributesOf(carried);\n}\n",
|
|
10
|
+
"import type {\n\tExporter,\n\tLogRecord,\n\tResource,\n\tSeverity,\n\tSignal,\n\tSpanRecord,\n} from '@softistx/telemetry';\nimport { levelOf } from '../bridge/levels';\nimport { FROM_TELEMETRY } from '../bridge/origin';\nimport { TelemetryTransport } from '../bridge/transport';\n\n/**\n * What this exporter needs of a logger.\n *\n * Structural, so that `winston.Logger`, a child logger, and\n * `@nxgt/shared-logging`'s `Logger` — which *is* winston's — all fit without\n * this package importing any of them.\n */\nexport interface WinstonLike {\n\tlog(info: Record<string, unknown>): unknown;\n\treadonly transports?: readonly unknown[];\n}\n\nexport interface WinstonExporterOptions {\n\t/** The logger the signals are written to. */\n\treadonly logger: WinstonLike;\n\t/** Whether spans are written as lines too. Default `false`. */\n\treadonly spans?: boolean;\n\t/** The level a span is written at. Default `info`. */\n\treadonly spanSeverity?: Severity;\n}\n\n/**\n * Telemetry signals into a winston logger that is already there.\n *\n * ```ts\n * createTelemetry('checkout', {\n * exporters: [winstonExporter({ logger })],\n * }).install();\n * ```\n *\n * For an application whose log shipping is solved — a file rotation, a syslog\n * transport, a vendor's — and that wants `log.info(...)` from this library to\n * land in the same place as everything else, rather than a second pipe to\n * operate.\n *\n * Spans are **off** by default. A span is a duration and a set of attributes,\n * which is a poor fit for a line of text, and turning every one of them into a\n * log line is how a cheap trace becomes an expensive log bill. `spans: true`\n * when the lines are what you have.\n *\n * A **failed span is always written at `error`**, whatever `spanSeverity` says.\n * That is the line somebody is looking for.\n */\nexport function winstonExporter(options: WinstonExporterOptions): Exporter {\n\trefuseTheLoop(options.logger);\n\n\tconst spans = options.spans ?? false;\n\tconst spanSeverity = options.spanSeverity ?? 'info';\n\n\treturn {\n\t\texport(_resource: Resource, batch: readonly Signal[]): void {\n\t\t\tfor (const signal of batch) {\n\t\t\t\tif (signal.type === 'log') {\n\t\t\t\t\twrite(\n\t\t\t\t\t\toptions.logger,\n\t\t\t\t\t\tlevelOf(signal.severity),\n\t\t\t\t\t\tsignal.name,\n\t\t\t\t\t\tmeta(signal),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!spans) continue;\n\n\t\t\t\tconst severity = signal.status === 'error' ? 'error' : spanSeverity;\n\t\t\t\twrite(options.logger, levelOf(severity), signal.name, spanMeta(signal));\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * A logger that already feeds the pipeline must not also be fed by it.\n *\n * Caught at construction, because the failure mode is a loop that does not\n * crash: it spins, and the first sign of it is a machine at 100% writing the\n * same line to itself. A message at startup is the cheapest possible version of\n * that discovery.\n */\nfunction refuseTheLoop(logger: WinstonLike): void {\n\tconst found = logger.transports?.some(\n\t\t(transport) => transport instanceof TelemetryTransport,\n\t);\n\tif (found !== true) return;\n\n\tthrow new Error(\n\t\t'[telemetry] this logger already has a telemetryTransport(), so exporting ' +\n\t\t\t'to it would be a loop: its lines go to the pipeline, and the pipeline ' +\n\t\t\t'would write them back to it. Use one direction or the other — the ' +\n\t\t\t'transport to collect winston lines, or winstonExporter to write ' +\n\t\t\t'signals — not both on the same logger.',\n\t);\n}\n\n/**\n * One line, through winston's **single-argument** `log`.\n *\n * Not `log(level, message, meta)`, and the difference is not cosmetic. On the\n * three-argument path winston tests the message against `/%[scdjifoO%]/` and,\n * when it matches, treats the meta as printf arguments — they go to\n * `Symbol.for('splat')` and **none of them reach the line**. A span named\n * `GET /files/%s`, or a log message that merely contains a `%d`, would lose its\n * `traceId`, its attributes, and the mark that stops this bridge looping.\n *\n * The one-argument form is winston's own hot path: it takes the object as the\n * line, sets the level and writes it. Nothing is parsed, so nothing is lost.\n */\nfunction write(\n\tlogger: WinstonLike,\n\tlevel: string,\n\tmessage: string,\n\tmeta: Record<string, unknown>,\n): void {\n\ttry {\n\t\tlogger.log({ ...meta, level, message });\n\t} catch {\n\t\t// An exporter that throws reaches `onExportError` and costs the rest of\n\t\t// the batch. A logger with a broken transport is not worth that.\n\t}\n}\n\nfunction meta(signal: LogRecord): Record<string, unknown> {\n\treturn {\n\t\t...signal.attributes,\n\t\t[FROM_TELEMETRY]: true,\n\t\tsource: signal.source,\n\t\t...(signal.span === undefined\n\t\t\t? {}\n\t\t\t: { traceId: signal.span.traceId, spanId: signal.span.spanId }),\n\t};\n}\n\nfunction spanMeta(signal: SpanRecord): Record<string, unknown> {\n\treturn {\n\t\t...signal.attributes,\n\t\t[FROM_TELEMETRY]: true,\n\t\tkind: signal.kind,\n\t\tstatus: signal.status,\n\t\tdurationMs: signal.endedAt - signal.startedAt,\n\t\ttraceId: signal.context.traceId,\n\t\tspanId: signal.context.spanId,\n\t\t...(signal.parent === undefined ? {} : { parentSpanId: signal.parent }),\n\t\t...(signal.error === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\t'exception.type': signal.error.type,\n\t\t\t\t\t...(signal.error.message === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { 'exception.message': signal.error.message }),\n\t\t\t\t}),\n\t};\n}\n"
|
|
11
|
+
],
|
|
12
|
+
"mappings": ";AAAA;AAiEO,SAAS,eAAe,CAAC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AAAA,IAClB,MAAM,OAAO;AAAA,IACb,QAAQ,OAAO;AAAA,IACf,YAAY,OAAO,UAAU,OAAO;AAAA,IACpC,SAAS,OAAO,QAAQ;AAAA,IACxB,QAAQ,OAAO,QAAQ;AAAA,OACnB,OAAO,WAAW,YAAY,CAAC,IAAI,EAAE,cAAc,OAAO,OAAO;AAAA,OACjE,OAAO,UAAU,YAClB,CAAC,IACD;AAAA,MACA,kBAAkB,OAAO,MAAM;AAAA,SAC3B,OAAO,MAAM,YAAY,YAC1B,CAAC,IACD,EAAE,qBAAqB,OAAO,MAAM,QAAQ;AAAA,IAChD;AAAA,EACH;AAAA;",
|
|
13
|
+
"debugId": "55BA21733E7F2D3064756E2164756E21",
|
|
14
|
+
"names": []
|
|
15
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,71 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@softistx/telemetry-logging",
|
|
3
|
+
"version": "0.3.3",
|
|
4
|
+
"description": "The winston bridge for @softistx/telemetry: trace ids on every line, winston lines into the pipeline, and telemetry signals into a winston already in place",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"README.md",
|
|
12
|
+
"package.json",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"import": "./dist/index.js",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"winston",
|
|
25
|
+
"telemetry",
|
|
26
|
+
"observability",
|
|
27
|
+
"logging",
|
|
28
|
+
"tracing",
|
|
29
|
+
"opentelemetry",
|
|
30
|
+
"typescript"
|
|
31
|
+
],
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/softistx/nxgt-telemetry.git",
|
|
35
|
+
"directory": "packages/telemetry-logging"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"registry": "https://registry.npmjs.org",
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "bun run ../../build.ts",
|
|
43
|
+
"test": "bun test src",
|
|
44
|
+
"typecheck": "tsc --noEmit"
|
|
45
|
+
},
|
|
46
|
+
"nxgt": {
|
|
47
|
+
"entrypoints": [
|
|
48
|
+
"src/index.ts"
|
|
49
|
+
]
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"@softistx/telemetry": "^0.4.2"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@types/bun": "^1.4.2",
|
|
56
|
+
"winston": "3.19.0",
|
|
57
|
+
"winston-transport": "4.9.0"
|
|
58
|
+
},
|
|
59
|
+
"peerDependencies": {
|
|
60
|
+
"typescript": "^6.0.3 || ^7.0.0",
|
|
61
|
+
"winston": "^3.11.0"
|
|
62
|
+
},
|
|
63
|
+
"peerDependenciesMeta": {
|
|
64
|
+
"typescript": {
|
|
65
|
+
"optional": true
|
|
66
|
+
},
|
|
67
|
+
"winston": {
|
|
68
|
+
"optional": true
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|