logger.ts86 lines, 2.0 KB
| 1 | import winston from "winston"; |
| 2 | import path from "path"; |
| 3 | import fs from "fs"; |
| 4 | |
| 5 | // Define log levels |
| 6 | const levels = { |
| 7 | error: 0, |
| 8 | warn: 1, |
| 9 | info: 2, |
| 10 | http: 3, |
| 11 | debug: 4, |
| 12 | }; |
| 13 | |
| 14 | // Define colors for each level |
| 15 | const colors = { |
| 16 | error: "red", |
| 17 | warn: "yellow", |
| 18 | info: "green", |
| 19 | http: "magenta", |
| 20 | debug: "blue", |
| 21 | }; |
| 22 | |
| 23 | // tell winston that we want to link our colors |
| 24 | winston.addColors(colors); |
| 25 | |
| 26 | // Create format for console output |
| 27 | const consoleFormat = winston.format.combine( |
| 28 | winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }), |
| 29 | winston.format.colorize({ all: true }), |
| 30 | winston.format.printf( |
| 31 | (info) => `${info.timestamp} ${info.level}: ${info.message}` |
| 32 | ) |
| 33 | ); |
| 34 | |
| 35 | // Create format for file output (JSON) |
| 36 | const fileFormat = winston.format.combine( |
| 37 | winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }), |
| 38 | winston.format.json() |
| 39 | ); |
| 40 | |
| 41 | // Determine log level based on environment |
| 42 | const level = () => { |
| 43 | const env = process.env.NODE_ENV || "development"; |
| 44 | return env === "development" ? "debug" : "info"; |
| 45 | }; |
| 46 | |
| 47 | // Define log directory and files |
| 48 | const logDir = "logs"; |
| 49 | const errorLog = path.join(logDir, "error.log"); |
| 50 | const combinedLog = path.join(logDir, "combined.log"); |
| 51 | |
| 52 | // Create logs directory if it doesn't exist |
| 53 | if (!fs.existsSync(logDir)) { |
| 54 | fs.mkdirSync(logDir, { recursive: true }); |
| 55 | } |
| 56 | |
| 57 | // Create the logger instance |
| 58 | const logger = winston.createLogger({ |
| 59 | level: level(), |
| 60 | levels, |
| 61 | format: fileFormat, |
| 62 | transports: [ |
| 63 | // Write all logs with level 'error' to error.log |
| 64 | new winston.transports.File({ filename: errorLog, level: "error" }), |
| 65 | // Write all logs to combined.log |
| 66 | new winston.transports.File({ filename: combinedLog }), |
| 67 | ], |
| 68 | }); |
| 69 | |
| 70 | // If we're not in production, log to the console |
| 71 | if (process.env.NODE_ENV !== "production") { |
| 72 | logger.add( |
| 73 | new winston.transports.Console({ |
| 74 | format: consoleFormat, |
| 75 | }) |
| 76 | ); |
| 77 | } |
| 78 | |
| 79 | // Create a stream object for morgan middleware |
| 80 | export const stream = { |
| 81 | write: (message: string) => { |
| 82 | logger.http(message.trim()); |
| 83 | }, |
| 84 | }; |
| 85 | |
| 86 | export default logger; |