Skip to content
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 stops logger without any error message #1194

Closed
billiebbb opened this issue Jan 27, 2018 · 31 comments
Closed

transports.File stops logger without any error message #1194

billiebbb opened this issue Jan 27, 2018 · 31 comments

Comments

@billiebbb
Copy link

billiebbb commented Jan 27, 2018

I'm trying to use transports.File to save log file in loop with logger. After several logs print out it stops to write log to file and print nothing in console without any error message.

Here is my test code:

import winston from 'winston'

const winstonConfig = {
  level: 'debug',
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({
      filename:  'file/path/to/combined.log',
      maxsize: 10 * 1024 * 1024,
      maxFiles: 10
    })
  ]
}
let logger = winston.createLogger(winstonConfig)

for(let i=0; i<10000; i++){
  logger.debug(i)
}

Is it stdout buffer issue?

I'm using version 3.0.0-rc1 with node:8-alpine image in docker container

@beac0n
Copy link

beac0n commented Jan 27, 2018

I have the same problem. But for mit only occures, when I'm logging something really long

@billiebbb
Copy link
Author

I test this case on mac os. The same case in linux are working fine.

@beac0n
Copy link

beac0n commented Jan 28, 2018

I'm having this issue on Arch Linux. However, it works fine with wintston@2.4.0.

@bouchezb
Copy link

bouchezb commented Feb 9, 2018

Hi,

Same case here on a raspberry pi3 with

"winston": "^3.0.0-rc1",
"winston-daily-rotate-file": "^2.0.0-rc.2"

I have 3 DailyRotateFile loggers with differents levels and a console logger in dev env.
I'm also logging a lot of stuff.

