build: switch to NodeNext module resolution
[e-mobility-charging-stations-simulator.git] / src / utils / Logger.ts
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 { Configuration } from './Configuration.js';
7 import { insertAt } from './Utils.js';
8 import { ConfigurationSection, type LogConfiguration } from '../types/index.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 logConfiguration.errorFile!,
21 '-%DATE%',
22 logConfiguration.errorFile!.indexOf('.log'),
23 ),
24 level: 'error',
25 ...(logMaxFiles && { maxFiles: logMaxFiles }),
26 ...(logMaxSize && { maxSize: logMaxSize }),
27 }),
28 new DailyRotateFile({
29 filename: insertAt(logConfiguration.file!, '-%DATE%', logConfiguration.file!.indexOf('.log')),
30 ...(logMaxFiles && { maxFiles: logMaxFiles }),
31 ...(logMaxSize && { maxSize: logMaxSize }),
32 }),
33 ];
34 } else {
35 transports = [
36 new TransportType.File({
37 filename: logConfiguration.errorFile,
38 level: 'error',
39 }),
40 new TransportType.File({
41 filename: logConfiguration.file,
42 }),
43 ];
44 }
45
46 export const logger = createLogger({
47 silent: !logConfiguration.enabled,
48 level: logConfiguration.level,
49 format: format.combine(
50 format.splat(),
51 (format[logConfiguration.format! as keyof FormatWrap] as FormatWrap)(),
52 ),
53 transports,
54 });
55
56 //
57 // If enabled, log to the `console` with the format:
58 // `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
59 //
60 if (logConfiguration.console) {
61 logger.add(
62 new TransportType.Console({
63 format: format.combine(
64 format.splat(),
65 (format[logConfiguration.format! as keyof FormatWrap] as FormatWrap)(),
66 ),
67 }),
68 );
69 }