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