简体   繁体   中英

How can I log my errors into a txt file AND the console in nodejs?

How can I log my errors into a txt file AND the console in nodejs?

I want to be able to keep all my errors in a text file.

It depends on what framework you want to use.

You can use Winston , which has the support for Transports - enabling you to create different outputs (file, tcp, stdout etc.) for your logs (based on level and other rules)

Use morgan

const fs = require('fs');
const morgan = require('morgan');

const logs = fs.createWriteStream(
  path.join(__dirname, 'logs.log'),
  { flags: 'a' }
);

app.use(morgan('combined', { stream: logs }));

In terms of pure Node.js functionality that works irrespective of frameworks or libraries, console.log() writes data to process.stdout , which is a stream that you can listen to. You can attach a listener function for the data event , and write console.log both to "the console" as well as to file that way.

Alternatively, you can pipe process.stdout into a file, but that's far more tricky to get right.

Also note that if you also yo log error output as well, you'll need to listen for data on process.stderr in addition to process.stdout .

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