File size: 1,376 Bytes
c01955c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import winston from 'winston';
import { LOGGER_FOLDER_NAME, LOGGER_FILE_NAME } from "../constants/constants.js";
import fs from "fs";
import path from "path";

// Ensure log directory exists synchronously
if (!fs.existsSync(LOGGER_FOLDER_NAME)) {
    fs.mkdirSync(LOGGER_FOLDER_NAME, { recursive: true });
    console.log('Log folder created!');
}

const logPath = path.join(LOGGER_FOLDER_NAME, LOGGER_FILE_NAME);

const logFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  winston.format.errors({ stack: true }),
  winston.format.json()
);

export const logger = winston.createLogger({
  level: 'info',
  format: logFormat,
  defaultMeta: { service: 'user-service' },
  transports: [
    new winston.transports.File({ filename: logPath }),
  ],
});

//
// If we're not in production then log to the `console` with custom format:
//
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.combine(
      winston.format.colorize(),
      winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
      winston.format.printf(({ timestamp, level, message, stack, ...meta }) => {
        return `${timestamp} [${level}]: ${message} ${stack ? `\n${stack}` : ''} ${Object.keys(meta).length ? JSON.stringify(meta) : ''}`;
      })
    ),
  }));
}

export default logger;