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