Skip to content

Commit e75b7a2

Browse files
committed
Add named loggers
1 parent aa3a766 commit e75b7a2

File tree

6 files changed

+85
-12
lines changed

6 files changed

+85
-12
lines changed

README.md

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,17 @@ In order to run a native ES module in Node.js, you have to do two things:
6161
2) For now, start with `--experimental-specifier-resolution=node`
6262

6363
Example `package.json`
64-
```json
64+
```json5
6565
{
6666
"name": "NAME",
6767
"version": "1.0.0",
6868
"main": "index.js",
69-
"type": "module", // <-- here
69+
// here:
70+
"type": "module",
7071
"scripts": {
7172
"build": "tsc -p .",
72-
"start": "node --enable-source-maps --experimental-specifier-resolution=node index.js" // <-- and here
73+
// and here:
74+
"start": "node --enable-source-maps --experimental-specifier-resolution=node index.js"
7375
},
7476
"dependencies": {
7577
"tslog": "^4"
@@ -144,7 +146,7 @@ This feature enables `tslog` to reference a correct line number in your TypeScri
144146
```typescript
145147
import { Logger } from "tslog";
146148

147-
const logger = new Logger();
149+
const logger = new Logger({ name: "myLogger" });
148150
logger.silly("I am a silly log.");
149151
logger.trace("I am a trace log.");
150152
logger.debug("I am a debug log.");
@@ -169,6 +171,8 @@ logger.fatal(new Error("I am a pretty Error with a stacktrace."));
169171
- **Pretty Error:** Errors and stack traces printed in a structured way and fully accessible through _JSON_ (e.g. external Log services)
170172
- **ES Modules:** import syntax with ([tree-shaking](https://webpack.js.org/guides/tree-shaking/))
171173
- **Object/JSON highlighting:** Nicely prints out objects
174+
- **Instance Name**: _(Server-side only)_ Logs capture instance name (default host name) making it easy to distinguish logs coming from different instances
175+
- **Named Logger:** Logger can be named (e.g. useful for packages/modules and monorepos)
172176
- **Sub Logger with inheritance:** Powerful sub-loggers with settings inheritance, also at runtime
173177
- **Secrets masking:** Prevent passwords and secrets from sneaking into log files by masking them
174178
- **Short paths:** Paths are relative to the root of the application folder
@@ -268,6 +272,36 @@ const jsonLogger = new Logger({type: "json"});
268272
const hiddenLogger = new Logger({type: "hidden"});
269273
```
270274

275+
276+
#### Name
277+
278+
Each logger has an optional name. You can find the name of the logger responsible for a log inside the `Meta`-object or printed in `pretty` mode.
279+
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. `:`).
280+
281+
Simple name example:
282+
```typescript
283+
new Logger({ name: "myLogger" });
284+
```
285+
286+
Sub-loggers with an inherited name:
287+
```typescript
288+
const mainLogger = new Logger({ type: "pretty", name: "MainLogger" });
289+
mainLogger.silly("foo bar");
290+
291+
const firstSubLogger = mainLogger.getSubLogger({ name: "FirstSubLogger" });
292+
firstSubLogger.silly("foo bar 1");
293+
294+
const secondSubLogger = firstSubLogger.getSubLogger({ name: "SecondSubLogger" });
295+
secondSubLogger.silly("foo bar 2");
296+
```
297+
298+
Output:
299+
```shell
300+
2022-11-17 10:45:47.705 SILLY [/examples/nodejs/index2.ts:51 MainLogger] foo bar
301+
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:54 MainLogger:FirstSubLogger] foo bar 1
302+
2022-11-17 10:45:47.706 SILLY [/examples/nodejs/index2.ts:57 MainLogger:FirstSubLogger:SecondSubLogger] foo bar 2
303+
```
304+
271305
#### minLevel
272306

273307
You can ignore every log message from being processed until a certain severity.
@@ -276,7 +310,7 @@ Default severities are:
276310

277311
```typescript
278312

279-
const suppressSilly = new Logger({minLevel: 1 });
313+
const suppressSilly = new Logger({ minLevel: 1 });
280314
suppressSilly.silly("Will be hidden");
281315
suppressSilly.trace("Will be visible");
282316
```
@@ -319,6 +353,7 @@ Following settings are available for styling:
319353
- `{{ms}}`: milliseconds
320354
- `{{dateIsoStr}}`: Shortcut for `{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}`
321355
- `{{logLevelName}}`: name of the log level
356+
- `{{name}}`: optional name of the current logger and his parents (e.g. "ParentLogger:ThisLogger")
322357
- `{{fullFilePath}}`: a full path starting from `/` root
323358
- `{{filePathWithLine}}`: a full path below the project path with line number
324359
- `prettyErrorTemplate`: template string for error message. Possible placeholders:
@@ -329,6 +364,7 @@ Following settings are available for styling:
329364
- `{{fileName}}`: name of the file
330365
- `{{filePathWithLine}}`: a full path below the project path with a line number
331366
- `{{method}}`: _optional_ name of the invoking method
367+
- `prettyErrorParentNamesSeparator`: separator to be used when joining names ot the parent logger, and the current one (default: `:`)
332368
- `prettyInspectOptions`: <a href="https://nodejs.org/api/util.html#utilinspectobject-options" target="_blank">Available options</a>
333369

334370
- **Styling:**
@@ -348,9 +384,10 @@ You can define the property containing this meta information with `metaProperty`
348384
```typescript
349385

350386
const logger = new Logger({
351-
prettyLogTemplate: "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t[{{filePathWithLine}}]\t",
387+
prettyLogTemplate: "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t[{{filePathWithLine}}{{name}}]\t",
352388
prettyErrorTemplate: "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}",
353389
prettyErrorStackTemplate: " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}",
390+
prettyErrorParentNamesSeparator: ":",
354391
stylePrettyLogs: true,
355392
prettyLogStyles: {
356393
logLevelName: {
@@ -365,6 +402,7 @@ const logger = new Logger({
365402
},
366403
dateIsoStr: "white",
367404
filePathWithLine: "white",
405+
name: "white",
368406
errorName: ["bold", "bgRedBright", "whiteBright"],
369407
fileName: ["yellow"],
370408
},

examples/nodejs/index2.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,11 @@ jsonLoggerArgumentsArray.silly("test1", "test2");
4747

4848
////////////////////////////
4949

50-
const log = new Logger({ type: "json" }, { name: "DefaultLogger" });
50+
const mainLogger = new Logger({ type: "pretty", name: "MainLogger" });
51+
mainLogger.silly("foo bar");
5152

52-
log.silly("foo bar");
53+
const firstSubLogger = mainLogger.getSubLogger({ name: "FirstSubLogger" });
54+
firstSubLogger.silly("foo bar 1");
55+
56+
const secondSubLogger = firstSubLogger.getSubLogger({ name: "SecondSubLogger" });
57+
secondSubLogger.silly("foo bar 2");

src/BaseLogger.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,15 @@ export class BaseLogger<LogObj> {
1919

2020
this.settings = {
2121
type: settings?.type ?? "pretty",
22+
name: settings?.name,
23+
parentNames: settings?.parentNames,
2224
minLevel: settings?.minLevel ?? 0,
2325
argumentsArrayName: settings?.argumentsArrayName,
24-
prettyLogTemplate: settings?.prettyLogTemplate ?? "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t[{{filePathWithLine}}]\t",
26+
prettyLogTemplate:
27+
settings?.prettyLogTemplate ?? "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t[{{filePathWithLine}}{{name}}]\t",
2528
prettyErrorTemplate: settings?.prettyErrorTemplate ?? "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}",
2629
prettyErrorStackTemplate: settings?.prettyErrorTemplate ?? " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}",
30+
prettyErrorParentNamesSeparator: settings?.prettyErrorParentNamesSeparator ?? ":",
2731
stylePrettyLogs: settings?.stylePrettyLogs ?? true,
2832
prettyLogStyles: settings?.prettyLogStyles ?? {
2933
logLevelName: {
@@ -38,6 +42,7 @@ export class BaseLogger<LogObj> {
3842
},
3943
dateIsoStr: "white",
4044
filePathWithLine: "white",
45+
name: "white",
4146
errorName: ["bold", "bgRedBright", "whiteBright"],
4247
fileName: ["yellow"],
4348
},
@@ -150,6 +155,13 @@ export class BaseLogger<LogObj> {
150155
const subLoggerSettings: ISettings<LogObj> = {
151156
...this.settings,
152157
...settings,
158+
// collect parent names in Array
159+
parentNames:
160+
this.settings?.parentNames != null && this.settings?.name != null
161+
? [...this.settings.parentNames, this.settings.name]
162+
: this.settings?.name != null
163+
? [this.settings.name]
164+
: undefined,
153165
// merge all prefixes instead of overwriting them
154166
prefix: [...this.settings.prefix, ...(settings?.prefix ?? [])],
155167
};
@@ -244,7 +256,7 @@ export class BaseLogger<LogObj> {
244256
private _addMetaToLogObj(logObj: LogObj, logLevelId: number, logLevelName: string): LogObj & ILogObjMeta & ILogObj {
245257
return {
246258
...logObj,
247-
[this.settings.metaProperty]: getMeta(logLevelId, logLevelName, this.stackDepthLevel),
259+
[this.settings.metaProperty]: getMeta(logLevelId, logLevelName, this.stackDepthLevel, this.settings.name, this.settings.parentNames),
248260
};
249261
}
250262

@@ -273,6 +285,10 @@ export class BaseLogger<LogObj> {
273285
placeholderValues["logLevelName"] = logObjMeta?.logLevelName;
274286
placeholderValues["filePathWithLine"] = logObjMeta?.path?.filePathWithLine;
275287
placeholderValues["fullFilePath"] = logObjMeta?.path?.fullFilePath;
288+
// name
289+
let parentNamesString = this.settings.parentNames?.join(this.settings.prettyErrorParentNamesSeparator);
290+
parentNamesString = parentNamesString != null && logObjMeta?.name != null ? parentNamesString + this.settings.prettyErrorParentNamesSeparator : undefined;
291+
placeholderValues["name"] = logObjMeta?.name != null || parentNamesString != null ? " " + (parentNamesString ?? "") + logObjMeta?.name ?? "" : "";
276292

277293
return formatTemplate(this.settings, template, placeholderValues);
278294
}

src/interfaces.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,14 @@ export type TStyle =
1010

1111
export interface ISettingsParam<LogObj> {
1212
type?: "json" | "pretty" | "hidden";
13+
name?: string;
14+
parentNames?: string[];
1315
minLevel?: number;
1416
argumentsArrayName?: string;
1517
prettyLogTemplate?: string;
1618
prettyErrorTemplate?: string;
1719
prettyErrorStackTemplate?: string;
20+
prettyErrorParentNamesSeparator?: string;
1821
stylePrettyLogs?: boolean;
1922
prettyLogStyles?: {
2023
yyyy?: TStyle;
@@ -53,11 +56,14 @@ export interface ISettingsParam<LogObj> {
5356

5457
export interface ISettings<LogObj> extends ISettingsParam<LogObj> {
5558
type: "json" | "pretty" | "hidden";
59+
name?: string;
60+
parentNames?: string[];
5661
minLevel: number;
5762
argumentsArrayName?: string;
5863
prettyLogTemplate: string;
5964
prettyErrorTemplate: string;
6065
prettyErrorStackTemplate: string;
66+
prettyErrorParentNamesSeparator: string;
6167
stylePrettyLogs: boolean;
6268
prettyLogStyles: {
6369
yyyy?: TStyle;
@@ -73,6 +79,7 @@ export interface ISettings<LogObj> extends ISettingsParam<LogObj> {
7379
filePath?: TStyle;
7480
fileLine?: TStyle;
7581
filePathWithLine?: TStyle;
82+
name?: TStyle;
7683
errorName?: TStyle;
7784
errorMessage?: TStyle;
7885
};

src/runtime/browser/index.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { formatTemplate } from "../../formatTemplate";
33
import { inspect } from "./util.inspect.polyfil";
44

55
export interface IMetaStatic {
6+
name?: string;
7+
parentNames?: string[];
68
runtime: string;
79
browser: string;
810
}
@@ -19,9 +21,10 @@ const meta: IMetaStatic = {
1921
browser: window?.["navigator"].userAgent,
2022
};
2123

22-
export function getMeta(logLevelId: number, logLevelName: string, stackDepthLevel: number): IMeta {
24+
export function getMeta(logLevelId: number, logLevelName: string, stackDepthLevel: number, name?: string): IMeta {
2325
return {
2426
...meta,
27+
name,
2528
date: new Date(),
2629
logLevelId,
2730
logLevelName,

src/runtime/nodejs/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import { formatTemplate } from "../../formatTemplate";
66
export { InspectOptions };
77

88
export interface IMetaStatic {
9+
name?: string;
10+
parentNames?: string[];
911
runtime: string;
1012
hostname: string;
1113
}
@@ -22,9 +24,11 @@ const meta: IMetaStatic = {
2224
hostname: hostname(),
2325
};
2426

25-
export function getMeta(logLevelId: number, logLevelName: string, stackDepthLevel: number): IMeta {
27+
export function getMeta(logLevelId: number, logLevelName: string, stackDepthLevel: number, name?: string, parentNames?: string[]): IMeta {
2628
return {
2729
...meta,
30+
name,
31+
parentNames,
2832
date: new Date(),
2933
logLevelId,
3034
logLevelName,

0 commit comments

Comments
 (0)