| 1 | import type { FormatWrap } from 'logform'; |
| 2 | import { type Logger, createLogger, format, type transport } from 'winston'; |
| 3 | import TransportType from 'winston/lib/winston/transports'; |
| 4 | import DailyRotateFile from 'winston-daily-rotate-file'; |
| 5 | |
| 6 | import { Configuration, Utils } from './internal'; |
| 7 | |
| 8 | let transports: transport[]; |
| 9 | if (Configuration.getLogRotate() === true) { |
| 10 | const logMaxFiles = Configuration.getLogMaxFiles(); |
| 11 | const logMaxSize = Configuration.getLogMaxSize(); |
| 12 | transports = [ |
| 13 | new DailyRotateFile({ |
| 14 | filename: Utils.insertAt( |
| 15 | Configuration.getLogErrorFile(), |
| 16 | '-%DATE%', |
| 17 | Configuration.getLogErrorFile()?.indexOf('.log') |
| 18 | ), |
| 19 | level: 'error', |
| 20 | ...(logMaxFiles && { maxFiles: logMaxFiles }), |
| 21 | ...(logMaxSize && { maxSize: logMaxSize }), |
| 22 | }), |
| 23 | new DailyRotateFile({ |
| 24 | filename: Utils.insertAt( |
| 25 | Configuration.getLogFile(), |
| 26 | '-%DATE%', |
| 27 | Configuration.getLogFile()?.indexOf('.log') |
| 28 | ), |
| 29 | ...(logMaxFiles && { maxFiles: logMaxFiles }), |
| 30 | ...(logMaxSize && { maxSize: logMaxSize }), |
| 31 | }), |
| 32 | ]; |
| 33 | } else { |
| 34 | transports = [ |
| 35 | new TransportType.File({ filename: Configuration.getLogErrorFile(), level: 'error' }), |
| 36 | new TransportType.File({ filename: Configuration.getLogFile() }), |
| 37 | ]; |
| 38 | } |
| 39 | |
| 40 | const logger: Logger = createLogger({ |
| 41 | level: Configuration.getLogLevel(), |
| 42 | format: format.combine(format.splat(), (format[Configuration.getLogFormat()] as FormatWrap)()), |
| 43 | transports, |
| 44 | }); |
| 45 | |
| 46 | // |
| 47 | // If enabled, log to the `console` with the format: |
| 48 | // `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` |
| 49 | // |
| 50 | if (Configuration.getLogConsole()) { |
| 51 | logger.add( |
| 52 | new TransportType.Console({ |
| 53 | format: format.combine( |
| 54 | format.splat(), |
| 55 | (format[Configuration.getLogFormat()] as FormatWrap)() |
| 56 | ), |
| 57 | }) |
| 58 | ); |
| 59 | } |
| 60 | |
| 61 | export { logger }; |