1 // Thanks http://tostring.it/2014/06/23/advanced-logging-with-nodejs/
2 import { stat } from 'fs-extra'
3 import { omit } from 'lodash'
4 import { join } from 'path'
5 import { format as sqlFormat } from 'sql-formatter'
6 import { createLogger, format, transports } from 'winston'
7 import { FileTransportOptions } from 'winston/lib/winston/transports'
8 import { CONFIG } from '../initializers/config'
9 import { LOG_FILENAME } from '../initializers/constants'
11 const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
13 function getLoggerReplacer () {
14 const seen = new WeakSet()
16 // Thanks: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#Examples
17 return (key: string, value: any) => {
18 if (key === 'cert') return 'Replaced by the logger to avoid large log message'
20 if (typeof value === 'object' && value !== null) {
21 if (seen.has(value)) return
26 if (value instanceof Set) {
27 return Array.from(value)
30 if (value instanceof Map) {
31 return Array.from(value.entries())
34 if (value instanceof Error) {
37 Object.getOwnPropertyNames(value).forEach(key => { error[key] = value[key] })
46 const consoleLoggerFormat = format.printf(info => {
47 const toOmit = [ 'label', 'timestamp', 'level', 'message', 'sql', 'tags' ]
49 const obj = omit(info, ...toOmit)
51 let additionalInfos = JSON.stringify(obj, getLoggerReplacer(), 2)
53 if (additionalInfos === undefined || additionalInfos === '{}') additionalInfos = ''
54 else additionalInfos = ' ' + additionalInfos
57 if (CONFIG.LOG.PRETTIFY_SQL) {
58 additionalInfos += '\n' + sqlFormat(info.sql, {
63 additionalInfos += ' - ' + info.sql
67 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
70 const jsonLoggerFormat = format.printf(info => {
71 return JSON.stringify(info, getLoggerReplacer())
74 const timestampFormatter = format.timestamp({
75 format: 'YYYY-MM-DD HH:mm:ss.SSS'
77 const labelFormatter = (suffix?: string) => {
79 label: suffix ? `${label} ${suffix}` : label
83 const fileLoggerOptions: FileTransportOptions = {
84 filename: join(CONFIG.STORAGE.LOG_DIR, LOG_FILENAME),
85 handleExceptions: true,
86 format: format.combine(
92 if (CONFIG.LOG.ROTATION.ENABLED) {
93 fileLoggerOptions.maxsize = CONFIG.LOG.ROTATION.MAX_FILE_SIZE
94 fileLoggerOptions.maxFiles = CONFIG.LOG.ROTATION.MAX_FILES
97 const logger = buildLogger()
99 function buildLogger (labelSuffix?: string) {
100 return createLogger({
101 level: CONFIG.LOG.LEVEL,
102 format: format.combine(
103 labelFormatter(labelSuffix),
107 new transports.File(fileLoggerOptions),
108 new transports.Console({
109 handleExceptions: true,
110 format: format.combine(
121 function bunyanLogFactory (level: string) {
122 return function (...params: any[]) {
124 let args = [].concat(params)
126 if (arguments[0] instanceof Error) {
127 meta = arguments[0].toString()
128 args = Array.prototype.slice.call(arguments, 1)
130 } else if (typeof (args[0]) !== 'string') {
132 args = Array.prototype.slice.call(arguments, 1)
136 logger[level].apply(logger, args)
140 const bunyanLogger = {
142 trace: bunyanLogFactory('debug'),
143 debug: bunyanLogFactory('debug'),
144 info: bunyanLogFactory('info'),
145 warn: bunyanLogFactory('warn'),
146 error: bunyanLogFactory('error'),
147 fatal: bunyanLogFactory('error')
150 type LoggerTagsFn = (...tags: string[]) => { tags: string[] }
151 function loggerTagsFactory (...defaultTags: string[]): LoggerTagsFn {
152 return (...tags: string[]) => {
153 return { tags: defaultTags.concat(tags) }
157 async function mtimeSortFilesDesc (files: string[], basePath: string) {
159 const out: { file: string, mtime: number }[] = []
161 for (const file of files) {
162 const p = stat(basePath + '/' + file)
164 if (stats.isFile()) out.push({ file, mtime: stats.mtime.getTime() })
170 await Promise.all(promises)
172 out.sort((a, b) => b.mtime - a.mtime)
177 // ---------------------------------------------------------------------------