PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label winston. Show all posts
Showing posts with label winston. Show all posts

Tuesday, November 15, 2022

[FIXED] Why error logs appears in warning logs file - Node.Js & Winston

 November 15, 2022     error-handling, node.js, winston     No comments   

Issue

In my Node.js REST API I am using Winston Logging to print the errors and info logs in a separated files. This is my Winston setup:

const { createLogger, format, transports } = require("winston");
const { timestamp, printf, errors } = format;

const logFormat = printf(({ level, message, timestamp, stack }) => {
  return `${timestamp} ${level}: ${stack || message}`;
});

const logger = createLogger({
  transports: [
    //new transports.Console(),
    new transports.File({
      level: "info",
      filename: "logsWarnings.log",
    }),
    new transports.File({
      level: "error",
      filename: "logsErrors.log",
    }),
  ],
  format: format.combine(
    timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
    format.json(),
    format.prettyPrint(),
    errors({ stack: true })
    //logFormat
  ),
  statusLevels: true,
});

module.exports = logger;

This is an example of one of my requests (info log is for req details):

deleteUser: (req, res) => {
    logger.info("This is an info log");
    mySqlConnection.query(
      "DELETE FROM Users WHERE user_id=?",
      req.params.userid,
      (err, rows) => {
        try {
          if (rows.affectedRows >= 1) {
            res.send("user deleted successfully");
          } else {
            res.status(500).send("Can't delete row");
          }
        } catch (err) {
          logger.error("this is error", { err });
        }
      }
    );
  },

I have a problem that error logs appears both in the error logs file and in the warning logs file. How can I fix it?


Solution

What is going on?

As mentioned in the documentation

Logging levels in winston conform to the severity ordering specified by RFC5424: severity of all levels is assumed to be numerically ascending from most important to least important.

const levels = { error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6 };

and

winston allows you to define a level property on each transport which specifies the maximum level of messages that a transport should log.

What that means? For example:

You used "info" level for logsWarnings.log file. it means that you are going to log itself and more important levels into the file (info, warn and error).

For logsErrors.log file you used "error" level. That means it will only log the error level logs because "error" has the highest importance.

That is why you are getting both in your logsWarnings.log file.

Solution:

You can separate logger like:

...
const formatConf = format.combine(
  timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
  format.json(),
  format.prettyPrint(),
  errors({ stack: true })
  //logFormat
);

const infoLogger = createLogger({
  transports: [
    //new transports.Console(),
    new transports.File({
      level: "info",
      filename: "./logs/logsWarnings.log",
    }),
  ],
  format: formatConf,
  statusLevels: true,
});

const errLogger = createLogger({
  transports: [
    new transports.File({
      level: "error",
      filename: "./logs/logsErrors.log",
    }),
  ],
  format: formatConf,
  statusLevels: true,
});
...

And use like:

errLogger.error("this is error", { err });
// or
infoLogger.info("This is an info log");

For more customization, please see the documentation.



Answered By - sh2a
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing