1 import { stat } from 'fs-extra'
2 import { join } from 'path'
3 import { format as sqlFormat } from 'sql-formatter'
4 import { createLogger, format, transports } from 'winston'
5 import { FileTransportOptions } from 'winston/lib/winston/transports'
6 import { context } from '@opentelemetry/api'
7 import { getSpanContext } from '@opentelemetry/api/build/src/trace/context-utils'
8 import { omit } from '@shared/core-utils'
9 import { CONFIG } from '../initializers/config'
10 import { LOG_FILENAME } from '../initializers/constants'
12 const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
14 const consoleLoggerFormat = format.printf(info => {
15 let additionalInfos = JSON.stringify(getAdditionalInfo(info), removeCyclicValues(), 2)
17 if (additionalInfos === undefined || additionalInfos === '{}') additionalInfos = ''
18 else additionalInfos = ' ' + additionalInfos
21 if (CONFIG.LOG.PRETTIFY_SQL) {
22 additionalInfos += '\n' + sqlFormat(info.sql, {
27 additionalInfos += ' - ' + info.sql
31 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
34 const jsonLoggerFormat = format.printf(info => {
35 return JSON.stringify(info, removeCyclicValues())
38 const timestampFormatter = format.timestamp({
39 format: 'YYYY-MM-DD HH:mm:ss.SSS'
41 const labelFormatter = (suffix?: string) => {
43 label: suffix ? `${label} ${suffix}` : label
47 const fileLoggerOptions: FileTransportOptions = {
48 filename: join(CONFIG.STORAGE.LOG_DIR, LOG_FILENAME),
49 handleExceptions: true,
50 format: format.combine(
56 if (CONFIG.LOG.ROTATION.ENABLED) {
57 fileLoggerOptions.maxsize = CONFIG.LOG.ROTATION.MAX_FILE_SIZE
58 fileLoggerOptions.maxFiles = CONFIG.LOG.ROTATION.MAX_FILES
61 function buildLogger (labelSuffix?: string) {
63 level: CONFIG.LOG.LEVEL,
65 get traceId () { return getSpanContext(context.active())?.traceId },
66 get spanId () { return getSpanContext(context.active())?.spanId },
67 get traceFlags () { return getSpanContext(context.active())?.traceFlags }
69 format: format.combine(
70 labelFormatter(labelSuffix),
74 new transports.File(fileLoggerOptions),
75 new transports.Console({
76 handleExceptions: true,
77 format: format.combine(
88 const logger = buildLogger()
90 // ---------------------------------------------------------------------------
92 function bunyanLogFactory (level: string) {
93 return function (...params: any[]) {
95 let args = [].concat(params)
97 if (arguments[0] instanceof Error) {
98 meta = arguments[0].toString()
99 args = Array.prototype.slice.call(arguments, 1)
101 } else if (typeof (args[0]) !== 'string') {
103 args = Array.prototype.slice.call(arguments, 1)
107 logger[level].apply(logger, args)
111 const bunyanLogger = {
113 trace: bunyanLogFactory('debug'),
114 debug: bunyanLogFactory('debug'),
115 verbose: bunyanLogFactory('debug'),
116 info: bunyanLogFactory('info'),
117 warn: bunyanLogFactory('warn'),
118 error: bunyanLogFactory('error'),
119 fatal: bunyanLogFactory('error')
122 // ---------------------------------------------------------------------------
124 type LoggerTagsFn = (...tags: string[]) => { tags: string[] }
125 function loggerTagsFactory (...defaultTags: string[]): LoggerTagsFn {
126 return (...tags: string[]) => {
127 return { tags: defaultTags.concat(tags) }
131 // ---------------------------------------------------------------------------
133 async function mtimeSortFilesDesc (files: string[], basePath: string) {
135 const out: { file: string, mtime: number }[] = []
137 for (const file of files) {
138 const p = stat(basePath + '/' + file)
140 if (stats.isFile()) out.push({ file, mtime: stats.mtime.getTime() })
146 await Promise.all(promises)
148 out.sort((a, b) => b.mtime - a.mtime)
153 // ---------------------------------------------------------------------------
169 // ---------------------------------------------------------------------------
171 function removeCyclicValues () {
172 const seen = new WeakSet()
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'
178 if (typeof value === 'object' && value !== null) {
179 if (seen.has(value)) return
184 if (value instanceof Set) {
185 return Array.from(value)
188 if (value instanceof Map) {
189 return Array.from(value.entries())
192 if (value instanceof Error) {
195 Object.getOwnPropertyNames(value).forEach(key => { error[key] = value[key] })
204 function getAdditionalInfo (info: any) {
205 const toOmit = [ 'label', 'timestamp', 'level', 'message', 'sql', 'tags' ]
207 return omit(info, toOmit)