|
1 | | -export default { |
2 | | - log(...args: unknown[]) { |
3 | | - console.log(...args); |
4 | | - }, |
| 1 | +import { CI, NODE_ENV } from './config'; |
| 2 | +import winston from 'winston'; |
| 3 | +import util from 'node:util'; |
5 | 4 |
|
6 | | - info(...args: unknown[]) { |
7 | | - console.info(...args); |
8 | | - }, |
9 | | - |
10 | | - warn(...args: unknown[]) { |
11 | | - console.warn(...args); |
12 | | - }, |
| 5 | +const stripSymbols = (anyObj: unknown): unknown => { |
| 6 | + return typeof anyObj === 'object' && |
| 7 | + anyObj !== null && |
| 8 | + Object.keys(anyObj).length && |
| 9 | + !Array.isArray(anyObj) |
| 10 | + ? Object.fromEntries(Object.entries(anyObj)) |
| 11 | + : anyObj; |
| 12 | +}; |
13 | 13 |
|
14 | | - error(...args: unknown[]) { |
15 | | - if (args.every((a) => a instanceof Error)) { |
16 | | - console.error(...args.map((a) => a.toString())); |
17 | | - } else { |
18 | | - console.error(...args); |
19 | | - } |
20 | | - }, |
| 14 | +const inspectObj = (anyObj: unknown): string => { |
| 15 | + if (typeof anyObj === 'string') return anyObj; |
| 16 | + const obj = stripSymbols(anyObj); |
| 17 | + return util.inspect(obj, { depth: null, colors: true, compact: CI }); |
21 | 18 | }; |
| 19 | + |
| 20 | +const winstonLevelColorsExt = Object.fromEntries( |
| 21 | + Object.entries(winston.config.npm.colors).map(([level, color]) => [ |
| 22 | + level.toUpperCase(), |
| 23 | + color, |
| 24 | + ]) |
| 25 | +); |
| 26 | + |
| 27 | +winston.addColors(winstonLevelColorsExt); |
| 28 | + |
| 29 | +export const logger = winston.createLogger({ |
| 30 | + format: winston.format.combine( |
| 31 | + winston.format((info) => { |
| 32 | + info.level = info.level.toUpperCase(); |
| 33 | + return info; |
| 34 | + })(), |
| 35 | + winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), |
| 36 | + winston.format.colorize({ level: true }), |
| 37 | + winston.format.printf(({ timestamp, level, message, ...meta }) => { |
| 38 | + return `[${timestamp}] ${level}: ${inspectObj(message)}${ |
| 39 | + Object.keys(meta).length ? '\n' + inspectObj(meta) : '' |
| 40 | + }`; |
| 41 | + }) |
| 42 | + ), |
| 43 | + transports: [new winston.transports.Console()], |
| 44 | + silent: NODE_ENV === 'test', |
| 45 | + level: 'info', |
| 46 | +}); |
| 47 | + |
| 48 | +if (!CI) { |
| 49 | + logger.add( |
| 50 | + new winston.transports.File({ |
| 51 | + tailable: true, |
| 52 | + filename: 'logs/app.log', |
| 53 | + format: winston.format.json(), |
| 54 | + maxsize: 1024 * 1024 * 5, // 5MB |
| 55 | + maxFiles: 3, |
| 56 | + }) |
| 57 | + ); |
| 58 | +} |
| 59 | + |
| 60 | +export default logger; |
0 commit comments