]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/logger.ts
Translated using Weblate (Kabyle)
[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 { omit } from 'lodash'
4import * as path from 'path'
5import { format as sqlFormat } from 'sql-formatter'
6import * as winston from 'winston'
7import { FileTransportOptions } from 'winston/lib/winston/transports'
8import { CONFIG } from '../initializers/config'
9import { LOG_FILENAME } from '../initializers/constants'
10
11const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
12
13// Create the directory if it does not exist
14// FIXME: use async
15mkdirpSync(CONFIG.STORAGE.LOG_DIR)
16
17function getLoggerReplacer () {
18 const seen = new WeakSet()
19
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'
23
24 if (typeof value === 'object' && value !== null) {
25 if (seen.has(value)) return
26
27 seen.add(value)
28 }
29
30 if (value instanceof Set) {
31 return Array.from(value)
32 }
33
34 if (value instanceof Map) {
35 return Array.from(value.entries())
36 }
37
38 if (value instanceof Error) {
39 const error = {}
40
41 Object.getOwnPropertyNames(value).forEach(key => { error[key] = value[key] })
42
43 return error
44 }
45
46 return value
47 }
48}
49
50const consoleLoggerFormat = winston.format.printf(info => {
51 const toOmit = [ 'label', 'timestamp', 'level', 'message', 'sql', 'tags' ]
52
53 const obj = omit(info, ...toOmit)
54
55 let additionalInfos = JSON.stringify(obj, getLoggerReplacer(), 2)
56
57 if (additionalInfos === undefined || additionalInfos === '{}') additionalInfos = ''
58 else additionalInfos = ' ' + additionalInfos
59
60 if (info.sql) {
61 if (CONFIG.LOG.PRETTIFY_SQL) {
62 additionalInfos += '\n' + sqlFormat(info.sql, {
63 language: 'sql',
64 indent: ' '
65 })
66 } else {
67 additionalInfos += ' - ' + info.sql
68 }
69 }
70
71 return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}`
72})
73
74const jsonLoggerFormat = winston.format.printf(info => {
75 return JSON.stringify(info, getLoggerReplacer())
76})
77
78const timestampFormatter = winston.format.timestamp({
79 format: 'YYYY-MM-DD HH:mm:ss.SSS'
80})
81const labelFormatter = (suffix?: string) => {
82 return winston.format.label({
83 label: suffix ? `${label} ${suffix}` : label
84 })
85}
86
87const fileLoggerOptions: FileTransportOptions = {
88 filename: path.join(CONFIG.STORAGE.LOG_DIR, LOG_FILENAME),
89 handleExceptions: true,
90 format: winston.format.combine(
91 winston.format.timestamp(),
92 jsonLoggerFormat
93 )
94}
95
96if (CONFIG.LOG.ROTATION.ENABLED) {
97 fileLoggerOptions.maxsize = CONFIG.LOG.ROTATION.MAX_FILE_SIZE
98 fileLoggerOptions.maxFiles = CONFIG.LOG.ROTATION.MAX_FILES
99}
100
101const logger = buildLogger()
102
103function buildLogger (labelSuffix?: string) {
104 return winston.createLogger({
105 level: CONFIG.LOG.LEVEL,
106 format: winston.format.combine(
107 labelFormatter(labelSuffix),
108 winston.format.splat()
109 ),
110 transports: [
111 new winston.transports.File(fileLoggerOptions),
112 new winston.transports.Console({
113 handleExceptions: true,
114 format: winston.format.combine(
115 timestampFormatter,
116 winston.format.colorize(),
117 consoleLoggerFormat
118 )
119 })
120 ],
121 exitOnError: true
122 })
123}
124
125function bunyanLogFactory (level: string) {
126 return function () {
127 let meta = null
128 let args: any[] = []
129 args.concat(arguments)
130
131 if (arguments[0] instanceof Error) {
132 meta = arguments[0].toString()
133 args = Array.prototype.slice.call(arguments, 1)
134 args.push(meta)
135 } else if (typeof (args[0]) !== 'string') {
136 meta = arguments[0]
137 args = Array.prototype.slice.call(arguments, 1)
138 args.push(meta)
139 }
140
141 logger[level].apply(logger, args)
142 }
143}
144
145const 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')
152}
153
154function loggerTagsFactory (...defaultTags: string[]) {
155 return (...tags: string[]) => {
156 return { tags: defaultTags.concat(tags) }
157 }
158}
159
160// ---------------------------------------------------------------------------
161
162export {
163 buildLogger,
164 timestampFormatter,
165 labelFormatter,
166 consoleLoggerFormat,
167 jsonLoggerFormat,
168 logger,
169 loggerTagsFactory,
170 bunyanLogger
171}