]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/logger.ts
Disable sql prettifier by default
[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' ]
44 if (CONFIG.LOG.PRETTIFY_SQL) toOmit.push('sql')
45
46 const obj = omit(info, ...toOmit)
47
48 let additionalInfos = JSON.stringify(obj, getLoggerReplacer(), 2)
49
50 if (additionalInfos === undefined || additionalInfos === '{}') additionalInfos = ''
51 else additionalInfos = ' ' + additionalInfos
52
53 if (CONFIG.LOG.PRETTIFY_SQL && info.sql) {
54 additionalInfos += '\n' + sqlFormat(info.sql, {
55 language: 'sql',
56 ident: ' '
57 })
58 }
59
60 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
61 })
62
63 const jsonLoggerFormat = winston.format.printf(info => {
64 return JSON.stringify(info, getLoggerReplacer())
65 })
66
67 const timestampFormatter = winston.format.timestamp({
68 format: 'YYYY-MM-DD HH:mm:ss.SSS'
69 })
70 const labelFormatter = (suffix?: string) => {
71 return winston.format.label({
72 label: suffix ? `${label} ${suffix}` : label
73 })
74 }
75
76 const fileLoggerOptions: FileTransportOptions = {
77 filename: path.join(CONFIG.STORAGE.LOG_DIR, LOG_FILENAME),
78 handleExceptions: true,
79 format: winston.format.combine(
80 winston.format.timestamp(),
81 jsonLoggerFormat
82 )
83 }
84
85 if (CONFIG.LOG.ROTATION.ENABLED) {
86 fileLoggerOptions.maxsize = CONFIG.LOG.ROTATION.MAX_FILE_SIZE
87 fileLoggerOptions.maxFiles = CONFIG.LOG.ROTATION.MAX_FILES
88 }
89
90 const logger = buildLogger()
91
92 function buildLogger (labelSuffix?: string) {
93 return winston.createLogger({
94 level: CONFIG.LOG.LEVEL,
95 format: winston.format.combine(
96 labelFormatter(labelSuffix),
97 winston.format.splat()
98 ),
99 transports: [
100 new winston.transports.File(fileLoggerOptions),
101 new winston.transports.Console({
102 handleExceptions: true,
103 format: winston.format.combine(
104 timestampFormatter,
105 winston.format.colorize(),
106 consoleLoggerFormat
107 )
108 })
109 ],
110 exitOnError: true
111 })
112 }
113
114 function bunyanLogFactory (level: string) {
115 return function () {
116 let meta = null
117 let args: any[] = []
118 args.concat(arguments)
119
120 if (arguments[0] instanceof Error) {
121 meta = arguments[0].toString()
122 args = Array.prototype.slice.call(arguments, 1)
123 args.push(meta)
124 } else if (typeof (args[0]) !== 'string') {
125 meta = arguments[0]
126 args = Array.prototype.slice.call(arguments, 1)
127 args.push(meta)
128 }
129
130 logger[level].apply(logger, args)
131 }
132 }
133
134 const bunyanLogger = {
135 trace: bunyanLogFactory('debug'),
136 debug: bunyanLogFactory('debug'),
137 info: bunyanLogFactory('info'),
138 warn: bunyanLogFactory('warn'),
139 error: bunyanLogFactory('error'),
140 fatal: bunyanLogFactory('error')
141 }
142 // ---------------------------------------------------------------------------
143
144 export {
145 buildLogger,
146 timestampFormatter,
147 labelFormatter,
148 consoleLoggerFormat,
149 jsonLoggerFormat,
150 logger,
151 bunyanLogger
152 }