1 // Thanks http://tostring.it/2014/06/23/advanced-logging-with-nodejs/
2 import { mkdirpSync } from 'fs-extra'
3 import * as path from 'path'
4 import * as winston from 'winston'
5 import { FileTransportOptions } from 'winston/lib/winston/transports'
6 import { CONFIG } from '../initializers/config'
7 import { omit } from 'lodash'
9 const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
11 // Create the directory if it does not exist
13 mkdirpSync(CONFIG.STORAGE.LOG_DIR)
15 function getLoggerReplacer () {
16 const seen = new WeakSet()
18 // Thanks: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#Examples
19 return (key: string, value: any) => {
20 if (typeof value === 'object' && value !== null) {
21 if (seen.has(value)) return
26 if (value instanceof Error) {
29 Object.getOwnPropertyNames(value).forEach(key => error[ key ] = value[ key ])
38 const consoleLoggerFormat = winston.format.printf(info => {
39 const obj = omit(info, 'label', 'timestamp', 'level', 'message')
41 let additionalInfos = JSON.stringify(obj, getLoggerReplacer(), 2)
43 if (additionalInfos === undefined || additionalInfos === '{}') additionalInfos = ''
44 else additionalInfos = ' ' + additionalInfos
46 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
49 const jsonLoggerFormat = winston.format.printf(info => {
50 return JSON.stringify(info, getLoggerReplacer())
53 const timestampFormatter = winston.format.timestamp({
54 format: 'YYYY-MM-DD HH:mm:ss.SSS'
56 const labelFormatter = winston.format.label({
60 const fileLoggerOptions: FileTransportOptions = {
61 filename: path.join(CONFIG.STORAGE.LOG_DIR, 'peertube.log'),
62 handleExceptions: true,
63 format: winston.format.combine(
64 winston.format.timestamp(),
69 if (CONFIG.LOG.ROTATION) {
70 fileLoggerOptions.maxsize = 1024 * 1024 * 12
71 fileLoggerOptions.maxFiles = 20
74 const logger = winston.createLogger({
75 level: CONFIG.LOG.LEVEL,
76 format: winston.format.combine(
78 winston.format.splat()
81 new winston.transports.File(fileLoggerOptions),
82 new winston.transports.Console({
83 handleExceptions: true,
84 format: winston.format.combine(
86 winston.format.colorize(),
94 function bunyanLogFactory (level: string) {
98 args.concat(arguments)
100 if (arguments[ 0 ] instanceof Error) {
101 meta = arguments[ 0 ].toString()
102 args = Array.prototype.slice.call(arguments, 1)
104 } else if (typeof (args[ 0 ]) !== 'string') {
105 meta = arguments[ 0 ]
106 args = Array.prototype.slice.call(arguments, 1)
110 logger[ level ].apply(logger, args)
113 const bunyanLogger = {
114 trace: bunyanLogFactory('debug'),
115 debug: bunyanLogFactory('debug'),
116 info: bunyanLogFactory('info'),
117 warn: bunyanLogFactory('warn'),
118 error: bunyanLogFactory('error'),
119 fatal: bunyanLogFactory('error')
121 // ---------------------------------------------------------------------------