68

What is best way to log my express js webserver? The inbuilt express.logger() just displays logs on screen. Can I also log them into a file in /log folder? Also the current logger automatically logs the request and responses. I need to log some application data into the log files. Can this be done using express.logger?

Regards, Lalith

1

8 Answers 8

74

To send the express or connect logs to a file use Node's writeStream. For example to send the express logs to ./myLogFile.log :

open the stream to your file in append mode with :

var logFile = fs.createWriteStream('./myLogFile.log', {flags: 'a'}); //use {flags: 'w'} to open in write mode

then, in your express config use after doing npm install morgan :

import morgan from 'morgan';
import express from 'express'
const app = express();
app.use(morgan('combined', { stream: logFile }));

should also work for connect.logger.

(Note: We have used import statement for declaring variable assuming user may put in their package.json "type": "module")

Sign up to request clarification or add additional context in comments.

3 Comments

ass express.logger is connect.logger it indeed does work. :)
express.logger is called morgan in express v4
Most middleware (like logger) is no longer bundled with Express and must be installed separately. Please see github.com/senchalabs/connect#middleware. We will have to use morgan as third party dependency
49

Look at the connect middleware that express extends. The express.logger() is the same as the connect.logger():

http://expressjs.com/api.html#middleware

http://www.senchalabs.org/connect/logger.html

The logger has a stream option that can be set where you want the output to go. By default it sends it to stdout. Also you can specify the log format you want to use.

6 Comments

Thanks Chad, This is exactly what I needed. It clearly gives response time for each connection.
Thanks, the link should be fixed now.
how do you do it inside a middleware function? I don't have access to express object
Also note that the logger should be placed before the router object in middleware ordering.
Since Express 4, the default express.logger has been replaced by Morgan
|
20

You should try winston

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({ filename: 'somefile.log' })
  ]
});

3 Comments

But express creates a /log folder. I thought they have built-in logging facility?
it does, but winston is more built out with async remote logging on top.
Best option if you need to log to a file and with json input. +1. Tried morgan also but liked winston better.
8

winston is kinda silly, multi-transport logging == tee(1), or just tail the file and transfer the data off, easy as pie

2 Comments

We're looking at Winston right now. Curious - is there something wrong with Winston's multi-logging approach? (I.e., a good reason we should avoid it?) And any criticisms of using the other features, which seem kind-of-useful prima facie, like meta-data, etc. ? Is there a reason not to use it
I just went through setting up logging using papertrail for a nodejs app.. i started off using winston to send express accesses through to paper trail, but then I ended up just setting express to use process.stdout and using tee to pipe to a file and logger syslog utility so I could have stdout, stderr stored locally as well as aggregated to papertrail, i found it to be a simpler setup but perhaps will change in the future.
8

Use log4js:

var log4js = require('log4js');
log4js.configure({
    appenders: [{type: 'console'},
                {type: 'file', filename: 'express.log', category: 'dev'}]
});

var logger = log4js.getLogger('dev');
logger.setLevel('DEBUG');

app.use(log4js.connectLogger(logger, {level: log4js.levels.DEBUG}));

Comments

6

For HTTP request logging: https://github.com/expressjs/morgan#write-logs-to-a-file

var express = require('express')
var fs = require('fs')
var morgan = require('morgan')

var app = express()

// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})

// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

1 Comment

Wondering if it also takes care of rotating the log files?
4

You could try cluster http://learnboost.github.io/cluster/ for Node. Use express to build the app, while the cluster takes over the rest of the tasks including logging.

  1. app.use(express.logger()); - in your express apps, ex: app.js
  2. cluster.use(cluster.logger('logs')); - in your cluster server, ex: server.js

Comments

1

For logging or debugging, Install winston package

npm i winston

Call package in this file

const { createLogger, transports, format } = require('winston');

const logger = createLogger({
  format: format.combine(
    format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }),
    format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
  ),
  transports: [
    new transports.File({
      filename: './logs/logs.log',
      json: false,
      maxsize: 5242880,
      maxFiles: 5,
    }),
    new transports.Console(),
  ]
});

Write this code where you want to debug, you can call different log like info, warn, error.

logger.info('some info log message');
logger.warn('some warn log message');
logger.error('some error log message');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.