简体   繁体   English

尝试从npm用'log'包登录到Node.js文件

[英]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. 我希望通常使用console.log()记录的内容转到该文件。

edit: here's the context that I am using it in, as a minimal example. 编辑:这是我在其中使用的上下文,作为最小示例。 log.info() works fine outside of the while. log.info()可以在一段时间之外正常工作。 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. 您需要使用fs.appendFileSync()方法才能将内容同步添加到正在创建的日志中。

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. 软件包并非旨在记录Console.log()语句。 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. 因此,普通的console.log()也将相同的信息存储在其中。
Log package which you mentioned is used to create user defined logs of any type (info,debug,warning etc etc.). 您提到的日志包用于创建任何类型的用户定义的日志(信息,调试,警告等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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