File size: 1,654 Bytes
f90228b
 
bede2fc
f90228b
bede2fc
 
 
 
 
f90228b
bede2fc
f90228b
 
bede2fc
f90228b
 
 
 
bede2fc
 
 
 
 
 
2b62b0c
bede2fc
 
 
 
 
 
2b62b0c
bede2fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f90228b
 
2b62b0c
bede2fc
f90228b
bede2fc
 
 
 
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import winston from "winston";

const { combine, timestamp, printf, colorize, errors, json } = winston.format;

const isProduction = process.env.NODE_ENV === "production";

const devFormat = printf(({ level, message, timestamp, stack, reqId, ...metadata }) => {
  const prefix = reqId ? `[${reqId}] ` : "";
  let msg = `${timestamp} [${level}]: ${prefix}${message}`;
  if (Object.keys(metadata).length > 0) {
    msg += ` ${JSON.stringify(metadata)}`;
  }
  if (stack) {
    msg += `\n${stack}`;
  }
  return msg;
});

function createTransports() {
  const transports: winston.transport[] = [];

  if (isProduction) {
    transports.push(
      new winston.transports.File({
        filename: "logs/pram-error.log",
        level: "error",
        format: combine(timestamp(), errors({ stack: true }), json()),
        maxsize: 10 * 1024 * 1024,
        maxFiles: 14,
      }),
      new winston.transports.File({
        filename: "logs/pram-combined.log",
        format: combine(timestamp(), errors({ stack: true }), json()),
        maxsize: 10 * 1024 * 1024,
        maxFiles: 7,
      }),
    );
  }

  transports.push(
    new winston.transports.Console({
      format: isProduction
        ? combine(timestamp(), errors({ stack: true }), json())
        : combine(colorize(), timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), errors({ stack: true }), devFormat),
    }),
  );

  return transports;
}

export const logger = winston.createLogger({
  level: process.env.LOG_LEVEL ?? "info",
  defaultMeta: { service: "pram-api" },
  transports: createTransports(),
});

export function withRequestId(reqId: string) {
  return logger.child({ reqId });
}