]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/logger.ts
Merge remote-tracking branch 'weblate/develop' into develop
[github/Chocobozzz/PeerTube.git] / server / helpers / logger.ts
CommitLineData
b9fbc176 1import { stat } from 'fs-extra'
41fb13c3 2import { join } from 'path'
2a6cf69c 3import { format as sqlFormat } from 'sql-formatter'
41fb13c3 4import { createLogger, format, transports } from 'winston'
fcf4569f 5import { FileTransportOptions } from 'winston/lib/winston/transports'
630d0a1b
C
6import { context } from '@opentelemetry/api'
7import { getSpanContext } from '@opentelemetry/api/build/src/trace/context-utils'
bbd5aa7e 8import { omit } from '@shared/core-utils'
6dd9de95 9import { CONFIG } from '../initializers/config'
837666fe 10import { LOG_FILENAME } from '../initializers/constants'
8c308c2b 11
65fcc311 12const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
320d6275 13
41fb13c3 14const consoleLoggerFormat = format.printf(info => {
630d0a1b 15 let additionalInfos = JSON.stringify(getAdditionalInfo(info), removeCyclicValues(), 2)
fd8710b8 16
e20015d7 17 if (additionalInfos === undefined || additionalInfos === '{}') additionalInfos = ''
2af4fa4d 18 else additionalInfos = ' ' + additionalInfos
23e27dd5 19
d223dca0
C
20 if (info.sql) {
21 if (CONFIG.LOG.PRETTIFY_SQL) {
22 additionalInfos += '\n' + sqlFormat(info.sql, {
23 language: 'sql',
a91e9beb 24 tabWidth: 2
d223dca0
C
25 })
26 } else {
27 additionalInfos += ' - ' + info.sql
28 }
2a6cf69c
RK
29 }
30
2af4fa4d 31 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
23e27dd5
C
32})
33
41fb13c3 34const jsonLoggerFormat = format.printf(info => {
630d0a1b 35 return JSON.stringify(info, removeCyclicValues())
276d03ed
C
36})
37
41fb13c3 38const timestampFormatter = format.timestamp({
0647f472 39 format: 'YYYY-MM-DD HH:mm:ss.SSS'
23e27dd5 40})
bc0d801b 41const labelFormatter = (suffix?: string) => {
41fb13c3 42 return format.label({
bc0d801b
C
43 label: suffix ? `${label} ${suffix}` : label
44 })
45}
23e27dd5 46
fcf4569f 47const fileLoggerOptions: FileTransportOptions = {
41fb13c3 48 filename: join(CONFIG.STORAGE.LOG_DIR, LOG_FILENAME),
fcf4569f 49 handleExceptions: true,
41fb13c3
C
50 format: format.combine(
51 format.timestamp(),
fcf4569f
NB
52 jsonLoggerFormat
53 )
54}
55
2f6b5e2d
C
56if (CONFIG.LOG.ROTATION.ENABLED) {
57 fileLoggerOptions.maxsize = CONFIG.LOG.ROTATION.MAX_FILE_SIZE
58 fileLoggerOptions.maxFiles = CONFIG.LOG.ROTATION.MAX_FILES
fcf4569f
NB
59}
60
bc0d801b 61function buildLogger (labelSuffix?: string) {
41fb13c3 62 return createLogger({
bc0d801b 63 level: CONFIG.LOG.LEVEL,
630d0a1b
C
64 defaultMeta: {
65 get traceId () { return getSpanContext(context.active())?.traceId },
66 get spanId () { return getSpanContext(context.active())?.spanId },
67 get traceFlags () { return getSpanContext(context.active())?.traceFlags }
68 },
41fb13c3 69 format: format.combine(
bc0d801b 70 labelFormatter(labelSuffix),
41fb13c3 71 format.splat()
bc0d801b
C
72 ),
73 transports: [
41fb13c3
C
74 new transports.File(fileLoggerOptions),
75 new transports.Console({
bc0d801b 76 handleExceptions: true,
41fb13c3 77 format: format.combine(
bc0d801b 78 timestampFormatter,
41fb13c3 79 format.colorize(),
bc0d801b
C
80 consoleLoggerFormat
81 )
82 })
83 ],
84 exitOnError: true
85 })
86}
8c308c2b 87
630d0a1b
C
88const logger = buildLogger()
89
90// ---------------------------------------------------------------------------
91
05e67d62 92function bunyanLogFactory (level: string) {
40a8c0a4 93 return function (...params: any[]) {
05e67d62 94 let meta = null
40a8c0a4 95 let args = [].concat(params)
05e67d62 96
a1587156
C
97 if (arguments[0] instanceof Error) {
98 meta = arguments[0].toString()
05e67d62
C
99 args = Array.prototype.slice.call(arguments, 1)
100 args.push(meta)
a1587156
C
101 } else if (typeof (args[0]) !== 'string') {
102 meta = arguments[0]
05e67d62
C
103 args = Array.prototype.slice.call(arguments, 1)
104 args.push(meta)
105 }
106
a1587156 107 logger[level].apply(logger, args)
05e67d62
C
108 }
109}
a1587156 110
05e67d62 111const bunyanLogger = {
40a8c0a4 112 level: () => { },
05e67d62
C
113 trace: bunyanLogFactory('debug'),
114 debug: bunyanLogFactory('debug'),
630d0a1b 115 verbose: bunyanLogFactory('debug'),
05e67d62
C
116 info: bunyanLogFactory('info'),
117 warn: bunyanLogFactory('warn'),
118 error: bunyanLogFactory('error'),
119 fatal: bunyanLogFactory('error')
120}
452b3bea 121
630d0a1b
C
122// ---------------------------------------------------------------------------
123
46320694
C
124type LoggerTagsFn = (...tags: string[]) => { tags: string[] }
125function loggerTagsFactory (...defaultTags: string[]): LoggerTagsFn {
452b3bea
C
126 return (...tags: string[]) => {
127 return { tags: defaultTags.concat(tags) }
128 }
129}
130
630d0a1b
C
131// ---------------------------------------------------------------------------
132
15a7eafb
C
133async function mtimeSortFilesDesc (files: string[], basePath: string) {
134 const promises = []
135 const out: { file: string, mtime: number }[] = []
136
137 for (const file of files) {
138 const p = stat(basePath + '/' + file)
139 .then(stats => {
140 if (stats.isFile()) out.push({ file, mtime: stats.mtime.getTime() })
141 })
142
143 promises.push(p)
144 }
145
146 await Promise.all(promises)
147
148 out.sort((a, b) => b.mtime - a.mtime)
149
150 return out
151}
152
9f10b292 153// ---------------------------------------------------------------------------
c45f7f84 154
23e27dd5 155export {
46320694
C
156 LoggerTagsFn,
157
bc0d801b 158 buildLogger,
23e27dd5
C
159 timestampFormatter,
160 labelFormatter,
276d03ed 161 consoleLoggerFormat,
59390818 162 jsonLoggerFormat,
15a7eafb 163 mtimeSortFilesDesc,
05e67d62 164 logger,
452b3bea 165 loggerTagsFactory,
05e67d62 166 bunyanLogger
23e27dd5 167}
630d0a1b
C
168
169// ---------------------------------------------------------------------------
170
171function removeCyclicValues () {
172 const seen = new WeakSet()
173
174 // Thanks: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#Examples
175 return (key: string, value: any) => {
176 if (key === 'cert') return 'Replaced by the logger to avoid large log message'
177
178 if (typeof value === 'object' && value !== null) {
179 if (seen.has(value)) return
180
181 seen.add(value)
182 }
183
184 if (value instanceof Set) {
185 return Array.from(value)
186 }
187
188 if (value instanceof Map) {
189 return Array.from(value.entries())
190 }
191
192 if (value instanceof Error) {
193 const error = {}
194
195 Object.getOwnPropertyNames(value).forEach(key => { error[key] = value[key] })
196
197 return error
198 }
199
200 return value
201 }
202}
203
204function getAdditionalInfo (info: any) {
205 const toOmit = [ 'label', 'timestamp', 'level', 'message', 'sql', 'tags' ]
206
bbd5aa7e 207 return omit(info, toOmit)
630d0a1b 208}