Home > Mobile >  loggers and logging in nodejs what is should be like?
loggers and logging in nodejs what is should be like?

Time:11-22

I'm studying the loggers and logging subject for first time.. and I'm trying to create it via nodejs application after watching some tutorials .

after I did it I found all tutorials that do it in index.js file .. it's smth like

logger.warn('text warn')
logger.error('text error')
logger.error(new Error('smth wrong here'))

but what I studied was I should print system logs, if it has warn or any issues. how can I do it? and if I want to save these details in text file it will be better?

CodePudding user response:

you can look at packages like Winston or Pino for logging any kind of level of information for your server. This is better and saves you a lot of time.

CodePudding user response:

Your question is not very clear, but I assume you would like to know how to use a logger module.

I'm using winston. It is fairly easy to use and the documentation is very clear. All you need is to create your own logger which is done by using the createLogger function. There're many options you can use to configure your logger so you will just need to read the documentation.

Here is an example of how I use it in my projects, exporting the logger and then using it in the app:

logger.js:

const { addColors, transports, format, createLogger } = require("winston");
const { combine, colorize, simple, prettyPrint } = format;

const logLevels = {
  levels: { critical: 0, error: 1, warning: 2, debug: 3, info: 4 },
  colors: {
    critical: "bold magenta",
    error: "bold red",
    warning: "bold yellow",
    info: "bold blue",
    debug: "bold green",
  },
};

addColors(logLevels.colors);

const transport =
  process.env.NODE_ENV === "production"
    ? new transports.Console({
        format: combine(colorize(), simple()),
      })
    : new transports.File({ filename: "file.log" });

const logger = createLogger({
  levels: logLevels.levels,
  format: prettyPrint(),
  transports: [transport],
});

module.exports = logger;

app.js:

const logger = require("./logger");
logger.log({ level: "info", message: "info log" });
  • Related