7d1d72f29d8b1d1fae4b858304777ecf1b11a152
[oweals/peertube.git] / server / helpers / logger.ts
1 // Thanks http://tostring.it/2014/06/23/advanced-logging-with-nodejs/
2 import * as mkdirp from 'mkdirp'
3 import * as path from 'path'
4 import * as winston from 'winston'
5 import { CONFIG } from '../initializers'
6
7 const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
8
9 // Create the directory if it does not exist
10 mkdirp.sync(CONFIG.STORAGE.LOG_DIR)
11
12 // Use object for better performances (~ O(1))
13 const excludedKeys = {
14   level: true,
15   message: true,
16   splat: true,
17   timestamp: true,
18   label: true
19 }
20 function keysExcluder (key, value) {
21   return excludedKeys[key] === true ? undefined : value
22 }
23
24 const consoleLoggerFormat = winston.format.printf(info => {
25   let additionalInfos = JSON.stringify(info, keysExcluder, 2)
26   if (additionalInfos === '{}') additionalInfos = ''
27   else additionalInfos = ' ' + additionalInfos
28
29   if (info.message && info.message.stack !== undefined) info.message = info.message.stack
30   return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
31 })
32
33 const jsonLoggerFormat = winston.format.printf(info => {
34   if (info.message && info.message.stack !== undefined) info.message = info.message.stack
35
36   return JSON.stringify(info)
37 })
38
39 const timestampFormatter = winston.format.timestamp({
40   format: 'YYYY-MM-dd HH:mm:ss.SSS'
41 })
42 const labelFormatter = winston.format.label({
43   label
44 })
45
46 const logger = new winston.createLogger({
47   level: CONFIG.LOG.LEVEL,
48   transports: [
49     new winston.transports.File({
50       filename: path.join(CONFIG.STORAGE.LOG_DIR, 'peertube.log'),
51       handleExceptions: true,
52       maxsize: 5242880,
53       maxFiles: 5,
54       format: winston.format.combine(
55         timestampFormatter,
56         labelFormatter,
57         winston.format.splat(),
58         jsonLoggerFormat
59       )
60     }),
61     new winston.transports.Console({
62       handleExcegiptions: true,
63       humanReadableUnhandledException: true,
64       format: winston.format.combine(
65         timestampFormatter,
66         winston.format.splat(),
67         labelFormatter,
68         winston.format.colorize(),
69         consoleLoggerFormat
70       )
71     })
72   ],
73   exitOnError: true
74 })
75
76 // ---------------------------------------------------------------------------
77
78 export {
79   timestampFormatter,
80   labelFormatter,
81   consoleLoggerFormat,
82   logger
83 }