6a02f680abbb4437276b046b1d877be6a0bc9c96
[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 loggerFormat = winston.format.printf((info) => {
25   let additionalInfos = JSON.stringify(info, keysExcluder, 2)
26   if (additionalInfos === '{}') additionalInfos = ''
27
28   return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message} ${additionalInfos}`
29 })
30
31 const timestampFormatter = winston.format.timestamp({
32   format: 'YYYY-MM-dd HH:mm:ss.SSS'
33 })
34 const labelFormatter = winston.format.label({
35   label
36 })
37
38 const logger = new winston.createLogger({
39   level: CONFIG.LOG.LEVEL,
40   transports: [
41     new winston.transports.File({
42       filename: path.join(CONFIG.STORAGE.LOG_DIR, 'peertube.log'),
43       handleExceptions: true,
44       maxsize: 5242880,
45       maxFiles: 5,
46       format: winston.format.combine(
47         timestampFormatter,
48         labelFormatter,
49         winston.format.splat(),
50         winston.format.json()
51       )
52     }),
53     new winston.transports.Console({
54       handleExceptions: true,
55       humanReadableUnhandledException: true,
56       format: winston.format.combine(
57         timestampFormatter,
58         winston.format.splat(),
59         labelFormatter,
60         winston.format.colorize(),
61         loggerFormat
62       )
63     })
64   ],
65   exitOnError: true
66 })
67
68 // ---------------------------------------------------------------------------
69
70 export {
71   timestampFormatter,
72   labelFormatter,
73   loggerFormat,
74   logger
75 }