DEV Community

korey 🇳🇬
korey 🇳🇬

Posted on

FILE LOGGING IN NODEJS

LOGGING IN NODEJS.

The problem

Keeping the interaction history with the application is quite important in every application if we don't keep the logs the following occurs

  1. We are unable to track errors on production and their causes
  2. We are unable to monitor our system and be sure if some bugs or some functionality our users complain of is true.
  3. We are unable to obtain the transaction history with the application.

LOGGING CONFIGURATION

npm i winston
npm i app-root-path
Enter fullscreen mode Exit fullscreen mode

we create a logger.js file and add the following

import  *  as  winston  from  'winston';
import  'winston-daily-rotate-file';
import  appRoot  from  'app-root-path';

const  logger = winston.createLogger({
    transports: [
        new  winston.transports.DailyRotateFile ({
        filename:  'application-%DATE%.log',
        dirname:  `${appRoot}/logs/`,
        level:  'info',
        handleExceptions:  true,
        colorize:  true,
        json:  false,
        zippedArchive:  true,
        maxSize:  '20m',
        maxFiles:  '14d'
    })
],exitOnError:  false});

export  default  logger;
Enter fullscreen mode Exit fullscreen mode

For the above, we configured the logs to do the following

  • create a new instance of the Winston logger
const  logger = winston.createLogger({})
Enter fullscreen mode Exit fullscreen mode
  • We configured new transport which is the medium we want to use to log our file called winston.transports.DailyRotateFile, our transport can also be to the console. we set our transport attributes to the following
    transports: [
        new  winston.transports.DailyRotateFile ({
        filename:  'application-%DATE%.log',
        dirname:  `${appRoot}/logs/`,
        level:  'info',
        handleExceptions:  true,
        colorize:  true,
        json:  false,
        zippedArchive:  true,
        maxSize:  '20m',
        maxFiles:  '14d'
    })
Enter fullscreen mode Exit fullscreen mode
  • log file will be created with name application-date.log
  • logs will be saved into a log folder in our root directory
  • Each log file will contain the loggs of the application in a day
  • After a day the log file will be zipped to keep our growing file system in check
  • After 14days we'll configure our logs to be archived.

For the winston logger we have various log level which are

const  levels  =  { 
 error:  0, 
 warn:  1, 
 info:  2, 
 verbose:  3, 
 debug:  4, 
 silly:  5 
};
Enter fullscreen mode Exit fullscreen mode

If any level is chosen the logger will log errors less than or equal to this level.

In the Entry of the application, we add the logger to the error middleware to enable all request and response and error to be logged in the application

import  logger  from  './logger.js';

app.use((err, req, res, next) => {
logger.error(`${err.status || 500} - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
res.status(500).send('server error, this will be resolved shortly!')
})
Enter fullscreen mode Exit fullscreen mode

we can optionally add our logger to our controller to log errors

we create a separate file called serverResponse

import  logger  from  './logger';
/**
* @name  serverResponse
* @param  {Object}  res express response object
* @param  {Number}  code status code to return
* @param  {Ojectb}  data object with response details
* @returns  {JSON} JSON response with status and response information
*/
const  serverResponse = (req, res, code, data) => {
logger.info(`${req.originalUrl} - ${req.method} - ${req.ip}
- ${code} - ${JSON.stringify(data)}
`);
res.status(code).json({ ...data });
}

export default serverResponse;

Enter fullscreen mode Exit fullscreen mode

This file will be used as a helper in our application to return our responses at the same time log the response to prevent repetitive code in the codebase.

Below is how it can be used in a typical controller

import  serverResponse  from  './serverResponse';
class  Auth {
/**
* @static
* @param  {JSON}  req
* @param  {JSON}  res
* @memberof  Auth
*/
static  async  login (req, res) {
serverResponse(req, res, 200, {msg: 'login successful'});
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
roser137 profile image
roser137 • Edited

what does json:false do in configuration? I couldn't find anything in docs or source

Collapse
 
adeyemiadekore2 profile image
korey 🇳🇬 • Edited

I think this has to do with expecting your output logs in json format.
you could see this in the type definition of DailyRotateFile as shown in the image attached.

dev-to-uploads.s3.amazonaws.com/up...

Collapse
 
adeyemiadekore2 profile image
korey 🇳🇬

Thanks to everyone who gave feedbacks on this.
A PR has been made to make get started easily in .js and .ts

github.com/winstonjs/winston-daily...

Collapse
 
adeyemiadekore2 profile image
korey 🇳🇬

Hello @kedei01 kindly provide more details or a screenshot of the issue so I can be able to help

Collapse
 
kedei01 profile image
kedei01

the daily rotate file keeps showing undefined....please help!