]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/logger.ts
Fix tests
[github/Chocobozzz/PeerTube.git] / server / helpers / logger.ts
... / ...
CommitLineData
1// Thanks http://tostring.it/2014/06/23/advanced-logging-with-nodejs/
2import { mkdirpSync } from 'fs-extra'
3import * as path from 'path'
4import * as winston from 'winston'
5import { FileTransportOptions } from 'winston/lib/winston/transports'
6import { CONFIG } from '../initializers/config'
7import { omit } from 'lodash'
8import { LOG_FILENAME } from '../initializers/constants'
9
10const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
11
12// Create the directory if it does not exist
13// FIXME: use async
14mkdirpSync(CONFIG.STORAGE.LOG_DIR)
15
16function getLoggerReplacer () {
17 const seen = new WeakSet()
18
19 // Thanks: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#Examples
20 return (key: string, value: any) => {
21 if (typeof value === 'object' && value !== null) {
22 if (seen.has(value)) return
23
24 seen.add(value)
25 }
26
27 if (value instanceof Error) {
28 const error = {}
29
30 Object.getOwnPropertyNames(value).forEach(key => { error[key] = value[key] })
31
32 return error
33 }
34
35 return value
36 }
37}
38
39const consoleLoggerFormat = winston.format.printf(info => {
40 const obj = omit(info, 'label', 'timestamp', 'level', 'message')
41
42 let additionalInfos = JSON.stringify(obj, getLoggerReplacer(), 2)
43
44 if (additionalInfos === undefined || additionalInfos === '{}') additionalInfos = ''
45 else additionalInfos = ' ' + additionalInfos
46
47 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
48})
49
50const jsonLoggerFormat = winston.format.printf(info => {
51 return JSON.stringify(info, getLoggerReplacer())
52})
53
54const timestampFormatter = winston.format.timestamp({
55 format: 'YYYY-MM-DD HH:mm:ss.SSS'
56})
57const labelFormatter = (suffix?: string) => {
58 return winston.format.label({
59 label: suffix ? `${label} ${suffix}` : label
60 })
61}
62
63const fileLoggerOptions: FileTransportOptions = {
64 filename: path.join(CONFIG.STORAGE.LOG_DIR, LOG_FILENAME),
65 handleExceptions: true,
66 format: winston.format.combine(
67 winston.format.timestamp(),
68 jsonLoggerFormat
69 )
70}
71
72if (CONFIG.LOG.ROTATION.ENABLED) {
73 fileLoggerOptions.maxsize = CONFIG.LOG.ROTATION.MAX_FILE_SIZE
74 fileLoggerOptions.maxFiles = CONFIG.LOG.ROTATION.MAX_FILES
75}
76
77const logger = buildLogger()
78
79function buildLogger (labelSuffix?: string) {
80 return winston.createLogger({
81 level: CONFIG.LOG.LEVEL,
82 format: winston.format.combine(
83 labelFormatter(labelSuffix),
84 winston.format.splat()
85 ),
86 transports: [
87 new winston.transports.File(fileLoggerOptions),
88 new winston.transports.Console({
89 handleExceptions: true,
90 format: winston.format.combine(
91 timestampFormatter,
92 winston.format.colorize(),
93 consoleLoggerFormat
94 )
95 })
96 ],
97 exitOnError: true
98 })
99}
100
101function bunyanLogFactory (level: string) {
102 return function () {
103 let meta = null
104 let args: any[] = []
105 args.concat(arguments)
106
107 if (arguments[0] instanceof Error) {
108 meta = arguments[0].toString()
109 args = Array.prototype.slice.call(arguments, 1)
110 args.push(meta)
111 } else if (typeof (args[0]) !== 'string') {
112 meta = arguments[0]
113 args = Array.prototype.slice.call(arguments, 1)
114 args.push(meta)
115 }
116
117 logger[level].apply(logger, args)
118 }
119}
120
121const bunyanLogger = {
122 trace: bunyanLogFactory('debug'),
123 debug: bunyanLogFactory('debug'),
124 info: bunyanLogFactory('info'),
125 warn: bunyanLogFactory('warn'),
126 error: bunyanLogFactory('error'),
127 fatal: bunyanLogFactory('error')
128}
129// ---------------------------------------------------------------------------
130
131export {
132 buildLogger,
133 timestampFormatter,
134 labelFormatter,
135 consoleLoggerFormat,
136 jsonLoggerFormat,
137 logger,
138 bunyanLogger
139}