0
# Format System
1
2
Comprehensive log message formatting system with built-in formatters and composable format transformations for customizing log output across all transports.
3
4
## Capabilities
5
6
### Format Interface
7
8
Base interface for all format transformations that process log info objects.
9
10
```javascript { .api }
11
/**
12
* Base format interface for log transformations
13
*/
14
interface Format {
15
/** Transform function that processes log info objects */
16
transform: (info: TransformableInfo, options?: any) => TransformableInfo | boolean;
17
}
18
19
interface TransformableInfo {
20
/** Log level (error, warn, info, etc.) */
21
level: string;
22
/** Log message */
23
message: string;
24
/** Timestamp if added by timestamp format */
25
timestamp?: string;
26
/** Any additional metadata */
27
[key: string]: any;
28
}
29
```
30
31
### Built-in Formats
32
33
Core formatting functions available through `winston.format`.
34
35
```javascript { .api }
36
/**
37
* JSON format - outputs log as JSON string
38
* @returns Format that stringifies log info as JSON
39
*/
40
function json(): Format;
41
42
/**
43
* Simple format - basic level and message output
44
* @returns Format that outputs "level: message" format
45
*/
46
function simple(): Format;
47
48
/**
49
* Combine multiple formats into a single format
50
* @param formats - Array of formats to combine
51
* @returns Combined format that applies all formats in sequence
52
*/
53
function combine(...formats: Format[]): Format;
54
55
/**
56
* Add timestamp to log messages
57
* @param options - Timestamp configuration options
58
* @returns Format that adds timestamp property
59
*/
60
function timestamp(options?: TimestampOptions): Format;
61
62
/**
63
* Colorize log levels and messages for console output
64
* @param options - Colorization configuration
65
* @returns Format that adds color codes
66
*/
67
function colorize(options?: ColorizeOptions): Format;
68
69
/**
70
* Custom template format using printf-style function
71
* @param templateFunction - Function that returns formatted string
72
* @returns Format using custom template
73
*/
74
function printf(templateFunction: (info: TransformableInfo) => string): Format;
75
76
/**
77
* Enhanced error formatting with stack traces
78
* @param options - Error formatting options
79
* @returns Format that processes Error objects
80
*/
81
function errors(options?: ErrorsOptions): Format;
82
83
/**
84
* Add label to log messages
85
* @param options - Label configuration
86
* @returns Format that adds label property
87
*/
88
function label(options?: LabelOptions): Format;
89
90
/**
91
* Logstash-compatible JSON format
92
* @returns Format for Logstash/ELK stack compatibility
93
*/
94
function logstash(): Format;
95
96
/**
97
* Pretty-print objects and nested data
98
* @param options - Pretty printing options
99
* @returns Format for readable object output
100
*/
101
function prettyPrint(options?: PrettyPrintOptions): Format;
102
103
/**
104
* String interpolation format (util.format style)
105
* @returns Format that handles string interpolation
106
*/
107
function splat(): Format;
108
109
/**
110
* Remove color codes from log messages
111
* @returns Format that strips ANSI color codes
112
*/
113
function uncolorize(): Format;
114
115
/**
116
* Align log messages for better readability
117
* @returns Format that aligns text output
118
*/
119
function align(): Format;
120
121
/**
122
* CLI-specific formatting with colors and levels
123
* @param options - CLI formatting options
124
* @returns Format optimized for command-line output
125
*/
126
function cli(options?: CliOptions): Format;
127
128
/**
129
* Add millisecond timing information
130
* @returns Format that adds timing deltas
131
*/
132
function ms(): Format;
133
134
/**
135
* Metadata formatting for structured logging
136
* @param options - Metadata configuration
137
* @returns Format that handles metadata objects
138
*/
139
function metadata(options?: MetadataOptions): Format;
140
```
141
142
**Usage Examples:**
143
144
```javascript
145
const winston = require('winston');
146
147
// Basic JSON format
148
const logger = winston.createLogger({
149
format: winston.format.json(),
150
transports: [new winston.transports.Console()]
151
});
152
153
// Combined formats
154
const logger2 = winston.createLogger({
155
format: winston.format.combine(
156
winston.format.timestamp(),
157
winston.format.errors({ stack: true }),
158
winston.format.json()
159
),
160
transports: [new winston.transports.Console()]
161
});
162
163
// Custom printf format
164
const logger3 = winston.createLogger({
165
format: winston.format.combine(
166
winston.format.timestamp(),
167
winston.format.printf(({ timestamp, level, message, ...meta }) => {
168
return `${timestamp} [${level.toUpperCase()}]: ${message} ${Object.keys(meta).length ? JSON.stringify(meta) : ''}`;
169
})
170
),
171
transports: [new winston.transports.Console()]
172
});
173
```
174
175
### Format Options Interfaces
176
177
Configuration interfaces for various format functions.
178
179
```javascript { .api }
180
interface TimestampOptions {
181
/** Timestamp format string (moment.js style) */
182
format?: string;
183
/** Property name for timestamp (default: 'timestamp') */
184
alias?: string;
185
}
186
187
interface ColorizeOptions {
188
/** Colorize the level */
189
level?: boolean;
190
/** Colorize everything */
191
all?: boolean;
192
/** Colorize the message */
193
message?: boolean;
194
/** Custom color mapping */
195
colors?: { [level: string]: string };
196
}
197
198
interface ErrorsOptions {
199
/** Include stack trace in error formatting */
200
stack?: boolean;
201
}
202
203
interface LabelOptions {
204
/** Label string to add */
205
label?: string;
206
/** Add label to message instead of separate property */
207
message?: boolean;
208
}
209
210
interface PrettyPrintOptions {
211
/** Object inspection depth */
212
depth?: number;
213
/** Colorize pretty-printed output */
214
colorize?: boolean;
215
}
216
217
interface CliOptions {
218
/** Logging levels configuration */
219
levels?: { [level: string]: number };
220
/** Colors configuration */
221
colors?: { [level: string]: string };
222
}
223
224
interface MetadataOptions {
225
/** Property name for metadata */
226
key?: string;
227
/** Fill properties from metadata */
228
fillExcept?: string[];
229
/** Fill only these properties from metadata */
230
fillWith?: string[];
231
}
232
```
233
234
### Creating Custom Formats
235
236
Creating custom format transformations for specialized logging needs.
237
238
```javascript { .api }
239
/**
240
* Create a custom format function
241
* @param transformFunction - Function that transforms log info
242
* @returns Custom format instance
243
*/
244
function format(transformFunction: (info: TransformableInfo) => TransformableInfo | boolean): Format;
245
```
246
247
**Usage Examples:**
248
249
```javascript
250
const winston = require('winston');
251
252
// Custom format to add request ID
253
const addRequestId = winston.format((info, opts) => {
254
if (opts.requestId) {
255
info.requestId = opts.requestId;
256
}
257
return info;
258
});
259
260
// Custom format to filter sensitive data
261
const filterSensitive = winston.format((info) => {
262
if (info.password) {
263
info.password = '[REDACTED]';
264
}
265
if (info.creditCard) {
266
delete info.creditCard;
267
}
268
return info;
269
});
270
271
// Custom format for performance logging
272
const performanceFormat = winston.format((info) => {
273
if (info.duration && info.duration > 1000) {
274
info.performanceFlag = 'SLOW';
275
}
276
return info;
277
});
278
279
// Use custom formats
280
const logger = winston.createLogger({
281
format: winston.format.combine(
282
addRequestId({ requestId: 'req-123' }),
283
filterSensitive(),
284
performanceFormat(),
285
winston.format.timestamp(),
286
winston.format.json()
287
),
288
transports: [new winston.transports.Console()]
289
});
290
```
291
292
### Advanced Format Patterns
293
294
**Conditional formatting:**
295
296
```javascript
297
const winston = require('winston');
298
299
const conditionalFormat = winston.format((info, opts) => {
300
if (process.env.NODE_ENV === 'production') {
301
// Remove debug information in production
302
delete info.debugInfo;
303
delete info.trace;
304
}
305
return info;
306
});
307
308
const logger = winston.createLogger({
309
format: winston.format.combine(
310
conditionalFormat(),
311
winston.format.json()
312
),
313
transports: [new winston.transports.Console()]
314
});
315
```
316
317
**Environment-specific formatting:**
318
319
```javascript
320
const winston = require('winston');
321
322
const createFormat = () => {
323
if (process.env.NODE_ENV === 'development') {
324
return winston.format.combine(
325
winston.format.colorize(),
326
winston.format.timestamp({ format: 'HH:mm:ss' }),
327
winston.format.printf(({ timestamp, level, message }) => {
328
return `${timestamp} ${level}: ${message}`;
329
})
330
);
331
}
332
333
return winston.format.combine(
334
winston.format.timestamp(),
335
winston.format.errors({ stack: true }),
336
winston.format.json()
337
);
338
};
339
340
const logger = winston.createLogger({
341
format: createFormat(),
342
transports: [
343
new winston.transports.Console(),
344
new winston.transports.File({ filename: 'app.log' })
345
]
346
});
347
```
348
349
**Multi-transport formatting:**
350
351
```javascript
352
const winston = require('winston');
353
354
const logger = winston.createLogger({
355
level: 'info',
356
transports: [
357
// Console with colorized simple format
358
new winston.transports.Console({
359
format: winston.format.combine(
360
winston.format.colorize(),
361
winston.format.simple()
362
)
363
}),
364
// File with structured JSON format
365
new winston.transports.File({
366
filename: 'app.log',
367
format: winston.format.combine(
368
winston.format.timestamp(),
369
winston.format.errors({ stack: true }),
370
winston.format.json()
371
)
372
}),
373
// Error file with detailed formatting
374
new winston.transports.File({
375
filename: 'error.log',
376
level: 'error',
377
format: winston.format.combine(
378
winston.format.timestamp(),
379
winston.format.errors({ stack: true }),
380
winston.format.printf(({ timestamp, level, message, stack }) => {
381
return `${timestamp} [${level.toUpperCase()}]: ${message}\n${stack || ''}`;
382
})
383
)
384
})
385
]
386
});
387
```
388
389
## Format System Integration
390
391
The format system integrates seamlessly with all Winston components:
392
393
- **Logger instances**: Can specify global format applied to all transports
394
- **Individual transports**: Can override global format with transport-specific formatting
395
- **Exception/Rejection handlers**: Use formats for error logging
396
- **Child loggers**: Inherit parent format but can be overridden
397
- **Query results**: Format system processes queried log entries
398
399
This provides maximum flexibility for different logging scenarios while maintaining consistent APIs across the entire Winston ecosystem.