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'
7 const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
9 // Create the directory if it does not exist
10 mkdirp.sync(CONFIG.STORAGE.LOG_DIR)
12 // Use object for better performances (~ O(1))
13 const excludedKeys = {
20 function keysExcluder (key, value) {
21 if (excludedKeys[key] === true) return undefined
23 if (key === 'err') return value.stack
28 const consoleLoggerFormat = winston.format.printf(info => {
29 let additionalInfos = JSON.stringify(info, keysExcluder, 2)
30 if (additionalInfos === '{}') additionalInfos = ''
31 else additionalInfos = ' ' + additionalInfos
33 if (info.message && info.message.stack !== undefined) info.message = info.message.stack
34 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
37 const jsonLoggerFormat = winston.format.printf(infoArg => {
38 let info = infoArg.err
39 ? Object.assign({}, infoArg, { err: infoArg.err.stack })
42 if (infoArg.message && infoArg.message.stack !== undefined) {
43 info = Object.assign({}, info, { message: infoArg.message.stack })
46 return JSON.stringify(info)
49 const timestampFormatter = winston.format.timestamp({
50 format: 'YYYY-MM-DD HH:mm:ss.SSS'
52 const labelFormatter = winston.format.label({
56 const logger = new winston.createLogger({
57 level: CONFIG.LOG.LEVEL,
59 new winston.transports.File({
60 filename: path.join(CONFIG.STORAGE.LOG_DIR, 'peertube.log'),
61 handleExceptions: true,
64 format: winston.format.combine(
65 winston.format.timestamp(),
67 winston.format.splat(),
71 new winston.transports.Console({
72 handleExceptions: true,
73 humanReadableUnhandledException: true,
74 format: winston.format.combine(
76 winston.format.splat(),
78 winston.format.colorize(),
86 function bunyanLogFactory (level: string) {
89 let args = [].concat(arguments)
91 if (arguments[ 0 ] instanceof Error) {
92 meta = arguments[ 0 ].toString()
93 args = Array.prototype.slice.call(arguments, 1)
95 } else if (typeof (args[ 0 ]) !== 'string') {
97 args = Array.prototype.slice.call(arguments, 1)
101 logger[ level ].apply(logger, args)
104 const bunyanLogger = {
105 trace: bunyanLogFactory('debug'),
106 debug: bunyanLogFactory('debug'),
107 info: bunyanLogFactory('info'),
108 warn: bunyanLogFactory('warn'),
109 error: bunyanLogFactory('error'),
110 fatal: bunyanLogFactory('error')
113 // ---------------------------------------------------------------------------