Skip to content

Commit 814c572

Browse files
drazisilindexzero
authored andcommitted
Add handleRejections support (winstonjs#1462)
* Add handleRejections suppot * Correct typo
1 parent 5e91a1a commit 814c572

File tree

9 files changed

+653
-78
lines changed

9 files changed

+653
-78
lines changed

lib/winston.js

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ winston.createLogger = require('./winston/create-logger');
5151
* @type {Object}
5252
*/
5353
winston.ExceptionHandler = require('./winston/exception-handler');
54+
/**
55+
* Expose core Logging-related prototypes.
56+
* @type {Object}
57+
*/
58+
winston.RejectionHandler = require('./winston/rejection-handler');
5459
/**
5560
* Expose core Logging-related prototypes.
5661
* @type {Container}
@@ -85,21 +90,25 @@ winston.loggers = new winston.Container();
8590
const defaultLogger = winston.createLogger();
8691

8792
// Pass through the target methods onto `winston.
88-
Object.keys(winston.config.npm.levels).concat([
89-
'log',
90-
'query',
91-
'stream',
92-
'add',
93-
'remove',
94-
'clear',
95-
'profile',
96-
'startTimer',
97-
'handleExceptions',
98-
'unhandleExceptions',
99-
'configure'
100-
]).forEach(method => (
101-
winston[method] = (...args) => defaultLogger[method](...args)
102-
));
93+
Object.keys(winston.config.npm.levels)
94+
.concat([
95+
'log',
96+
'query',
97+
'stream',
98+
'add',
99+
'remove',
100+
'clear',
101+
'profile',
102+
'startTimer',
103+
'handleExceptions',
104+
'unhandleExceptions',
105+
'handleRejections',
106+
'unhandleRejections',
107+
'configure'
108+
])
109+
.forEach(
110+
method => (winston[method] = (...args) => defaultLogger[method](...args))
111+
);
103112

104113
/**
105114
* Define getter / setter for the default logger level which need to be exposed
@@ -131,9 +140,7 @@ Object.defineProperty(winston, 'exceptions', {
131140
* which need to be exposed by winston.
132141
* @type {Logger}
133142
*/
134-
[
135-
'exitOnError'
136-
].forEach(prop => {
143+
['exitOnError'].forEach(prop => {
137144
Object.defineProperty(winston, prop, {
138145
get() {
139146
return defaultLogger[prop];
@@ -152,6 +159,7 @@ Object.defineProperty(winston, 'default', {
152159
get() {
153160
return {
154161
exceptionHandlers: defaultLogger.exceptionHandlers,
162+
rejectionHandlers: defaultLogger.rejectionHandlers,
155163
transports: defaultLogger.transports
156164
};
157165
}
@@ -160,20 +168,14 @@ Object.defineProperty(winston, 'default', {
160168
// Have friendlier breakage notices for properties that were exposed by default
161169
// on winston < 3.0.
162170
warn.deprecated(winston, 'setLevels');
163-
warn.forFunctions(winston, 'useFormat', ['cli']);
164-
warn.forProperties(winston, 'useFormat', [
165-
'padLevels',
166-
'stripColors'
167-
]);
168-
warn.forFunctions(winston, 'deprecated', [
171+
warn.forFunctions(winston, 'useFormat', ['cli']);
172+
warn.forProperties(winston, 'useFormat', ['padLevels', 'stripColors']);
173+
warn.forFunctions(winston, 'deprecated', [
169174
'addRewriter',
170175
'addFilter',
171176
'clone',
172177
'extend'
173178
]);
174-
warn.forProperties(winston, 'deprecated', [
175-
'emitErrs',
176-
'levelLength'
177-
]);
179+
warn.forProperties(winston, 'deprecated', ['emitErrs', 'levelLength']);
178180
// Throw a useful error when users attempt to run `new winston.Logger`.
179181
warn.moved(winston, 'createLogger', 'Logger');

lib/winston/logger.js

Lines changed: 68 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const asyncForEach = require('async/forEach');
1212
const { LEVEL, SPLAT } = require('triple-beam');
1313
const isStream = require('is-stream');
1414
const ExceptionHandler = require('./exception-handler');
15+
const RejectionHandler = require('./rejection-handler');
1516
const LegacyTransportStream = require('winston-transport/legacy');
1617
const Profiler = require('./profiler');
1718
const { warn } = require('./common');
@@ -88,7 +89,8 @@ class Logger extends Transform {
8889
padLevels,
8990
rewriters,
9091
stripColors,
91-
exceptionHandlers
92+
exceptionHandlers,
93+
rejectionHandlers
9294
} = {}) {
9395
// Reset transports if we already have them
9496
if (this.transports.length) {
@@ -103,6 +105,7 @@ class Logger extends Transform {
103105
this.levels = levels || this.levels || config.npm.levels;
104106
this.level = level;
105107
this.exceptions = new ExceptionHandler(this);
108+
this.rejections = new RejectionHandler(this);
106109
this.profilers = {};
107110
this.exitOnError = exitOnError;
108111

@@ -113,19 +116,28 @@ class Logger extends Transform {
113116
}
114117

115118
if (
116-
colors || emitErrs || formatters ||
117-
padLevels || rewriters || stripColors
119+
colors ||
120+
emitErrs ||
121+
formatters ||
122+
padLevels ||
123+
rewriters ||
124+
stripColors
118125
) {
119-
throw new Error([
120-
'{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in [email protected].',
121-
'Use a custom winston.format(function) instead.',
122-
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
123-
].join('\n'));
126+
throw new Error(
127+
[
128+
'{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in [email protected].',
129+
'Use a custom winston.format(function) instead.',
130+
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
131+
].join('\n')
132+
);
124133
}
125134

126135
if (exceptionHandlers) {
127136
this.exceptions.handle(exceptionHandlers);
128137
}
138+
if (rejectionHandlers) {
139+
this.rejections.handle(rejectionHandlers);
140+
}
129141
}
130142

131143
isLevelEnabled(level) {
@@ -183,7 +195,8 @@ class Logger extends Transform {
183195
*
184196
*/
185197
/* eslint-enable valid-jsdoc */
186-
log(level, msg, ...splat) { // eslint-disable-line max-params
198+
log(level, msg, ...splat) {
199+
// eslint-disable-line max-params
187200
// Optimize for the hotpath of logging JSON literals
188201
if (arguments.length === 1) {
189202
// Yo dawg, I heard you like levels ... seriously ...
@@ -276,7 +289,10 @@ class Logger extends Transform {
276289
// Remark: not sure if we should simply error here.
277290
if (!this._readableState.pipes) {
278291
// eslint-disable-next-line no-console
279-
console.error('[winston] Attempt to write logs with no transports %j', info);
292+
console.error(
293+
'[winston] Attempt to write logs with no transports %j',
294+
info
295+
);
280296
}
281297

282298
// Here we write to the `format` pipe-chain, which on `readable` above will
@@ -300,11 +316,15 @@ class Logger extends Transform {
300316
*/
301317
_final(callback) {
302318
const transports = this.transports.slice();
303-
asyncForEach(transports, (transport, next) => {
304-
if (!transport || transport.finished) return setImmediate(next);
305-
transport.once('finish', next);
306-
transport.end();
307-
}, callback);
319+
asyncForEach(
320+
transports,
321+
(transport, next) => {
322+
if (!transport || transport.finished) return setImmediate(next);
323+
transport.once('finish', next);
324+
transport.end();
325+
},
326+
callback
327+
);
308328
}
309329

310330
/**
@@ -318,12 +338,15 @@ class Logger extends Transform {
318338
// 1. They inherit from winston.Transport in < 3.x.x which is NOT a stream.
319339
// 2. They expose a log method which has a length greater than 2 (i.e. more then
320340
// just `log(info, callback)`.
321-
const target = !isStream(transport) || transport.log.length > 2
322-
? new LegacyTransportStream({ transport })
323-
: transport;
341+
const target =
342+
!isStream(transport) || transport.log.length > 2
343+
? new LegacyTransportStream({ transport })
344+
: transport;
324345

325346
if (!target._writableState || !target._writableState.objectMode) {
326-
throw new Error('Transports must WritableStreams in objectMode. Set { objectMode: true }.');
347+
throw new Error(
348+
'Transports must WritableStreams in objectMode. Set { objectMode: true }.'
349+
);
327350
}
328351

329352
// Listen for the `error` event and the `warn` event on the new Transport.
@@ -335,6 +358,10 @@ class Logger extends Transform {
335358
this.exceptions.handle();
336359
}
337360

361+
if (transport.handleRejections) {
362+
this.rejections.handle();
363+
}
364+
338365
return this;
339366
}
340367

@@ -346,11 +373,14 @@ class Logger extends Transform {
346373
remove(transport) {
347374
let target = transport;
348375
if (!isStream(transport) || transport.log.length > 2) {
349-
target = this.transports
350-
.filter(match => match.transport === transport)[0];
376+
target = this.transports.filter(
377+
match => match.transport === transport
378+
)[0];
351379
}
352380

353-
if (target) { this.unpipe(target); }
381+
if (target) {
382+
this.unpipe(target);
383+
}
354384
return this;
355385
}
356386

@@ -523,7 +553,9 @@ class Logger extends Transform {
523553
// Attempt to be kind to users if they are still using older APIs.
524554
if (typeof args[args.length - 2] === 'function') {
525555
// eslint-disable-next-line no-console
526-
console.warn('Callback function no longer supported as of [email protected]');
556+
console.warn(
557+
'Callback function no longer supported as of [email protected]'
558+
);
527559
args.pop();
528560
}
529561

@@ -546,7 +578,9 @@ class Logger extends Transform {
546578
*/
547579
handleExceptions(...args) {
548580
// eslint-disable-next-line no-console
549-
console.warn('Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()');
581+
console.warn(
582+
'Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()'
583+
);
550584
this.exceptions.handle(...args);
551585
}
552586

@@ -557,7 +591,9 @@ class Logger extends Transform {
557591
*/
558592
unhandleExceptions(...args) {
559593
// eslint-disable-next-line no-console
560-
console.warn('Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()');
594+
console.warn(
595+
'Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()'
596+
);
561597
this.exceptions.unhandle(...args);
562598
}
563599

@@ -566,11 +602,13 @@ class Logger extends Transform {
566602
* @throws {Error} - TODO: add throws description.
567603
*/
568604
cli() {
569-
throw new Error([
570-
'Logger.cli() was removed in [email protected]',
571-
'Use a custom winston.formats.cli() instead.',
572-
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
573-
].join('\n'));
605+
throw new Error(
606+
[
607+
'Logger.cli() was removed in [email protected]',
608+
'Use a custom winston.formats.cli() instead.',
609+
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
610+
].join('\n')
611+
);
574612
}
575613

576614
/**

0 commit comments

Comments
 (0)