1 | const Transport = require('winston-transport');
|
2 | const stringifySafe = require('json-stringify-safe');
|
3 | const logzioNodejs = require('logzio-nodejs');
|
4 | const {
|
5 | LEVEL,
|
6 | MESSAGE,
|
7 | } = require('triple-beam');
|
8 |
|
9 | module.exports = class LogzioWinstonTransport extends Transport {
|
10 | constructor(options) {
|
11 | super(options);
|
12 | this.name = options.name || 'LogzioLogger';
|
13 | this.level = options.level || 'info';
|
14 | this.logzioLogger = logzioNodejs.createLogger(options);
|
15 | }
|
16 |
|
17 | log(info, callback) {
|
18 | setImmediate(() => {
|
19 | this.emit('logged', info);
|
20 | });
|
21 |
|
22 | const infoMessage = info.message || info[MESSAGE];
|
23 | let msg;
|
24 | if (typeof infoMessage !== 'string' && typeof infoMessage !== 'object') {
|
25 | msg = {
|
26 | message: this.constructor.safeToString(infoMessage),
|
27 | };
|
28 | } else if (typeof infoMessage === 'string') {
|
29 | msg = {
|
30 | message: infoMessage,
|
31 | };
|
32 | }
|
33 |
|
34 | const logObject = Object.assign({},
|
35 | info,
|
36 | msg, {
|
37 | level: info[LEVEL] || this.level,
|
38 | name: this.name,
|
39 | });
|
40 |
|
41 | this.logzioLogger.log(logObject);
|
42 | callback(null, true);
|
43 | }
|
44 |
|
45 | static safeToString(json) {
|
46 | try {
|
47 | return JSON.stringify(json);
|
48 | } catch (ex) {
|
49 | return stringifySafe(json, null, null, () => {});
|
50 | }
|
51 | }
|
52 |
|
53 | finish(callback) {
|
54 | this.logzioLogger.sendAndClose(callback);
|
55 | }
|
56 |
|
57 | close(cb) {
|
58 | this.finish(() => {
|
59 | this.emit('finish');
|
60 | this.emit('close');
|
61 | if (cb) cb();
|
62 | });
|
63 | }
|
64 | };
|