pi@raspberry:~ $ ls -ltah ~/.botctl/logs/*09
-rw-r--r-- 1 pi pi 56M févr.  9 21:56 /home/pi/.botctl/logs/combined.log.2018-02-09
-rw-r--r-- 1 pi pi 56M févr.  9 21:56 /home/pi/.botctl/logs/silly.log.2018-02-09
-rw-r--r-- 1 pi pi   0 févr.  9 07:51 /home/pi/.botctl/logs/error.log.2018-02-09

My config is the following

const consoleFormat = winston.format.combine(
  winston.format.colorize(),
  winston.format.timestamp(),
  winston.format.align(),
  winston.format.splat(),
  winston.format.printf((info) => {
    const ts = info.timestamp.slice(0, 19).replace('T', ' ');
    if (info.args) {
      return `${ts} [${info.level}]: ${info.message} ${(info.level > 3 && (Object.keys(info.args).length || Object.getOwnPropertyNames(info.args).length)) ? JSON.stringify(info.args, null, 2) : ''}`;
    } else {
      return `${ts} [${process.pid}] [${info.level}]: ${info.message}`;
    }
  })
);

const fileFormat = winston.format.combine(
  winston.format.timestamp(),
  winston.format.align(),
  winston.format.splat(),
  winston.format.printf((info) => {
    const ts = info.timestamp.slice(0, 19).replace('T', ' ');
    if (info.args) {
      return `${ts} [${process.pid}] [${info.level}]: ${info.message} ${(Object.keys(info.args).length || Object.getOwnPropertyNames(info.args).length) ? JSON.stringify(info.args, null, 2) : ''}`;
    } else {
      return `${ts} [${process.pid}] [${info.level}]: ${info.message}`;
    }
  })
);

winston.addColors(logLevels);

const LOG_LEVEL = process.env.NODE_LOG_LEVEL || 'verbose';
const CONSOLE_LEVEL = process.env.NODE_CONSOLE_LEVEL || 'info';

const logger = winston.createLogger({
  level: LOG_LEVEL,
  levels: logLevels.levels,
  format: fileFormat,
  transports: [
    //
    // - Write all logs error (and below) to `error.log`.
    // - Write all silly logs (and below) to silly.log.
    // - Write all %level% logs (and below) to main.log
    //
    new DailyRotateFile({ filename: path.join(LOGS_DIR, 'error.log'), level: 'error', handleExceptions: true }),
    new DailyRotateFile({ filename: path.join(LOGS_DIR, 'silly.log'), level: 'silly' }),
    new DailyRotateFile({ filename: path.join(LOGS_DIR, 'combined.log'), level: LOG_LEVEL })
  ]
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: consoleFormat,
    colorize: true,
    level: CONSOLE_LEVEL
  }));
}
logger.exitOnError = false;

I have noticed that my file logger stops at 21:56 and my console logger continued until 22:43.
Since then nothing happen in logs or my modules.
I need to restart my services with cron to bypass the issue so far.

I also notice that the error file is empty.
I can't tell if the issue is linked with some specific actions in my programs.

How can i provide more traces related to winston ?
Can i provide a parameter to limit file size or rotate by hours instead of days ?

Thanks

@ericdrobinson
Copy link

ericdrobinson commented Feb 22, 2018

I just ran into the same issue as @bouchezb and my setup is effectively identical:

"winston": "^3.0.0-rc1",
"winston-daily-rotate-file": "^2.0.0-rc.2"

I similarly use Console and DailyRotateFile transports (although I only have a single DailyRotateFile open). The transports are almost entirely built of default settings.

The format settings I use are timestamp() and a custom formatter that makes use of printf as shown in the documentation.

Anyone have any ideas as to what's going on?

[I should note that I'm running my server process in a Node Docker container (currently at 7.8.0). When the issue appears, checking for open files does not show the expected log file. The expected log file does appear to be open when the process is restarted. Something, it seems, is causing the stream to be closed.]

@bouchezb
Copy link

Hi,

I haven't found a solution yet (better than cron restart).
I recently tried an hour rotation and the issue happens with higher frequency.
Probably during rotation process.

@ericdrobinson
Copy link

@bouchezb

Probably during rotation process.

Yes, I believe you're correct.

I noticed that it was possible to hook into the stream events in the main README.md:

You can listen to the open, close, error, and finish events generated by the underlying stream. You can also listen for the rotate custom event. The rotate event will pass two parameters to the callback (oldFilename, newFilename).

So... I implemented them:

// DEBUGGING.
rotateFileTransport.on('close', function () {
    console.trace("Transport Stream Closing?!");
});

rotateFileTransport.on('finish', function () {
    console.trace("Transport Stream Finished?!");
});

rotateFileTransport.on('error', function (err: Error) {
    console.trace("Error with Transport [Stream?]?!");
    console.dir(err);
});

rotateFileTransport.on('open', function (fd: any) {
    console.trace("Transport Stream Opened?!");
    console.dir(fd);
});

rotateFileTransport.on('rotate', function (oldFile: any, newFile: any) {
    console.trace("Rotating Files?!");
    console.dir(oldFile);
    console.dir(newFile);
});

[I used console.dir/trace in case it wasn't just the File writing Transport (winston-daily-rotate-file), but the entire Logger itself that failed.]

I then played the waiting game. At some point a log entry was triggered at 02:25 UTC and the following flow of output occurred:

Express Endpoint Processing Error

The following error occurred. The important part is the timestamp (specifically 02:25:29):

2018-02-23T02:25:29.691Z [error]: Stack: Error
    at DoWork (/app/site/server.js:95:33)
    at HandleEndpoint (/app/site/server.js:175:17)
    at Layer.handle [as handle_request] (/app/site/node_modules/express/lib/router/layer.js:95:5)
    at next (/app/site/node_modules/express/lib/router/route.js:137:13)
    at jsonParser (/app/site/node_modules/body-parser/lib/types/json.js:118:7)
    at Layer.handle [as handle_request] (/app/site/node_modules/express/lib/router/layer.js:95:5)
    at next (/app/site/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/app/site/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/app/site/node_modules/express/lib/router/layer.js:95:5)
    at /app/site/node_modules/express/lib/router/index.js:281:22

On Rotate Triggered

Up next is the Rotate event. The source is, unsurprisingly, here. This occurs after both destroy is called on the old writeStream and a new one is generated with fs.createWriteStream.

The filenames output were as expected.

Trace: Rotating Files?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:71:13)
    at emitTwo (events.js:106:13)
    at DailyRotateFile.emit (events.js:194:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:93:18)
    at emitTwo (events.js:111:20)
    at EventEmitter.emit (events.js:194:7)
    at Object.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:441:24)
    at DailyRotateFile.log (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:134:24)
    at DailyRotateFile.TransportStream._write (/app/site/node_modules/winston-transport/index.js:88:17)
    at doWrite (_stream_writable.js:329:12)
'/app/logs/2018-02-22-main.log'
'/app/logs/2018-02-23-main.log'

On Close Triggered

The starting point of this stack [fs.js:1973] looks a little odd at first (it's in a ReadStream function), but the WriteStream version merely points to the ReadStream one. My best guess here is that this triggered by destroy but somehow pushed to the next tick...?

This is the point that I started finding the reported call-stacks oddly equal in length. It turns out, there's a default stackTraceLimit that appears to be set to 10. Setting it to ∞ will remove the limit altogether. I will try updating my code to see if it helps provide further insights. In the meantime...

Trace: Transport Stream Closing?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:57:13)
    at emitNone (events.js:91:20)
    at DailyRotateFile.emit (events.js:188:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:77:18)
    at emitNone (events.js:86:13)
    at EventEmitter.emit (events.js:188:7)
    at WriteStream.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:497:15)
    at emitNone (events.js:86:13)
    at WriteStream.emit (events.js:188:7)
    at fs.js:1973:14

On Open Triggered

My best guess is that this was triggered by the call to createWriteStream that generated the new file. The file descriptor output (11) was the same file descriptor as the [theoretically?] just-closed file.

Trace: Transport Stream Opened?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:67:13)
    at emitOne (events.js:96:13)
    at DailyRotateFile.emit (events.js:191:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:89:18)
    at emitOne (events.js:96:13)
    at EventEmitter.emit (events.js:191:7)
    at WriteStream.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:506:15)
    at emitOne (events.js:101:20)
    at WriteStream.emit (events.js:191:7)
    at WriteStream.<anonymous> (fs.js:2043:10)
11

On Finish Triggered

I'm not entirely sure where this one came from, but it looks like finishMaybe is called once writing completes. Perhaps this occurs immediately after writing to the newly created file for the first time?

Trace: Transport Stream Finished?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:60:13)
    at emitNone (events.js:91:20)
    at DailyRotateFile.emit (events.js:188:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:81:18)
    at emitNone (events.js:86:13)
    at EventEmitter.emit (events.js:188:7)
    at WriteStream.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:500:15)
    at emitNone (events.js:91:20)
    at WriteStream.emit (events.js:188:7)
    at finishMaybe (_stream_writable.js:510:14)

On Close Triggered [again]

This is the same callstack (top) as the last Closed event. My guess is that this is now the new file being closed. It seems that it's opened, written to once, and then immediately finalized and closed. This obviously isn't correct. No idea at present why this occurs (and am not 100% confident in this analysis).

Trace: Transport Stream Closing?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:57:13)
    at emitNone (events.js:91:20)
    at DailyRotateFile.emit (events.js:188:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:77:18)
    at emitNone (events.js:86:13)
    at EventEmitter.emit (events.js:188:7)
    at WriteStream.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:497:15)
    at emitNone (events.js:86:13)
    at WriteStream.emit (events.js:188:7)
    at fs.js:1973:14

In the first part of this breakdown I showed the timestamp reported by the event (02:25:29). When listing the files in the log directory, I see the following:

-rw-r--r-- 1 root root  865 Feb 23 02:25 2018-02-23-main.log

The important bit is the last modified time field: 02:25. It appears that the file is opened, written to, and then immediately closed. This is all triggered during the first event when file rotation occurs.

I suspect that the same thing (or very similar) may be happening for people using the main File Transport.

At this point I wish I'd added some timestamps to the logging. I'll add that and remove the stack trace limits to see what extra information I can glean from these events.

@ericdrobinson
Copy link

At this point I wish I'd added some timestamps to the logging. I'll add that and remove the stack trace limits to see what extra information I can glean from these events.

I made those adjustments and modified some settings to make the file rotation occur every 2 minutes (and set FileStreamRotator to verbose). I immediately reproduced the issue.

Here is what I got as output:

On Open Triggered

This is the initial file opening event. The number (11) at the end is the file descriptor of the opened log file.

Trace: [2018-02-23T20:39:39.886Z] Transport Stream Opened?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:67:13)
    at emitOne (events.js:96:13)
    at DailyRotateFile.emit (events.js:191:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:89:18)
    at emitOne (events.js:96:13)
    at EventEmitter.emit (events.js:191:7)
    at WriteStream.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:506:15)
    at emitOne (events.js:101:20)
    at WriteStream.emit (events.js:191:7)
    at WriteStream.<anonymous> (fs.js:2043:10)
    at FSReqWrap.oncomplete (fs.js:114:15)
11

Log Event

One log event was triggered.

2018-02-23T20:42:01.493Z [info]: Received Request.

File Rotation Event

That log event triggered the logic for the file rotation (I had waited more than the requisite 2min for file rotation). The first line is some of FileStreamRotator's verbose output.

2018-02-23T20:42:01.493Z '[FileStreamRotator] Changing logs from %s to %s' '/app/logs/201802232038-main.log' '/app/logs/201802232042-main.log'
Trace: [2018-02-23T20:42:01.494Z] Rotating Files?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:71:13)
    at emitTwo (events.js:106:13)
    at DailyRotateFile.emit (events.js:194:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:93:18)
    at emitTwo (events.js:111:20)
    at EventEmitter.emit (events.js:194:7)
    at Object.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:441:24)
    at DailyRotateFile.log (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:134:24)
    at DailyRotateFile.TransportStream._write (/app/site/node_modules/winston-transport/index.js:88:17)
    at doWrite (_stream_writable.js:329:12)
    at writeOrBuffer (_stream_writable.js:315:5)
    at DailyRotateFile.Writable.write (_stream_writable.js:241:11)
    at DerivedLogger.ondata (_stream_readable.js:557:20)
    at emitOne (events.js:101:20)
    at DerivedLogger.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at DerivedLogger.Readable.push (_stream_readable.js:136:10)
    at DerivedLogger.Transform.push (_stream_transform.js:128:32)
    at DerivedLogger._transform (/app/site/node_modules/winston/lib/winston/logger.js:218:8)
    at DerivedLogger.Transform._read (_stream_transform.js:167:10)
    at DerivedLogger.Transform._write (_stream_transform.js:155:12)
    at doWrite (_stream_writable.js:329:12)
    at writeOrBuffer (_stream_writable.js:315:5)
    at DerivedLogger.Writable.write (_stream_writable.js:241:11)
    at DerivedLogger.log (/app/site/node_modules/winston/lib/winston/logger.js:150:10)
    at /app/site/build/search.js:55:37
    at step (/app/site/build/search.js:38:23)
    at Object.next (/app/site/build/search.js:19:53)
    at /app/site/build/search.js:13:71
    at __awaiter (/app/site/build/search.js:9:12)
    at DoAsyncAwaitStuff (/app/site/build/search.js:50:12)
    at Layer.handle [as handle_request] (/app/site/node_modules/express/lib/router/layer.js:95:5)
    at next (/app/site/node_modules/express/lib/router/route.js:137:13)
    at /app/site/node_modules/body-parser/lib/read.js:130:5
    at invokeCallback (/app/site/node_modules/raw-body/index.js:224:16)
    at done (/app/site/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/app/site/node_modules/raw-body/index.js:273:7)
    at emitNone (events.js:86:13)
    at IncomingMessage.emit (events.js:188:7)
    at endReadableNT (_stream_readable.js:975:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
'/app/logs/201802232038-main.log'
'/app/logs/201802232042-main.log'

More Log Events

Two more log events were triggered. They are downstream of (were triggered by) the previous log event.

2018-02-23T20:42:01.506Z [info]: Async processing 1...
2018-02-23T20:42:01.533Z [info]: Async processing 2...

On Close Triggered

The close event was triggered, 68ms after the last log statement.

Trace: [2018-02-23T20:42:01.601Z] Transport Stream Closing?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:57:13)
    at emitNone (events.js:91:20)
    at DailyRotateFile.emit (events.js:188:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:77:18)
    at emitNone (events.js:86:13)
    at EventEmitter.emit (events.js:188:7)
    at WriteStream.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:497:15)
    at emitNone (events.js:86:13)
    at WriteStream.emit (events.js:188:7)
    at fs.js:1973:14
    at FSReqWrap.oncomplete (fs.js:114:15)

On Open Triggered

The open event was triggered 1ms later. Note that the file descriptor is the same.

Trace: [2018-02-23T20:42:01.602Z] Transport Stream Opened?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:67:13)
    at emitOne (events.js:96:13)
    at DailyRotateFile.emit (events.js:191:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:89:18)
    at emitOne (events.js:96:13)
    at EventEmitter.emit (events.js:191:7)
    at WriteStream.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:506:15)
    at emitOne (events.js:101:20)
    at WriteStream.emit (events.js:191:7)
    at WriteStream.<anonymous> (fs.js:2043:10)
    at FSReqWrap.oncomplete (fs.js:114:15)
11

On Finish Triggered

The finish event was triggered 12ms after open.

Trace: [2018-02-23T20:42:01.614Z] Transport Stream Finished?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:60:13)
    at emitNone (events.js:91:20)
    at DailyRotateFile.emit (events.js:188:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:81:18)
    at emitNone (events.js:86:13)
    at EventEmitter.emit (events.js:188:7)
    at WriteStream.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:500:15)
    at emitNone (events.js:91:20)
    at WriteStream.emit (events.js:188:7)
    at finishMaybe (_stream_writable.js:510:14)
    at afterWrite (_stream_writable.js:384:3)
    at onwrite (_stream_writable.js:374:7)
    at fs.js:2110:5
    at FSReqWrap.wrapper [as oncomplete] (fs.js:2077:5)

On Close Triggered

The close event was triggered again, 10ms after the last open.

Trace: [2018-02-23T20:42:01.624Z] Transport Stream Closing?!
    at DailyRotateFile.<anonymous> (/app/site/build/logger.js:57:13)
    at emitNone (events.js:91:20)
    at DailyRotateFile.emit (events.js:188:7)
    at EventEmitter.<anonymous> (/app/site/node_modules/winston-daily-rotate-file/daily-rotate-file.js:77:18)
    at emitNone (events.js:86:13)
    at EventEmitter.emit (events.js:188:7)
    at WriteStream.<anonymous> (/app/site/node_modules/file-stream-rotator/FileStreamRotator.js:497:15)
    at emitNone (events.js:86:13)
    at WriteStream.emit (events.js:188:7)
    at fs.js:1973:14
    at FSReqWrap.oncomplete (fs.js:114:15)

[Note]

Several events quickly followed (<200ms) the final close event report. Those events were not written to the log file - only the three log messages shown above made it into the new log file.


Removing the limit on call stack depth didn't reveal much extra with respect to the open/close/finish event callbacks. The rotate event, however, revealed quite a bit of information. Perhaps it would be helpful to someone who understands how Winston injects itself into the standard NodeJS Stream handling?

@indexzero, any thoughts here? If you've not seen these Issues yet, it seems that any Transport that attempts to close one file stream and open another (as the core File Transport does when you set a max size) will open the new file stream in such a manner that it is immediately closed. Is there a test that covers this scenario? This feels like a pretty serious showstopper for 3.0.0...

@ericdrobinson
Copy link

One more note: I have been testing with Node 7.8.0. The file names and line numbers in the call stacks in my last two posts will resolve correctly with files in this commit of the main NodeJS repo.

@ericdrobinson
Copy link

@bouchezb The winston-daily-rotate-file issue was identified and has been solved! Give it a shot by installing winston-daily-rotate-file@next.

While this good news is specifically related to the winston-daily-rotate-file Transport and not the File Transport, the issue that affected winston-daily-rotate-file could also be affecting the File Transport.

@billiebbb and @beac0n two questions for you:

  1. What versions of node/npm are you running?
  2. Can you tell if the logger stops working after a file rotation occurs?

I ask the second question because internal stream event bubbling with winston-daily-rotate-file is what caused the Transport to close and unpipe itself. This happened during the file rotation process. Some logs might make it into the newly created file before it was closed if they were reported quickly enough. Given the tight loop in @billiebbb's example code, it might be the case that those logs are buffered and then several files created before the File transport has some time to react to its first internal file sending an "I'm done" message (close or finish or something...).

@bouchezb
Copy link

bouchezb commented Mar 5, 2018

@ericdrobinson thanks for the fix.
I did the update but i'm still experiencing some issues.
I think this is more related to winston core module than winston-daily-rotate-file because crashes seems now to occur in a more random way than before.
I'll open a ticket if i can find some new revelant clues.
Thanks again for your support.
Regards.

@ericdrobinson
Copy link

ericdrobinson commented Mar 5, 2018

I think this is more related to winston core module than winston-daily-rotate-file because crashes seems now to occur in a more random way than before.
I'll open a ticket if i can find some new revelant clues.

That would probably be best. This issue is specifically about the File transport stopping the logger. Crashes would be another issue and it would be good to open a different issue (or comment on one that already exists) to keep the conversation focused.

@indexzero What settings/event registrations would you recommend adding when attempting to figure out issues in winston@3?

rcoedo pushed a commit to rcoedo/winston that referenced this issue Mar 15, 2018
rcoedo pushed a commit to rcoedo/winston that referenced this issue Mar 15, 2018
@dgotrik
Copy link

dgotrik commented Apr 10, 2018

Also seeing this issue on 3.0.0-rc3

I run the application and it works fine for some time, but then it fails to log to console or the log files with no exception or error generated - a "silent fail"

Is there any work being done on this?

@jansteuer
Copy link

@rcoedo commit fixes the issue but there is still an issue with formatting which I think is related to this.

const winston = require('winston')

const winstonConfig = {
  level: 'debug',
  transports: [
    new winston.transports.Console({
      format: winston.format.printf(info => `${info.level}: ${info.message}`)
    }),
    new winston.transports.File({
      filename: 'winston.log',
      maxsize: 10 * 1024 * 1024,
      maxFiles: 10,
      format: winston.format.printf(info => `${info.level}: ${info.message}`)
    })
  ]
}
const logger = winston.createLogger(winstonConfig)

for (let i = 0; i < 10000; i++) {
  logger.debug(i)
}

Produces this output to a file:

....
debug: 2600
debug: 2601
debug: 2602
debug: 2603
debug: 2604
debug: 2605
debug: 2606
{"message":2607,"level":"debug"}
{"message":2608,"level":"debug"}
{"message":2609,"level":"debug"}
{"message":2610,"level":"debug"}
{"message":2611,"level":"debug"}
{"message":2612,"level":"debug"}
{"message":2613,"level":"debug"}
{"message":2614,"level":"debug"}
{"message":2615,"level":"debug"}
{"message":2616,"level":"debug"}
{"message":2617,"level":"debug"}
{"message":2618,"level":"debug"}
{"message":2619,"level":"debug"}
{"message":2620,"level":"debug"}
{"message":2621,"level":"debug"}
debug: 2622
debug: 2623
debug: 2624
debug: 2625
debug: 2626
debug: 2627
debug: 2628
.....

Output in the console is formatted correctly.

@rcoedo
Copy link

rcoedo commented Apr 13, 2018

@jansteuer I can reproduce the behavior. When the stream.write tell us to wait for the drain event, the following 15 lines receive a non formatted message for some reason. I tried to find why but I failed.

I believe this is related to how the Logger handles the transports but I'm not sure. Maybe someone with some expertise in winston can guide us to finally fix the file transport 😃

@dgotrik
Copy link

dgotrik commented Apr 19, 2018

I implemented @rcoedo's fix, and the logger seemed stable for a few days, but today all of the logging for my application disappeared. There are no exceptions generated anywhere that I can see, and I can't find a way to reproduce it. Anybody at WinstonJS have an idea?

The current workaround I am trying is to forcibly delete and reinstantiate the logger every 30 minutes.

@ejaweb
Copy link

ejaweb commented May 3, 2018

Hi Everyone, my team is also able to reproduce this issue with the latest version of winston@3.0.0-rc5.

It's strange because when we first initialize our logger and run our application, everything is fine, or it seems... We log every time we receive a message from IBM MQLight and we noticed once around 600 messages (both from console and physical log file) winston inexplicably stops even though the application continues to run, just no logging at all?...

We know the issue is coming from Winston because we modified this bit of code in our custom logging class library that instantiates our logger to use fs.createWriteStream instead of Winston and it always works:

import { createLogger, format, transports } from "winston";

// ... inside the class ...
this.logger = createLogger({
            exitOnError: false,
            format: format.json(),
            transports: [
                new transports.File({
                    tailable: true,
                    zippedArchive: false,
                    handleExceptions: true,
                    filename: path.resolve(options.logDir, options.fileName),
                    maxsize: options.maxsize,
                    maxFiles: options.maxFiles
                })
            ]
 });
const write = (msg) => {
    this.logger.info(msg);
};

- vs -

import * as fs from "fs";

// ... inside the class ...
this.logger = fs.createWriteStream(path.resolve(options.logDir, options.fileName));
const write = (msg) => {
    this.logger.write(JSON.stringify(msg) + "\n");
};

Does anyone have any solution as to why Winston stops randomly?

@ericdrobinson
Copy link

Is it possible that this is related to #1144? That was fixed 8 days ago or so and merged into master 9 in PR #1291. On the other hand, winston@3.0.0-rc5 was released before that (13 days ago).

Perhaps test against master?

@ejaweb
Copy link

ejaweb commented May 4, 2018

@ericdrobinson Hmm, I was really hopeful.... I pulled the latest version from master in Winston as you recommended about an hour ago then manually dropped that version and referenced it in my code directly. Sadly, I received the same results.

My test involved dumping 10000 messages at <5ms. After about 700 or 800 received and logged messages, Winston logging for file and console stopped. So I went into my logger class to again use my own little version of fs.createWriteStream (shown in my previous comment) and ran the exact same test, results showed that precisely 10000 messages were logged.

Does Winston close the stream or something? The only difference I can see I'm doing with my little version of fs.createWriteStream in my test, is that I never close my stream or have any drain management.

@ericdrobinson
Copy link

@ejaweb I've no idea. You could start digging into this yourself by adding some debug logging to your Winston setup to begin tracking things down. I did this previously for a different bug that was apparently specific to winston-daily-rotate-file. Here's the description of what I did. Note that you'll want to set your stack trace limit to Infinity to properly see the full context within which you get your callbacks.

This bug report is missing good debug info from someone using the File Transport. My comments turned out to be related to a different issue.

As you have a 100% repro-case, perhaps you could add in some debug output and provide further context?

@ejaweb
Copy link

ejaweb commented May 6, 2018

@ericdrobinson Oh man interesting news! Before I decided to make any additional changes to my code (to start tracking down the bug), I decided to try winston-daily-rotate-file to see if I could re-produce the same error... I can't!!! It seems both the latest versions of master for winston and winston-daily-rotate-file contains the fix because it works perfectly! I tested multiple times as well. I think for now my team will be using this instead of winston's default Transports.File. Thanks!

@ericdrobinson
Copy link

@indexzero Shouldn't this issue be Closed now? It's referenced as "Fixed" in the release notes for rc6...

@rcoedo
Copy link

rcoedo commented Jun 27, 2018

I think this still happens when using the tailable: true option.

@dlarr
Copy link

dlarr commented Jul 9, 2018

I had same issue, today. What happened for me is the follwing

  • Transport Console
  • Transport File

In my project I had deleted the folder containing the log files.

In that case, winston was correctly logging stuff until it get to a specific point in the console! Always the same, don't know why.

I fixed this by creating the containing folder. As soon as winston found a file to write in, console output was back to normal.

Hope this helps.

ledbit added a commit to diag/winston that referenced this issue Jul 26, 2018
@hubiierik
Copy link

@dlarr Yes I have observed the same thing myself. It seems to be caused by missing error handling code in winston. By my reckoning, when the file stream cannot be created because the parent folder is missing, the file transport is allowed to continue in a zombie state until the PassThrough fills up. At the end a pause() is called and waits for a drain that will never happen.

@hubiierik
Copy link

In the particular case of @dlarr and me error handling in file.js!_createStream() and file.js!stat() should probably be looked at.

@hubiierik
Copy link

In our project we have a derived logger that creates a Console transport and a File transport. If the logger is run in an environment where the parent folder of the file transport is missing, the logger stops logging as described above. Also the Console transport stops. Our workaround is to not let our derived logger to create the file transport if the parent folder of the log file is missing.

DABH pushed a commit that referenced this issue Aug 27, 2018
* fix issue #1194 - where rotation of files isn't done when tailable is set to true

* more fixes to tail rolling + fix & enable unit tests

* fix unit tests interference from 01-file-maxsize - not sure why a new file gets created on an unrelated transport when adding a new Transport

* Update 01-file-maxsize.test.js

* Update file.js
@DABH
Copy link
Contributor

DABH commented Aug 27, 2018

Hopefully the case of tailable: true has also been fixed now, thanks to #1420. If someone could confirm or deny, testing against master, that would be awesome — would love to see this issue closed. The aforementioned fix will go out in the next release, which hopefully should be published very soon.

@satyabratasaha-me
Copy link

satyabratasaha-me commented Sep 2, 2018

I can confirm , the fix in master branch is working fine after setting tailable flag to true. Looking forward someone to publish this in npm.
tailable: true

@DABH
Copy link
Contributor

DABH commented Sep 11, 2018

Going to go ahead and close this at last (3.1.0 was pushed to npm recently), but if anyone can reliably reproduce issues with the core File transport (or other core transports), please open a new issue and we'll work to get to the bottom of it. Thanks to everyone who contributed to documenting and solving this issue!

@DABH DABH closed this as completed Sep 11, 2018
Mizumaki pushed a commit to Mizumaki/winston that referenced this issue Jun 11, 2020
* fix issue winstonjs#1194 - where rotation of files isn't done when tailable is set to true

* more fixes to tail rolling + fix & enable unit tests

* fix unit tests interference from 01-file-maxsize - not sure why a new file gets created on an unrelated transport when adding a new Transport

* Update 01-file-maxsize.test.js

* Update file.js
@ChrisMiami
Copy link

So, I'm using Winston 3.10.0 and Winston-daily-rotate-file 4.7.1 and have run into an issue very similar to this. My app has 5 asynchronous tasks to perform at startup and just as it's getting going, the logs stop abruptly. Console is not affected, but in production I don't keep console running. I had hoped that the daily rotate would trigger a reset and the logs would start being written, but this didn't happen. It's technically intermittent but only because it doesn't happen sometimes. I'm revving to Winston 3.11.0.

Does anyone have any ideas how to debug this? If I turn off tailable will that help? I find files on Windows don't tail anyway, and I have a final flush before the app quits so maybe that's not a big loss.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests