0
# Configuration
1
2
Comprehensive configuration system for customizing logger behavior, output formatting, styling, masking, and operational settings.
3
4
## Capabilities
5
6
### Settings Interface
7
8
Main configuration interface for logger initialization with all available options.
9
10
```typescript { .api }
11
/**
12
* Logger configuration parameters
13
* @template LogObj - Type for log object structure
14
*/
15
interface ISettingsParam<LogObj> {
16
/** Output format: "json" for structured output, "pretty" for human-readable, "hidden" to suppress output */
17
type?: "json" | "pretty" | "hidden";
18
19
/** Logger name for identification and hierarchy */
20
name?: string;
21
22
/** Parent logger names for nested logger hierarchies */
23
parentNames?: string[];
24
25
/** Minimum log level to output (0=silly, 1=trace, 2=debug, 3=info, 4=warn, 5=error, 6=fatal) */
26
minLevel?: number;
27
28
/** Parent logger names for nested logger hierarchies */
29
parentNames?: string[];
30
31
/** Property name for arguments array in JSON output */
32
argumentsArrayName?: string;
33
34
/** Hide file position information in production environments */
35
hideLogPositionForProduction?: boolean;
36
37
/** Template string for pretty log format with placeholders */
38
prettyLogTemplate?: string;
39
40
/** Template string for error formatting */
41
prettyErrorTemplate?: string;
42
43
/** Template string for error stack trace formatting */
44
prettyErrorStackTemplate?: string;
45
46
/** Separator for parent logger names in error output */
47
prettyErrorParentNamesSeparator?: string;
48
49
/** Delimiter for logger names in error output */
50
prettyErrorLoggerNameDelimiter?: string;
51
52
/** Apply ANSI color styling to pretty logs */
53
stylePrettyLogs?: boolean;
54
55
/** Timezone for timestamp formatting */
56
prettyLogTimeZone?: "UTC" | "local";
57
58
/** ANSI styling configuration for different log components */
59
prettyLogStyles?: IPrettyLogStyles;
60
61
/** Options for object inspection and formatting */
62
prettyInspectOptions?: InspectOptions;
63
64
/** Property name to store metadata in log objects */
65
metaProperty?: string;
66
67
/** Replacement text for masked sensitive values */
68
maskPlaceholder?: string;
69
70
/** Array of object keys whose values should be masked */
71
maskValuesOfKeys?: string[];
72
73
/** Whether key masking should be case-insensitive */
74
maskValuesOfKeysCaseInsensitive?: boolean;
75
76
/** Regular expressions for masking values in logs */
77
maskValuesRegEx?: RegExp[];
78
79
/** Prefix arguments added to every log message */
80
prefix?: unknown[];
81
82
/** Array of attached transport functions */
83
attachedTransports?: ((transportLogger: LogObj & ILogObjMeta) => void)[];
84
85
/** Override default internal functions */
86
overwrite?: ConfigurationOverrides<LogObj>;
87
}
88
```
89
90
**Usage Examples:**
91
92
```typescript
93
import { Logger } from "tslog";
94
95
// Basic configuration
96
const logger = new Logger({
97
name: "MyApp",
98
type: "pretty",
99
minLevel: 2,
100
});
101
102
// Production configuration
103
const prodLogger = new Logger({
104
name: "ProductionApp",
105
type: "json",
106
hideLogPositionForProduction: true,
107
prettyLogTimeZone: "UTC",
108
maskValuesOfKeys: ["password", "token", "secret"],
109
maskPlaceholder: "[REDACTED]",
110
});
111
112
// Development configuration with styling
113
const devLogger = new Logger({
114
name: "DevApp",
115
type: "pretty",
116
stylePrettyLogs: true,
117
prettyLogStyles: {
118
logLevelName: {
119
ERROR: ["bold", "red"],
120
WARN: ["bold", "yellow"],
121
INFO: ["bold", "blue"],
122
},
123
},
124
});
125
```
126
127
### Styling Configuration
128
129
ANSI styling options for different components of pretty-formatted log output.
130
131
```typescript { .api }
132
interface IPrettyLogStyles {
133
/** Year component styling */
134
yyyy?: TStyle;
135
/** Month component styling */
136
mm?: TStyle;
137
/** Day component styling */
138
dd?: TStyle;
139
/** Hour component styling */
140
hh?: TStyle;
141
/** Minute component styling */
142
MM?: TStyle;
143
/** Second component styling */
144
ss?: TStyle;
145
/** Millisecond component styling */
146
ms?: TStyle;
147
/** Full ISO date string styling */
148
dateIsoStr?: TStyle;
149
/** Log level name styling */
150
logLevelName?: TStyle;
151
/** File name styling */
152
fileName?: TStyle;
153
/** File name with line number styling */
154
fileNameWithLine?: TStyle;
155
/** File path styling */
156
filePath?: TStyle;
157
/** File line number styling */
158
fileLine?: TStyle;
159
/** File path with line number styling */
160
filePathWithLine?: TStyle;
161
/** Logger name styling */
162
name?: TStyle;
163
/** Logger name with prefix delimiter styling */
164
nameWithDelimiterPrefix?: TStyle;
165
/** Logger name with suffix delimiter styling */
166
nameWithDelimiterSuffix?: TStyle;
167
/** Error name styling */
168
errorName?: TStyle;
169
/** Error message styling */
170
errorMessage?: TStyle;
171
}
172
173
type TStyle =
174
| null
175
| string
176
| string[]
177
| {
178
[value: string]: null | string | string[];
179
};
180
```
181
182
**Usage Examples:**
183
184
```typescript
185
import { Logger } from "tslog";
186
187
// Custom styling configuration
188
const styledLogger = new Logger({
189
name: "StyledApp",
190
type: "pretty",
191
stylePrettyLogs: true,
192
prettyLogStyles: {
193
// Style log levels differently
194
logLevelName: {
195
ERROR: ["bold", "red", "bgWhite"],
196
WARN: ["bold", "yellow"],
197
INFO: ["bold", "blue"],
198
DEBUG: ["dim", "green"],
199
},
200
// Style timestamps
201
dateIsoStr: ["dim", "white"],
202
// Style file paths
203
filePathWithLine: ["underline", "cyan"],
204
// Style logger names
205
name: ["bold", "magenta"],
206
},
207
});
208
209
// Available style options: colors, background colors, and modifiers
210
const detailedStyles = {
211
logLevelName: {
212
// Colors: black, red, green, yellow, blue, magenta, cyan, white
213
// Bright colors: blackBright, redBright, greenBright, etc.
214
ERROR: ["bold", "redBright"],
215
216
// Background colors: bgBlack, bgRed, bgGreen, etc.
217
// Bright backgrounds: bgBlackBright, bgRedBright, etc.
218
WARN: ["bold", "black", "bgYellow"],
219
220
// Modifiers: bold, dim, italic, underline, strikethrough, inverse
221
DEBUG: ["dim", "italic", "green"],
222
},
223
};
224
```
225
226
### Template Configuration
227
228
Customizable templates for log output formatting with placeholder replacement.
229
230
```typescript { .api }
231
/**
232
* Default pretty log template with available placeholders:
233
* {{yyyy}}, {{mm}}, {{dd}}, {{hh}}, {{MM}}, {{ss}}, {{ms}}
234
* {{dateIsoStr}}, {{logLevelName}}, {{fileName}}, {{filePath}}
235
* {{fileLine}}, {{filePathWithLine}}, {{name}}, {{nameWithDelimiterPrefix}}
236
*/
237
prettyLogTemplate: string; // Default: "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t{{filePathWithLine}}{{nameWithDelimiterPrefix}}\t"
238
239
/**
240
* Template for error formatting
241
*/
242
prettyErrorTemplate: string; // Default: "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}"
243
244
/**
245
* Template for error stack trace entries
246
*/
247
prettyErrorStackTemplate: string; // Default: " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}"
248
```
249
250
**Usage Examples:**
251
252
```typescript
253
import { Logger } from "tslog";
254
255
// Custom template configuration
256
const customLogger = new Logger({
257
name: "CustomFormat",
258
type: "pretty",
259
prettyLogTemplate: "[{{dateIsoStr}}] {{logLevelName}} ({{name}}): ",
260
prettyErrorTemplate: "ERROR: {{errorName}} - {{errorMessage}}\nStack:\n{{errorStack}}",
261
prettyErrorStackTemplate: " at {{method}} ({{filePathWithLine}})",
262
});
263
264
// Minimal template
265
const minimalLogger = new Logger({
266
type: "pretty",
267
prettyLogTemplate: "{{logLevelName}}: ",
268
});
269
```
270
271
### Masking Configuration
272
273
Security features for hiding sensitive information in log output.
274
275
```typescript { .api }
276
/**
277
* Masking configuration options
278
*/
279
interface MaskingConfig {
280
/** Replacement text for masked values */
281
maskPlaceholder?: string; // Default: "[***]"
282
283
/** Object keys whose values should be masked */
284
maskValuesOfKeys?: string[]; // Default: ["password"]
285
286
/** Case-insensitive key matching */
287
maskValuesOfKeysCaseInsensitive?: boolean; // Default: false
288
289
/** Regular expressions for value masking */
290
maskValuesRegEx?: RegExp[];
291
}
292
```
293
294
**Usage Examples:**
295
296
```typescript
297
import { Logger } from "tslog";
298
299
// Security-focused logger
300
const secureLogger = new Logger({
301
name: "SecureApp",
302
maskPlaceholder: "[REDACTED]",
303
maskValuesOfKeys: [
304
"password", "token", "secret", "key", "auth",
305
"authorization", "credential", "apiKey"
306
],
307
maskValuesOfKeysCaseInsensitive: true,
308
maskValuesRegEx: [
309
/\b[\w\.-]+@[\w\.-]+\.\w+\b/g, // Email addresses
310
/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, // Credit card numbers
311
],
312
});
313
314
// Example of masking in action
315
secureLogger.info("User login", {
316
username: "john_doe",
317
password: "secret123", // Will be masked
318
email: "john@example.com", // Will be masked by regex
319
});
320
```
321
322
### Override Configuration
323
324
Advanced configuration for overriding internal logger functions.
325
326
```typescript { .api }
327
interface ConfigurationOverrides<LogObj> {
328
/** Override placeholder replacement function */
329
addPlaceholders?: (logObjMeta: IMeta, placeholderValues: Record<string, string | number>) => void;
330
331
/** Override value masking function */
332
mask?: (args: unknown[]) => unknown[];
333
334
/** Override log object creation function */
335
toLogObj?: (args: unknown[], clonesLogObj?: LogObj) => LogObj;
336
337
/** Override metadata addition function */
338
addMeta?: (logObj: LogObj, logLevelId: number, logLevelName: string) => LogObj & ILogObjMeta;
339
340
/** Override metadata formatting function */
341
formatMeta?: (meta?: IMeta) => string;
342
343
/** Override log object formatting function */
344
formatLogObj?: (maskedArgs: unknown[], settings: ISettings<LogObj>) => { args: unknown[]; errors: string[] };
345
346
/** Override formatted output transport function */
347
transportFormatted?: (logMetaMarkup: string, logArgs: unknown[], logErrors: string[], settings: ISettings<LogObj>) => void;
348
349
/** Override JSON output transport function */
350
transportJSON?: (json: unknown) => void;
351
}
352
```
353
354
## Resolved Settings Interface
355
356
```typescript { .api }
357
/**
358
* Resolved settings interface with all defaults applied
359
* @template LogObj - Type for log object structure
360
*/
361
interface ISettings<LogObj> extends ISettingsParam<LogObj> {
362
type: "json" | "pretty" | "hidden";
363
minLevel: number;
364
hideLogPositionForProduction: boolean;
365
prettyLogTemplate: string;
366
prettyErrorTemplate: string;
367
prettyErrorStackTemplate: string;
368
prettyErrorParentNamesSeparator: string;
369
prettyErrorLoggerNameDelimiter: string;
370
stylePrettyLogs: boolean;
371
prettyLogTimeZone: "UTC" | "local";
372
prettyLogStyles: IPrettyLogStyles;
373
prettyInspectOptions: InspectOptions;
374
metaProperty: string;
375
maskPlaceholder: string;
376
maskValuesOfKeys: string[];
377
maskValuesOfKeysCaseInsensitive: boolean;
378
prefix: unknown[];
379
attachedTransports: ((transportLogger: LogObj & ILogObjMeta) => void)[];
380
}
381
```
382
383
## InspectOptions Interface
384
385
```typescript { .api }
386
/**
387
* Options for object inspection and formatting
388
* Based on Node.js util.inspect options
389
*/
390
interface InspectOptions {
391
/** Enable colors in output */
392
colors?: boolean;
393
394
/** Compact object formatting */
395
compact?: boolean;
396
397
/** Maximum depth for object inspection */
398
depth?: number;
399
400
/** Maximum array length to display */
401
maxArrayLength?: number;
402
403
/** Maximum string length to display */
404
maxStringLength?: number;
405
406
/** Show hidden properties */
407
showHidden?: boolean;
408
409
/** Show proxy details */
410
showProxy?: boolean;
411
}
412
```