You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+50-47Lines changed: 50 additions & 47 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -11,7 +11,7 @@
11
11
12
12
13
13
> Powerful, fast and expressive logging for TypeScript and JavaScript
14
-
14
+
15
15

16
16
17
17
@@ -49,13 +49,13 @@ Donations help me allocate more time for my open source work.
49
49
50
50
## Install
51
51
52
-
> ❗ **`tslog` is a native ES module.**
52
+
> ❗ **`tslog` is a native ES module.**
53
53
54
54
```bash
55
55
npm install tslog
56
56
```
57
57
58
-
In order to run a native ES module in Node.js, you have to do two things:
58
+
In order to run a native ES module in Node.js, you have to do two things:
59
59
60
60
1) Set `"type": "module"` in `package.json`.
61
61
2) For now, start with `--experimental-specifier-resolution=node`
@@ -180,21 +180,21 @@ logger.fatal(new Error("I am a pretty Error with a stacktrace."));
180
180
181
181
## API documentation
182
182
183
-
> **`tslog >= v4` is a major rewrite and introduces breaking changes.** <br>
184
-
> Please, follow this documentation when migrating.
183
+
> **`tslog >= v4` is a major rewrite and introduces breaking changes.** <br>
184
+
> Please, follow this documentation when migrating.
185
185
186
186
### <aname="life_cycle"></a>Lifecycle of a log message
187
187
188
-
Every incoming log message runs through a number of steps before being displayed or handed over to a "transport". Every step can be overwritten and adjusted.
188
+
Every incoming log message runs through a number of steps before being displayed or handed over to a "transport". Every step can be overwritten and adjusted.
189
189
190
190

191
191
192
192
-**log message** Log message comes in through the `BaseLogger.log()` method
193
193
-**mask** If masking is configured, log message gets recursively masked
194
-
-**toLogObj** Log message gets transformed into a log object: A default typed log object can be passed to constructor as a second parameter and will be cloned and enriched with the incoming log parameters. Error properties will be handled accordingly. If there is only one log property, and it's an object, both objects (cloned default `logObj` as well as the log property object) will be merged. If there are more than one, they will be put into properties called "0", "1", ... and so on. Alternatively, log message properties can be put into a property with a name configured with the `argumentsArrayName` setting.
194
+
-**toLogObj** Log message gets transformed into a log object: A default typed log object can be passed to constructor as a second parameter and will be cloned and enriched with the incoming log parameters. Error properties will be handled accordingly. If there is only one log property, and it's an object, both objects (cloned default `logObj` as well as the log property object) will be merged. If there are more than one, they will be put into properties called "0", "1", ... and so on. Alternatively, log message properties can be put into a property with a name configured with the `argumentsArrayName` setting.
195
195
-**addMetaToLogObj** Additional meta information, like the source code position of the log will be gathered and added to the `_meta` property or any other one configured with the setting `metaProperty`.
196
-
-**format** In case of "pretty" configuration, a log object will be formatted based on the templates configured in settings. Meta will be formatted by the method `_prettyFormatLogObjMeta` and the actual log payload will be formatted by `prettyFormatLogObj`. Both steps can be overwritten with the settings `formatMeta` and `formatMeta`.
197
-
-**transport** Last step is to "transport" a log message to every attached transport from the setting `attachedTransports`. Last step is the actual transport, either JSON (`transportJSON`), formatted (`transportFormatted`) or omitted, if its set to "hidden". Both default transports can also be overwritten by the corresponding setting.
196
+
-**format** In case of "pretty" configuration, a log object will be formatted based on the templates configured in settings. Meta will be formatted by the method `_prettyFormatLogObjMeta` and the actual log payload will be formatted by `prettyFormatLogObj`. Both steps can be overwritten with the settings `formatMeta` and `formatMeta`.
197
+
-**transport** Last step is to "transport" a log message to every attached transport from the setting `attachedTransports`. Last step is the actual transport, either JSON (`transportJSON`), formatted (`transportFormatted`) or omitted, if its set to "hidden". Both default transports can also be overwritten by the corresponding setting.
198
198
199
199
### Default log level
200
200
@@ -245,16 +245,16 @@ export class CustomLogger<LogObj> extends BaseLogger<LogObj> {
245
245
```
246
246
247
247
### Settings
248
-
`tslog` is highly customizable and pretty much every aspect can be either configured or overwritten.
248
+
`tslog` is highly customizable and pretty much every aspect can be either configured or overwritten.
249
249
A `settings` object is the first parameter passed to the `tslog` constructor:
-`pretty`**Default setting** prints out a formatted structured "pretty" log entry.
257
+
-`pretty`**Default setting** prints out a formatted structured "pretty" log entry.
258
258
-`json` prints out a `JSON` formatted log entry.
259
259
-`hidden` suppresses any output whatsoever and can be used with attached loggers for example.
260
260
@@ -275,16 +275,16 @@ const hiddenLogger = new Logger({type: "hidden"});
275
275
276
276
#### name
277
277
278
-
Each logger has an optional name.
279
-
You can find the name of the logger responsible for a log inside the `Meta`-object or printed in `pretty` mode.
280
-
Names get also inherited to sub loggers and can be found inside the `Meta`-object `parentNames` as well as printed out with a separator (e.g. `:`) in `pretty` mode.
278
+
Each logger has an optional name.
279
+
You can find the name of the logger responsible for a log inside the `Meta`-object or printed in `pretty` mode.
280
+
Names get also inherited to sub loggers and can be found inside the `Meta`-object `parentNames` as well as printed out with a separator (e.g. `:`) in `pretty` mode.
2022-11-17 10:45:47.705 SILLY [/examples/nodejs/index2.ts:51 MainLogger] foo bar
302
-
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:54 MainLogger:FirstSubLogger] foo bar 1
303
-
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:57 MainLogger:FirstSubLogger:SecondSubLogger] foo bar 2
301
+
2022-11-17 10:45:47.705 SILLY [/examples/nodejs/index2.ts:51] MainLogger foo bar
302
+
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:54] MainLogger:FirstSubLogger foo bar 1
303
+
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:57] MainLogger:FirstSubLogger:SecondSubLogger foo bar 2
304
304
```
305
305
306
306
#### minLevel
@@ -318,7 +318,7 @@ suppressSilly.trace("Will be visible");
318
318
319
319
#### argumentsArrayName
320
320
321
-
`tslog` < 4 wrote all parameters into an arguments array. In `tslog` >= 4 the main object becomes home for all log parameters, and they get merged with the default `logObj`.
321
+
`tslog` < 4 wrote all parameters into an arguments array. In `tslog` >= 4 the main object becomes home for all log parameters, and they get merged with the default `logObj`.
322
322
If you still want to put them into a separated parameter, you can do so by defining the `argumentsArrayName`.
323
323
324
324
```typescript
@@ -344,7 +344,7 @@ Enables you to overwrite the looks of a formatted _"pretty"_ log message by prov
344
344
Following settings are available for styling:
345
345
346
346
-**Templates:**
347
-
-`prettyLogTemplate`: template string for log messages. Possible placeholders:
347
+
-`prettyLogTemplate`: template string for log messages. Possible placeholders:
348
348
-`{{yyyy}}`: year
349
349
-`{{mm}}`: month
350
350
-`{{dd}}`: day
@@ -353,31 +353,33 @@ Following settings are available for styling:
353
353
-`{{ss}}`: seconds
354
354
-`{{ms}}`: milliseconds
355
355
-`{{dateIsoStr}}`: Shortcut for `{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}`
356
+
-`{{rawIsoStr}}`: Renders the date and time in ISO format (e.g.: YYYY-MM-DDTHH:mm:ss.SSSZ)
356
357
-`{{logLevelName}}`: name of the log level
357
358
-`{{name}}`: optional name of the current logger and his parents (e.g. "ParentLogger:ThisLogger")
358
359
-`{{fullFilePath}}`: a full path starting from `/` root
359
360
-`{{filePathWithLine}}`: a full path below the project path with line number
360
361
-`prettyErrorTemplate`: template string for error message. Possible placeholders:
361
362
-`{{errorName}}`: name of the error
362
363
-`{{errorMessage}}`: error message
363
-
-`{{errorStack}}`: Placeholder for all stack lines defined by `prettyErrorStackTemplate`
364
+
-`{{errorStack}}`: Placeholder for all stack lines defined by `prettyErrorStackTemplate`
364
365
-`prettyErrorStackTemplate`: template string for error stack trace lines. Possible placeholders:
365
366
-`{{fileName}}`: name of the file
366
367
-`{{filePathWithLine}}`: a full path below the project path with a line number
367
368
-`{{method}}`: _optional_ name of the invoking method
368
369
-`prettyErrorParentNamesSeparator`: separator to be used when joining names ot the parent logger, and the current one (default: `:`)
370
+
-`prettyErrorLoggerNameDelimiter`: if a logger name is set this delimiter will be added afterwards
-`stylePrettyLogs`: defines whether logs should be styled and colorized
373
375
-`prettyLogStyles`: provides colors and styles for different placeholders and can also be dependent on the value (e.g. log level)
374
376
- Level 1: template placeholder (defines a style for a certain template placeholder, s. above, without brackets).
375
-
- Level 2: Either a string with one style (e.g. `white`), or an array of styles (e.g. `["bold", "white"]`), or a nested object with key being a value.
377
+
- Level 2: Either a string with one style (e.g. `white`), or an array of styles (e.g. `["bold", "white"]`), or a nested object with key being a value.
376
378
- Level 3: Optional nested style based on placeholder values. Key is the value of the template placeholder and value is either a string of a style, or an array of styles (s. above), e.g. `{ SILLY: ["bold", "white"] }` which means: value "SILLY" should get a style of "bold" and "white". `*` means any value other than the defined.
377
379
-`prettyInspectOptions`: When a (potentially nested) object is printed out in Node.js, we use `util.formatWithOptions` under the hood. With `prettyInspectOptions` you can define the output. [Possible values](https://nodejs.org/api/util.html#utilinspectobject-showhidden-depth-colors)
378
380
379
381
#### Log meta information
380
-
`tslog` collects meta information for every log, like runtime, code position etc. The meta information collected depends on the runtime (browser or Node.js) and is accessible through the `LogObj`.
382
+
`tslog` collects meta information for every log, like runtime, code position etc. The meta information collected depends on the runtime (browser or Node.js) and is accessible through the `LogObj`.
381
383
You can define the property containing this meta information with `metaProperty`, which is "_meta" by default.
@@ -467,7 +470,7 @@ like sending messages to _Slack_ or _Telegram_ in case of an urgent error or for
467
470
468
471
##### Simple transport example
469
472
470
-
Here is a very simple implementation used in our _jest_ tests.
473
+
Here is a very simple implementation used in our _jest_ tests.
471
474
This example will suppress logs from being sent to `console` (`type: "hidden"`) and will instead collect them in an `array`.
472
475
473
476
```typescript
@@ -502,10 +505,10 @@ logger.warn("I am a warn log with a json object:", { foo: "bar" });
502
505
503
506
##### Storing logs in a file system with rotating files
504
507
505
-
If you want to limit the file size of the stored logs, a good practice is to use file rotation, where old logs will be deleted automatically.
508
+
If you want to limit the file size of the stored logs, a good practice is to use file rotation, where old logs will be deleted automatically.
506
509
There is a great library called `rotating-file-stream` solving this problem for us and even adding features like compression, file size limit etc.
507
510
508
-
1. First you need to install this library:
511
+
1. First you need to install this library:
509
512
```bash
510
513
npm i rotating-file-stream
511
514
```
@@ -533,7 +536,7 @@ logger.warn("I am a warn log with a json object:", { foo: "bar" });
533
536
534
537
```
535
538
536
-
#### Overwriting default behavior
539
+
#### Overwriting default behavior
537
540
538
541
One of the key advantages of `tslog` >= 4 is that you can overwrite pretty much every aspect of the log processing described in <ahref="#life_cycle">"Lifecycle of a log message"</a>.
539
542
@@ -567,7 +570,7 @@ For `pretty` logs:
567
570
// format LogObj attributes to a string and return it
// overwrite the default transport for formatted (e.g. pretty) log levels. e.g. replace console with StdOut, write to file etc.
573
+
// overwrite the default transport for formatted (e.g. pretty) log levels. e.g. replace console with StdOut, write to file etc.
571
574
},
572
575
},
573
576
});
@@ -590,7 +593,7 @@ As described in <a href="#life_cycle">"Lifecycle of a log message"</a>, every lo
590
593
A default logObj can be passed to the `tslog` constructor and will be cloned and merged into the log message. This makes `tslog` >= 4 highly configurable and easy to integrate into any 3rd party service.
591
594
The entire `logObj` will be printed out in `JSON` mode and also returned by every log method.
592
595
593
-
> **Tip:** All properties of the default `LogObj` containing function calls will be executed for every log message making use cases possible like `requestId` (s. below).
596
+
> **Tip:** All properties of the default `LogObj` containing function calls will be executed for every log message making use cases possible like `requestId` (s. below).
0 commit comments