support AsyncLocalStorage stored object merged into logs, breaking changes to constru...
[squeep-logger-json-console] / README.md
1 # @squeep/logger-json-console
2
3 A simple logger class, which mostly just structures messages, data, and some metadata as JSON and spews it, by default, to Console.
4
5 Supports basic scrubbing of well-defined sensitive fields, and an extensible set of JSON replacer functions for common objects.
6
7 If provided with an asyncLocalStorage instance, it expects a stored object which will be spread over the resulting logged json, taking precedence.
8
9 Intended to be specific to Squeep Framework Applications, this module has opinions.
10
11 ## API
12
13 Expects these arguments in any log call:
14
15 - `scope` - e.g. file:method
16 - `message` - text
17 - `data` - object
18 - any additional arguments are included as an array, but not scrubbed
19
20 ## JSON Replacers
21
22 Includes replacers for these objects:
23
24 - Error
25 - BigInt
26 - http.IncomingMessage
27 - http.OutgoingMessage
28 - http.ServerResponse
29
30 Custom replacers may be inserted into the logger instance's `jsonReplacers` array.
31
32 ## Data Sanitizers
33
34 Custom sanitizers may be inserted into the logger instance's `dataSanitizers` array.
35
36 ## Example
37
38 ```javascript
39 const http = require('node:http');
40 const { AsyncLocalStorage } = require('node:async_hooks');
41 const uuid = require('uuid');
42 const Logger = require('@squeep/logger-json-console');
43
44 const loggerOptions = {
45 ignoreBelowLevel: 'info',
46 };
47 const commonObject = {
48 nodeIdentifier: uuid.v1(),
49 };
50 const asyncLocalStorage = new AsyncLocalStorage();
51 const logger = new Logger(loggerOptions, commonObject, asyncLocalStorage);
52
53 const scope = 'exampleServer';
54 http.createServer((req, res) => {
55 asyncLocalStorage.run({ requestId: uuid.v1() }, () => {
56 logger.debug(scope, 'start', { req, res });
57 setImmediate(() => {
58 res.end();
59 logger.info(scope, 'finish', { req, res }, 'other stuff');
60 });
61 });
62 }).listen(8088);
63 ```
64
65 Results in messages such as this:
66
67 ```json
68 {
69 "nodeIdentifier": "64610280-fc17-11ed-a918-1dd19f027d43",
70 "timestamp": "2023-05-26T22:48:17.995Z",
71 "timestampMs": 1685141297995,
72 "level": "info",
73 "scope": "exampleServer",
74 "message": "finish",
75 "data": {
76 "req": {
77 "method": "GET",
78 "url": "/",
79 "httpVersion": "1.1",
80 "headers": {
81 "host": "localhost:8088",
82 "user-agent": "curl/7.83.1",
83 "accept": "*/*"
84 },
85 "trailers": {}
86 },
87 "res": {
88 "statusCode": 200,
89 "statusMessage": "OK",
90 "headers": {}
91 }
92 },
93 "other": [
94 "other stuff"
95 ],
96 "requestId": "68233aa0-fc17-11ed-a918-1dd19f027d43"
97 }
98 ```