Jo Ko
Jo Ko

Reputation: 7575

How to log issues to a file with NodeJS/ExpressJS?

I have my ReactJS and NodeJS/ExpressJS project up and running inside an instance. If there were to be a problem/error while the NodeJS is running, is there a way to report/write to a file in a particular directory to keep track of all the server issues?

For example, if it were to crash, it would write the error/issue to a file, so error logging to a file.

Thank you in advance and will accept/upvote answer.

Upvotes: 0

Views: 755

Answers (2)

JSEvgeny
JSEvgeny

Reputation: 2750

You can use morgan to do the magic.

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

app.use(logger('common', {
    stream: fs.createWriteStream('./access.log', {flags: 'a'})
}));

app.use(logger('dev'));

It will do both write into a file and show in console.

Ref to the answer

Upvotes: 3

Kacper Polak
Kacper Polak

Reputation: 1411

You can use Winston package with transport to and add it to middleware.

  winston.configure({
    transports: [
      new (winston.transports.File)({ filename: 'somefile.log' })
    ]
  });

Or just use express-winston

Upvotes: 0

Related Questions