]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/logger.ts
move from trending routes to alg param
[github/Chocobozzz/PeerTube.git] / server / helpers / logger.ts
1 // Thanks http://tostring.it/2014/06/23/advanced-logging-with-nodejs/
2 import { mkdirpSync } from 'fs-extra'
3 import { omit } from 'lodash'
4 import * as path from 'path'
5 import { format as sqlFormat } from 'sql-formatter'
6 import * as winston from 'winston'
7 import { FileTransportOptions } from 'winston/lib/winston/transports'
8 import { CONFIG } from '../initializers/config'
9 import { LOG_FILENAME } from '../initializers/constants'
10
11 const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
12
13 // Create the directory if it does not exist
14 // FIXME: use async
15 mkdirpSync(CONFIG.STORAGE.LOG_DIR)
16
17 function getLoggerReplacer () {
18 const seen = new WeakSet()
19
20 // Thanks: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#Examples
21 return (key: string, value: any) => {
22 if (key === 'cert') return 'Replaced by the logger to avoid large log message'
23
24 if (typeof value === 'object' && value !== null) {
25 if (seen.has(value)) return
26
27 seen.add(value)
28 }
29
30 if (value instanceof Error) {
31 const error = {}
32
33 Object.getOwnPropertyNames(value).forEach(key => { error[key] = value[key] })
34
35 return error
36 }
37
38 return value
39 }
40 }
41
42 const consoleLoggerFormat = winston.format.printf(info => {
43 const toOmit = [ 'label', 'timestamp', 'level', 'message', 'sql' ]
44
45 const obj = omit(info, ...toOmit)
46
47 let additionalInfos = JSON.stringify(obj, getLoggerReplacer(), 2)
48
49 if (additionalInfos === undefined || additionalInfos === '{}') additionalInfos = ''
50 else additionalInfos = ' ' + additionalInfos
51
52 if (info.sql) {
53 if (CONFIG.LOG.PRETTIFY_SQL) {
54 additionalInfos += '\n' + sqlFormat(info.sql, {
55 language: 'sql',
56 ident: ' '
57 })
58 } else {
59 additionalInfos += ' - ' + info.sql
60 }
61 }
62
63 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
64 })
65
66 const jsonLoggerFormat = winston.format.printf(info => {
67 return JSON.stringify(info, getLoggerReplacer())
68 })
69
70 const timestampFormatter = winston.format.timestamp({
71 format: 'YYYY-MM-DD HH:mm:ss.SSS'
72 })
73 const labelFormatter = (suffix?: string) => {
74 return winston.format.label({
75 label: suffix ? `${label} ${suffix}` : label
76 })
77 }
78
79 const fileLoggerOptions: FileTransportOptions = {
80 filename: path.join(CONFIG.STORAGE.LOG_DIR, LOG_FILENAME),
81 handleExceptions: true,
82 format: winston.format.combine(
83 winston.format.timestamp(),
84 jsonLoggerFormat
85 )
86 }
87
88 if (CONFIG.LOG.ROTATION.ENABLED) {
89 fileLoggerOptions.maxsize = CONFIG.LOG.ROTATION.MAX_FILE_SIZE
90 fileLoggerOptions.maxFiles = CONFIG.LOG.ROTATION.MAX_FILES
91 }
92
93 const logger = buildLogger()
94
95 function buildLogger (labelSuffix?: string) {
96 return winston.createLogger({
97 level: CONFIG.LOG.LEVEL,
98 format: winston.format.combine(
99 labelFormatter(labelSuffix),
100 winston.format.splat()
101 ),
102 transports: [
103 new winston.transports.File(fileLoggerOptions),
104 new winston.transports.Console({
105 handleExceptions: true,
106 format: winston.format.combine(
107 timestampFormatter,
108 winston.format.colorize(),
109 consoleLoggerFormat
110 )
111 })
112 ],
113 exitOnError: true
114 })
115 }
116
117 function bunyanLogFactory (level: string) {
118 return function () {
119 let meta = null
120 let args: any[] = []
121 args.concat(arguments)
122
123 if (arguments[0] instanceof Error) {
124 meta = arguments[0].toString()
125 args = Array.prototype.slice.call(arguments, 1)
126 args.push(meta)
127 } else if (typeof (args[0]) !== 'string') {
128 meta = arguments[0]
129 args = Array.prototype.slice.call(arguments, 1)
130 args.push(meta)
131 }
132
133 logger[level].apply(logger, args)
134 }
135 }
136
137 const bunyanLogger = {
138 trace: bunyanLogFactory('debug'),
139 debug: bunyanLogFactory('debug'),
140 info: bunyanLogFactory('info'),
141 warn: bunyanLogFactory('warn'),
142 error: bunyanLogFactory('error'),
143 fatal: bunyanLogFactory('error')
144 }
145 // ---------------------------------------------------------------------------
146
147 export {
148 buildLogger,
149 timestampFormatter,
150 labelFormatter,
151 consoleLoggerFormat,
152 jsonLoggerFormat,
153 logger,
154 bunyanLogger
155 }