| 1 | import type { FormatWrap } from 'logform' |
| 2 | import { createLogger, format, type transport } from 'winston' |
| 3 | import TransportType from 'winston/lib/winston/transports/index.js' |
| 4 | import DailyRotateFile from 'winston-daily-rotate-file' |
| 5 | |
| 6 | import { ConfigurationSection, type LogConfiguration } from '../types/index.js' |
| 7 | import { Configuration } from './Configuration.js' |
| 8 | import { insertAt } from './Utils.js' |
| 9 | |
| 10 | const logConfiguration = Configuration.getConfigurationSection<LogConfiguration>( |
| 11 | ConfigurationSection.log |
| 12 | ) |
| 13 | let transports: transport[] |
| 14 | if (logConfiguration.rotate === true) { |
| 15 | const logMaxFiles = logConfiguration.maxFiles |
| 16 | const logMaxSize = logConfiguration.maxSize |
| 17 | transports = [ |
| 18 | new DailyRotateFile({ |
| 19 | filename: insertAt( |
| 20 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 21 | logConfiguration.errorFile!, |
| 22 | '-%DATE%', |
| 23 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 24 | logConfiguration.errorFile!.indexOf('.log') |
| 25 | ), |
| 26 | level: 'error', |
| 27 | ...(logMaxFiles != null && { maxFiles: logMaxFiles }), |
| 28 | ...(logMaxSize != null && { maxSize: logMaxSize }) |
| 29 | }), |
| 30 | new DailyRotateFile({ |
| 31 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 32 | filename: insertAt(logConfiguration.file!, '-%DATE%', logConfiguration.file!.indexOf('.log')), |
| 33 | ...(logMaxFiles != null && { maxFiles: logMaxFiles }), |
| 34 | ...(logMaxSize != null && { maxSize: logMaxSize }) |
| 35 | }) |
| 36 | ] |
| 37 | } else { |
| 38 | transports = [ |
| 39 | new TransportType.File({ |
| 40 | filename: logConfiguration.errorFile, |
| 41 | level: 'error' |
| 42 | }), |
| 43 | new TransportType.File({ |
| 44 | filename: logConfiguration.file |
| 45 | }) |
| 46 | ] |
| 47 | } |
| 48 | |
| 49 | export const logger = createLogger({ |
| 50 | silent: logConfiguration.enabled === false, |
| 51 | level: logConfiguration.level, |
| 52 | format: format.combine( |
| 53 | format.splat(), |
| 54 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 55 | (format[logConfiguration.format! as keyof FormatWrap] as FormatWrap)() |
| 56 | ), |
| 57 | transports |
| 58 | }) |
| 59 | |
| 60 | // |
| 61 | // If enabled, log to the `console` with the format: |
| 62 | // `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` |
| 63 | // |
| 64 | if (logConfiguration.console === true) { |
| 65 | logger.add( |
| 66 | new TransportType.Console({ |
| 67 | format: format.combine( |
| 68 | format.splat(), |
| 69 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 70 | (format[logConfiguration.format! as keyof FormatWrap] as FormatWrap)() |
| 71 | ) |
| 72 | }) |
| 73 | ) |
| 74 | } |