Skip to content

Commit

Permalink
Add handleRejections support (winstonjs#1462)
Browse files Browse the repository at this point in the history
* Add handleRejections suppot

* Correct typo
  • Loading branch information
drazisil authored and indexzero committed Dec 26, 2018
1 parent 5e91a1a commit 814c572
Show file tree
Hide file tree
Showing 9 changed files with 653 additions and 78 deletions.
58 changes: 30 additions & 28 deletions lib/winston.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ winston.createLogger = require('./winston/create-logger');
* @type {Object}
*/
winston.ExceptionHandler = require('./winston/exception-handler');
/**
* Expose core Logging-related prototypes.
* @type {Object}
*/
winston.RejectionHandler = require('./winston/rejection-handler');
/**
* Expose core Logging-related prototypes.
* @type {Container}
Expand Down Expand Up @@ -85,21 +90,25 @@ winston.loggers = new winston.Container();
const defaultLogger = winston.createLogger();

// Pass through the target methods onto `winston.
Object.keys(winston.config.npm.levels).concat([
'log',
'query',
'stream',
'add',
'remove',
'clear',
'profile',
'startTimer',
'handleExceptions',
'unhandleExceptions',
'configure'
]).forEach(method => (
winston[method] = (...args) => defaultLogger[method](...args)
));
Object.keys(winston.config.npm.levels)
.concat([
'log',
'query',
'stream',
'add',
'remove',
'clear',
'profile',
'startTimer',
'handleExceptions',
'unhandleExceptions',
'handleRejections',
'unhandleRejections',
'configure'
])
.forEach(
method => (winston[method] = (...args) => defaultLogger[method](...args))
);

/**
* Define getter / setter for the default logger level which need to be exposed
Expand Down Expand Up @@ -131,9 +140,7 @@ Object.defineProperty(winston, 'exceptions', {
* which need to be exposed by winston.
* @type {Logger}
*/
[
'exitOnError'
].forEach(prop => {
['exitOnError'].forEach(prop => {
Object.defineProperty(winston, prop, {
get() {
return defaultLogger[prop];
Expand All @@ -152,6 +159,7 @@ Object.defineProperty(winston, 'default', {
get() {
return {
exceptionHandlers: defaultLogger.exceptionHandlers,
rejectionHandlers: defaultLogger.rejectionHandlers,
transports: defaultLogger.transports
};
}
Expand All @@ -160,20 +168,14 @@ Object.defineProperty(winston, 'default', {
// Have friendlier breakage notices for properties that were exposed by default
// on winston < 3.0.
warn.deprecated(winston, 'setLevels');
warn.forFunctions(winston, 'useFormat', ['cli']);
warn.forProperties(winston, 'useFormat', [
'padLevels',
'stripColors'
]);
warn.forFunctions(winston, 'deprecated', [
warn.forFunctions(winston, 'useFormat', ['cli']);
warn.forProperties(winston, 'useFormat', ['padLevels', 'stripColors']);
warn.forFunctions(winston, 'deprecated', [
'addRewriter',
'addFilter',
'clone',
'extend'
]);
warn.forProperties(winston, 'deprecated', [
'emitErrs',
'levelLength'
]);
warn.forProperties(winston, 'deprecated', ['emitErrs', 'levelLength']);
// Throw a useful error when users attempt to run `new winston.Logger`.
warn.moved(winston, 'createLogger', 'Logger');
98 changes: 68 additions & 30 deletions lib/winston/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const asyncForEach = require('async/forEach');
const { LEVEL, SPLAT } = require('triple-beam');
const isStream = require('is-stream');
const ExceptionHandler = require('./exception-handler');
const RejectionHandler = require('./rejection-handler');
const LegacyTransportStream = require('winston-transport/legacy');
const Profiler = require('./profiler');
const { warn } = require('./common');
Expand Down Expand Up @@ -88,7 +89,8 @@ class Logger extends Transform {
padLevels,
rewriters,
stripColors,
exceptionHandlers
exceptionHandlers,
rejectionHandlers
} = {}) {
// Reset transports if we already have them
if (this.transports.length) {
Expand All @@ -103,6 +105,7 @@ class Logger extends Transform {
this.levels = levels || this.levels || config.npm.levels;
this.level = level;
this.exceptions = new ExceptionHandler(this);
this.rejections = new RejectionHandler(this);
this.profilers = {};
this.exitOnError = exitOnError;

Expand All @@ -113,19 +116,28 @@ class Logger extends Transform {
}

if (
colors || emitErrs || formatters ||
padLevels || rewriters || stripColors
colors ||
emitErrs ||
formatters ||
padLevels ||
rewriters ||
stripColors
) {
throw new Error([
'{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.',
'Use a custom winston.format(function) instead.',
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
].join('\n'));
throw new Error(
[
'{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.',
'Use a custom winston.format(function) instead.',
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
].join('\n')
);
}

if (exceptionHandlers) {
this.exceptions.handle(exceptionHandlers);
}
if (rejectionHandlers) {
this.rejections.handle(rejectionHandlers);
}
}

isLevelEnabled(level) {
Expand Down Expand Up @@ -183,7 +195,8 @@ class Logger extends Transform {
*
*/
/* eslint-enable valid-jsdoc */
log(level, msg, ...splat) { // eslint-disable-line max-params
log(level, msg, ...splat) {
// eslint-disable-line max-params
// Optimize for the hotpath of logging JSON literals
if (arguments.length === 1) {
// Yo dawg, I heard you like levels ... seriously ...
Expand Down Expand Up @@ -276,7 +289,10 @@ class Logger extends Transform {
// Remark: not sure if we should simply error here.
if (!this._readableState.pipes) {
// eslint-disable-next-line no-console
console.error('[winston] Attempt to write logs with no transports %j', info);
console.error(
'[winston] Attempt to write logs with no transports %j',
info
);
}

// Here we write to the `format` pipe-chain, which on `readable` above will
Expand All @@ -300,11 +316,15 @@ class Logger extends Transform {
*/
_final(callback) {
const transports = this.transports.slice();
asyncForEach(transports, (transport, next) => {
if (!transport || transport.finished) return setImmediate(next);
transport.once('finish', next);
transport.end();
}, callback);
asyncForEach(
transports,
(transport, next) => {
if (!transport || transport.finished) return setImmediate(next);
transport.once('finish', next);
transport.end();
},
callback
);
}

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

if (!target._writableState || !target._writableState.objectMode) {
throw new Error('Transports must WritableStreams in objectMode. Set { objectMode: true }.');
throw new Error(
'Transports must WritableStreams in objectMode. Set { objectMode: true }.'
);
}

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

if (transport.handleRejections) {
this.rejections.handle();
}

return this;
}

Expand All @@ -346,11 +373,14 @@ class Logger extends Transform {
remove(transport) {
let target = transport;
if (!isStream(transport) || transport.log.length > 2) {
target = this.transports
.filter(match => match.transport === transport)[0];
target = this.transports.filter(
match => match.transport === transport
)[0];
}

if (target) { this.unpipe(target); }
if (target) {
this.unpipe(target);
}
return this;
}

Expand Down Expand Up @@ -523,7 +553,9 @@ class Logger extends Transform {
// Attempt to be kind to users if they are still using older APIs.
if (typeof args[args.length - 2] === 'function') {
// eslint-disable-next-line no-console
console.warn('Callback function no longer supported as of winston@3.0.0');
console.warn(
'Callback function no longer supported as of winston@3.0.0'
);
args.pop();
}

Expand All @@ -546,7 +578,9 @@ class Logger extends Transform {
*/
handleExceptions(...args) {
// eslint-disable-next-line no-console
console.warn('Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()');
console.warn(
'Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()'
);
this.exceptions.handle(...args);
}

Expand All @@ -557,7 +591,9 @@ class Logger extends Transform {
*/
unhandleExceptions(...args) {
// eslint-disable-next-line no-console
console.warn('Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()');
console.warn(
'Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()'
);
this.exceptions.unhandle(...args);
}

Expand All @@ -566,11 +602,13 @@ class Logger extends Transform {
* @throws {Error} - TODO: add throws description.
*/
cli() {
throw new Error([
'Logger.cli() was removed in winston@3.0.0',
'Use a custom winston.formats.cli() instead.',
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
].join('\n'));
throw new Error(
[
'Logger.cli() was removed in winston@3.0.0',
'Use a custom winston.formats.cli() instead.',
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
].join('\n')
);
}

/**
Expand Down
Loading

0 comments on commit 814c572

Please sign in to comment.