简体   繁体   中英

Trying to log to file on nodejs with 'log' package from npm

I'm not sure how I'm supposed to use this package . I've followed the example code from the docs:

var fs = require('fs')
  , Log = require('log')
  , log = new Log('debug', fs.createWriteStream('my.log'));

But then what? How do I send actual log info to the file? I want what normally gets logged with console.log() to go to the file.

edit: here's the context that I am using it in, as a minimal example. log.info() works fine outside of the while. As it is below, the file is created but has nothing in it.

var fs = require('fs')
var Log = require('log')
var log = new Log('info', fs.createWriteStream('my.log'));

while(true) {
    log.info("testing");
}
// (taken from readme of package)
log.debug('preparing email');
log.info('sending email');
log.error('failed to send email');

These will each log to the file you specified. The function denotes the log level, and is prepended to the data you provide.

You need to use fs.appendFileSync() method in order to add content synchronously to the log you are creating.

var fs require('fs')
,Log = require('log')
,log = new Log('debug', fs.createWriteStream('test.txt'));

log.debug('test test');
log.debug('test sadasd');
log.debug('test xcvxcv');
log.debug('test ewrewr');
log.debug('test hjgj');
log.debug('test fghfh');
log.debug('test yuiyui');

This package is not designed to log Console.log() statement. As per my knowledge every log file have date/time/(log type) and information related to it. So normal console.log() also have same info stored into it.
Log package which you mentioned is used to create user defined logs of any type (info,debug,warning etc etc.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM