refactor: cleanup configuration class usage
[e-mobility-charging-stations-simulator.git] / src / utils / Logger.ts
CommitLineData
63ec69b7 1import type { FormatWrap } from 'logform';
ae389044 2import { createLogger, format, type transport } from 'winston';
b768993d 3import TransportType from 'winston/lib/winston/transports/index.js';
78202038 4import DailyRotateFile from 'winston-daily-rotate-file';
8114d10e 5
878e026c 6import { Configuration } from './Configuration';
9bf0ef23 7import { insertAt } from './Utils';
5d049829 8import { ConfigurationSection, type LogConfiguration } from '../types';
7ec46a9a 9
864e5f8d
JB
10const logConfiguration = Configuration.getConfigurationSection<LogConfiguration>(
11 ConfigurationSection.log,
12);
6bf6769e 13let transports: transport[];
864e5f8d
JB
14if (logConfiguration.rotate === true) {
15 const logMaxFiles = logConfiguration.maxFiles;
16 const logMaxSize = logConfiguration.maxSize;
6bf6769e 17 transports = [
e7aeea18 18 new DailyRotateFile({
9bf0ef23 19 filename: insertAt(
864e5f8d 20 logConfiguration.errorFile!,
e7aeea18 21 '-%DATE%',
864e5f8d 22 logConfiguration.errorFile!.indexOf('.log'),
e7aeea18
JB
23 ),
24 level: 'error',
9988696d
JB
25 ...(logMaxFiles && { maxFiles: logMaxFiles }),
26 ...(logMaxSize && { maxSize: logMaxSize }),
e7aeea18
JB
27 }),
28 new DailyRotateFile({
864e5f8d 29 filename: insertAt(logConfiguration.file!, '-%DATE%', logConfiguration.file!.indexOf('.log')),
9988696d
JB
30 ...(logMaxFiles && { maxFiles: logMaxFiles }),
31 ...(logMaxSize && { maxSize: logMaxSize }),
e7aeea18 32 }),
6bf6769e
JB
33 ];
34} else {
35 transports = [
5d049829 36 new TransportType.File({
864e5f8d 37 filename: logConfiguration.errorFile,
5d049829
JB
38 level: 'error',
39 }),
40 new TransportType.File({
864e5f8d 41 filename: logConfiguration.file,
5d049829 42 }),
6bf6769e
JB
43 ];
44}
7dde0b73 45
ae389044 46export const logger = createLogger({
864e5f8d
JB
47 silent: !logConfiguration.enabled,
48 level: logConfiguration.level,
49 format: format.combine(format.splat(), (format[logConfiguration.format!] as FormatWrap)()),
17e9e8ce 50 transports,
9f2e3130 51});
7dde0b73
JB
52
53//
54// If enabled, log to the `console` with the format:
55// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
56//
864e5f8d 57if (logConfiguration.console) {
e7aeea18 58 logger.add(
0d8140bd 59 new TransportType.Console({
864e5f8d 60 format: format.combine(format.splat(), (format[logConfiguration.format!] as FormatWrap)()),
5edd8ba0 61 }),
e7aeea18 62 );
7dde0b73 63}