67

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

Lalith
  • 19,396
  • 17
  • 44
  • 54

8 Answers8

73

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")

Clinto_92_Abraham
  • 333
  • 1
  • 3
  • 10
Did
  • 911
  • 7
  • 6
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.

Jeremy Worboys
  • 533
  • 3
  • 16
Chad Williams
  • 606
  • 5
  • 5
20

You should try winston

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({ filename: 'somefile.log' })
  ]
});
Shahbaz
  • 46,337
  • 19
  • 116
  • 182
generalhenry
  • 17,227
  • 4
  • 48
  • 63
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}));
elwarren
  • 327
  • 4
  • 8
8

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

tjholowaychuk
  • 3,026
  • 1
  • 21
  • 6
  • 3
    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 – Aneil Mallavarapu Apr 11 '12 at 22:55
  • 2
    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. – alex.pilon Oct 29 '13 at 21:15
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!')
})
neurosnap
  • 5,658
  • 4
  • 26
  • 30
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
zr0gravity7
  • 2,917
  • 1
  • 12
  • 33
Len Xu
  • 91
  • 1
  • 1
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');
Tyler2P
  • 2,324
  • 26
  • 22
  • 31