]>
Commit | Line | Data |
---|---|---|
1 | // Thanks http://tostring.it/2014/06/23/advanced-logging-with-nodejs/ | |
2 | import * as mkdirp from 'mkdirp' | |
3 | import * as path from 'path' | |
4 | import * as winston from 'winston' | |
5 | import { CONFIG } from '../initializers' | |
6 | ||
7 | const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT | |
8 | ||
9 | // Create the directory if it does not exist | |
10 | mkdirp.sync(CONFIG.STORAGE.LOG_DIR) | |
11 | ||
12 | // Use object for better performances (~ O(1)) | |
13 | const excludedKeys = { | |
14 | level: true, | |
15 | message: true, | |
16 | splat: true, | |
17 | timestamp: true, | |
18 | label: true | |
19 | } | |
20 | function keysExcluder (key, value) { | |
21 | return excludedKeys[key] === true ? undefined : value | |
22 | } | |
23 | ||
24 | const loggerFormat = winston.format.printf(info => { | |
25 | let additionalInfos = JSON.stringify(info, keysExcluder, 2) | |
26 | if (additionalInfos === '{}') additionalInfos = '' | |
27 | else additionalInfos = ' ' + additionalInfos | |
28 | ||
29 | if (info.message && info.message.stack !== undefined) info.message = info.message.stack | |
30 | return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}${additionalInfos}` | |
31 | }) | |
32 | ||
33 | const timestampFormatter = winston.format.timestamp({ | |
34 | format: 'YYYY-MM-dd HH:mm:ss.SSS' | |
35 | }) | |
36 | const labelFormatter = winston.format.label({ | |
37 | label | |
38 | }) | |
39 | ||
40 | const logger = new winston.createLogger({ | |
41 | level: CONFIG.LOG.LEVEL, | |
42 | transports: [ | |
43 | new winston.transports.File({ | |
44 | filename: path.join(CONFIG.STORAGE.LOG_DIR, 'peertube.log'), | |
45 | handleExceptions: true, | |
46 | maxsize: 5242880, | |
47 | maxFiles: 5, | |
48 | format: winston.format.combine( | |
49 | timestampFormatter, | |
50 | labelFormatter, | |
51 | winston.format.splat(), | |
52 | winston.format.json() | |
53 | ) | |
54 | }), | |
55 | new winston.transports.Console({ | |
56 | handleExceptions: true, | |
57 | humanReadableUnhandledException: true, | |
58 | format: winston.format.combine( | |
59 | timestampFormatter, | |
60 | winston.format.splat(), | |
61 | labelFormatter, | |
62 | winston.format.colorize(), | |
63 | loggerFormat | |
64 | ) | |
65 | }) | |
66 | ], | |
67 | exitOnError: true | |
68 | }) | |
69 | ||
70 | // --------------------------------------------------------------------------- | |
71 | ||
72 | export { | |
73 | timestampFormatter, | |
74 | labelFormatter, | |
75 | loggerFormat, | |
76 | logger | |
77 | } |