refactor: split Utils static methods class into functions
[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';
7ec46a9a 8
6bf6769e 9let transports: transport[];
3d48c1c1
JB
10if (Configuration.getLog().rotate === true) {
11 const logMaxFiles = Configuration.getLog().maxFiles;
12 const logMaxSize = Configuration.getLog().maxSize;
6bf6769e 13 transports = [
e7aeea18 14 new DailyRotateFile({
9bf0ef23 15 filename: insertAt(
3d48c1c1 16 Configuration.getLog().errorFile,
e7aeea18 17 '-%DATE%',
3d48c1c1 18 Configuration.getLog().errorFile?.indexOf('.log')
e7aeea18
JB
19 ),
20 level: 'error',
9988696d
JB
21 ...(logMaxFiles && { maxFiles: logMaxFiles }),
22 ...(logMaxSize && { maxSize: logMaxSize }),
e7aeea18
JB
23 }),
24 new DailyRotateFile({
9bf0ef23 25 filename: insertAt(
3d48c1c1 26 Configuration.getLog().file,
e7aeea18 27 '-%DATE%',
3d48c1c1 28 Configuration.getLog().file?.indexOf('.log')
e7aeea18 29 ),
9988696d
JB
30 ...(logMaxFiles && { maxFiles: logMaxFiles }),
31 ...(logMaxSize && { maxSize: logMaxSize }),
e7aeea18 32 }),
6bf6769e
JB
33 ];
34} else {
35 transports = [
3d48c1c1
JB
36 new TransportType.File({ filename: Configuration.getLog().errorFile, level: 'error' }),
37 new TransportType.File({ filename: Configuration.getLog().file }),
6bf6769e
JB
38 ];
39}
7dde0b73 40
ae389044 41export const logger = createLogger({
3d48c1c1
JB
42 silent: !Configuration.getLog().enabled,
43 level: Configuration.getLog().level,
44 format: format.combine(format.splat(), (format[Configuration.getLog().format] as FormatWrap)()),
17e9e8ce 45 transports,
9f2e3130 46});
7dde0b73
JB
47
48//
49// If enabled, log to the `console` with the format:
50// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
51//
3d48c1c1 52if (Configuration.getLog().console) {
e7aeea18 53 logger.add(
0d8140bd 54 new TransportType.Console({
c0f4be74
JB
55 format: format.combine(
56 format.splat(),
3d48c1c1 57 (format[Configuration.getLog().format] as FormatWrap)()
c0f4be74 58 ),
e7aeea18
JB
59 })
60 );
7dde0b73 61}