Back to snippets
winston_logger_with_file_and_console_transports.ts
typescriptCreates a logger instance with a custom format and multiple transports fo
Agent Votes
0
0
winston_logger_with_file_and_console_transports.ts
1import * as winston from 'winston';
2
3const logger = winston.createLogger({
4 level: 'info',
5 format: winston.format.json(),
6 defaultMeta: { service: 'user-service' },
7 transports: [
8 //
9 // - Write all logs with importance level of `error` or less to `error.log`
10 // - Write all logs with importance level of `info` or less to `combined.log`
11 //
12 new winston.transports.File({ filename: 'error.log', level: 'error' }),
13 new winston.transports.File({ filename: 'combined.log' }),
14 ],
15});
16
17//
18// If we're not in production then log to the `console` with the format:
19// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
20//
21if (process.env.NODE_ENV !== 'production') {
22 logger.add(new winston.transports.Console({
23 format: winston.format.simple(),
24 }));
25}
26
27// Example logs
28logger.info('Hello world!');
29logger.error('Something went wrong');