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