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