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'
11 const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
13 // Create the directory if it does not exist
15 mkdirpSync(CONFIG.STORAGE.LOG_DIR)
17 function getLoggerReplacer () {
18 const seen = new WeakSet()
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'
24 if (typeof value === 'object' && value !== null) {
25 if (seen.has(value)) return
30 if (value instanceof Set) {
31 return Array.from(value)
34 if (value instanceof Map) {
35 return Array.from(value.entries())
38 if (value instanceof Error) {
41 Object.getOwnPropertyNames(value).forEach(key => { error[key] = value[key] })
50 const consoleLoggerFormat = winston.format.printf(info => {
51 const toOmit = [ 'label', 'timestamp', 'level', 'message', 'sql', 'tags' ]
53 const obj = omit(info, ...toOmit)
55 let additionalInfos = JSON.stringify(obj, getLoggerReplacer(), 2)
57 if (additionalInfos === undefined || additionalInfos === '{}') additionalInfos = ''
58 else additionalInfos = ' ' + additionalInfos
61 if (CONFIG.LOG.PRETTIFY_SQL) {
62 additionalInfos += '\n' + sqlFormat(info.sql, {
67 additionalInfos += ' - ' + info.sql
71 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
74 const jsonLoggerFormat = winston.format.printf(info => {
75 return JSON.stringify(info, getLoggerReplacer())
78 const timestampFormatter = winston.format.timestamp({
79 format: 'YYYY-MM-DD HH:mm:ss.SSS'
81 const labelFormatter = (suffix?: string) => {
82 return winston.format.label({
83 label: suffix ? `${label} ${suffix}` : label
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(),
96 if (CONFIG.LOG.ROTATION.ENABLED) {
97 fileLoggerOptions.maxsize = CONFIG.LOG.ROTATION.MAX_FILE_SIZE
98 fileLoggerOptions.maxFiles = CONFIG.LOG.ROTATION.MAX_FILES
101 const logger = buildLogger()
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()
111 new winston.transports.File(fileLoggerOptions),
112 new winston.transports.Console({
113 handleExceptions: true,
114 format: winston.format.combine(
116 winston.format.colorize(),
125 function bunyanLogFactory (level: string) {
129 args.concat(arguments)
131 if (arguments[0] instanceof Error) {
132 meta = arguments[0].toString()
133 args = Array.prototype.slice.call(arguments, 1)
135 } else if (typeof (args[0]) !== 'string') {
137 args = Array.prototype.slice.call(arguments, 1)
141 logger[level].apply(logger, args)
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')
154 type LoggerTagsFn = (...tags: string[]) => { tags: string[] }
155 function loggerTagsFactory (...defaultTags: string[]): LoggerTagsFn {
156 return (...tags: string[]) => {
157 return { tags: defaultTags.concat(tags) }
161 // ---------------------------------------------------------------------------