-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
transports.File is not flushing on end. #1504
Comments
I'm experiencing the same issue in some unit tests. In addition to waiting for the transport to emit the
There is still a race condition here because the test does pass some of the time, and inevitably if I look in the file manually it does have the logging output within it. |
Should be a function export function flushLogs(): Promise<void> {
// tslint:disable-next-line: typedef
return new Promise((resolve, reject) => {
logger.on('finish', () => resolve());
logger.end();
});
} |
I am experiencing the same issue, makes it really hard to use winston with asynchronous processing |
I am experiencing the exact same issue, the posted code by @racquetmaster is correct. It makes it almost impossible to use winston with asynchronous processing I have been following the documentation (below) calling the end() on Logger. I also tried directly on (File) Transport like @racquetmaster without success. IMO this is a very important issue.
'use strict'
const winston = require('winston')
const logFilePath = __dirname + '/test-async.log'
const logger = winston.createLogger({
level: 'debug',
format: winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
winston.format.simple(),
winston.format.printf(info => {
return `[${info.timestamp}] [${info.level}] ${info.message}`
})),
transports: [
new winston.transports.File({
filename: logFilePath
})
]
})
let code = 1
const asyncFunction = async function(){
return new Promise(function(resolve) {
setTimeout(function() {
logger.info('resolved')
resolve(0)
}, 300)
})
}
const start = async function(){
logger.info('START')
code = await asyncFunction()
logger.info(`code : ${code}`)
logger.on('finish', function() {
process.exit(code)
})
//Should display END before exiting the process according to doc
logger.info('END')
logger.end()
}
start() |
This works for me: |
This seems to solve the issue for me logger.on('finish', function() {
setImmediate(() => process.exit(code))
}) Did not have the time to look at winston code in detail but it seems to mean than the finish event is raised too early, maybe it is added to the event loop before the flush of the underlying transports |
I am sure this fix works pretty well: #1868 const fileTransport = new winston.transports.File({
filename: 'error.log',
level: 'error',
});
/**
* Create a basic logger that outputs stderr to error.log
*/
const logger = winston.createLogger({
level: 'info',
transports: [
fileTransport,
],
});
logger.endGracefully = () => new Promise((fulfill, reject) => {
// Add logic for other transports here ...
fileTransport.on('flush', () => {
fulfill();
});
logger.end();
});
// CODE
logger.error('Here comes a log entry');
setTimeout(async () => {
logger.error('Here comes another log entry');
await logger.endGracefully();
process.exit(0);
}, 1000)
|
Thanks for this. Your workaround doesn't work in my tests. Here's the basic test I have:
This fails because the file doesn't exist at the I hope that helps. |
This is still a major problem searched on internet. Found this, https://www.npmjs.com/package/winston-log-and-exit |
tldr: replace After wasting a couple of hours I hope this will help someone else. |
For anyone running in to this issue because they are trying to capture logs for assertion in unit tests (to check their logs are formatted properly), I solved this using a Stream transport rather than file. It was much, much more reliable: import { createLogger, format, transports } from 'winston';
import { Writable } from 'stream';
import { v4 } from 'uuid';
const logger = createLogger({
level: 'info',
format: format.combine(
format.timestamp(),
format.errors({ stack: true }),
errorFormatter(),
format.json()
),
transports: [new transports.Console({ format: format.errors({ stack: true }) })],
});
test('should log a basic message and tracetoken', () => {
// arrange - attach stream transport for assertions
const stream = new Writable();
const streamTransport = new winston.transports.Stream({ stream });
logger.add(streamTransport);
// arrange - write stream to string
let expectedOutput = '';
stream._write = (chunk, encoding, next) => {
expectedOutput += chunk;
next();
};
// act
const traceToken = v4();
logger.info('message', { traceToken });
// assert
expect(expectedOutput).toMatchJSON({ // jest-json matcher (basically just parsing stringified JSON)
traceToken,
timestamp,
message: 'message',
level: 'info',
});
}); |
* Different uncaughtException handling We've seen some uncaught exceptions where the process exits before logs are apparently flushed. This hopefully addresses that. Also start up sentry earlier, and catch top level exits differently. With ref to winstonjs/winston#1504 (comment) and https://nodejs.org/api/process.html#event-uncaughtexception
* Different uncaughtException handling We've seen some uncaught exceptions where the process exits before logs are apparently flushed. This hopefully addresses that. Also start up sentry earlier, and catch top level exits differently. With ref to winstonjs/winston#1504 (comment) and https://nodejs.org/api/process.html#event-uncaughtexception
* Different uncaughtException handling We've seen some uncaught exceptions where the process exits before logs are apparently flushed. This hopefully addresses that. Also start up sentry earlier, and catch top level exits differently. With ref to winstonjs/winston#1504 (comment) and https://nodejs.org/api/process.html#event-uncaughtexception
Please tell us about your environment:
winston
version?winston@2
winston@3
node -v
outputs: v10.10.0What is the problem?
File transport is not flushing on exit. Even when flushing per https://github.com/winstonjs/winston#awaiting-logs-to-be-written-in-winston
Steps to reproduce:
What do you expect to happen instead?
all messages (including THE LAST MESSAGE) should be written to the file.
The text was updated successfully, but these errors were encountered: