'How to categorize the log file based on current date?

currently I have log file where I am storing the log details. But I want to store the set of details on the every-day basis and it should generate the new file automatically.

    module.exports.log = log4js.configure({
    appenders: { log-info: { type: 'file', filename: 'logs/info.text'}},
    categories: { default: { appenders: ['log-info'], level: 'info' } }
});

I browsed through few stuffs, but I din't got any proper required info. Any link/advice, greatly appreciated.



Solution 1:[1]

I have use winston which work as your requirement. Create logs directory in your root folder and try this code

var winston = require('winston');
var path = require('path');
let __base = path.resolve(__dirname, '..');
var logger = new (winston.Logger)({
    levels: {
        error: 0,
        warn: 1,
        info: 2,
        debug :4 
    },
    transports: [
        new (winston.transports.Console)({
            prettyPrint: true,
            colorize: true,
            timestamp: true
        }),
        new (winston.transports.File)({
            name: 'errorLogger',
            filename: `${__base}/logs/log-${new Date().toLocaleDateString().replace(/\//g, '-')}.log`,
            colorize: true,
            /**
             *
             *
             * @returns
             */
            timestamp: function () {
                return (new Date().toLocaleString())
            }
        })
    ],
    colors: {
        info: "green",
        error: "red",
        warn: "yellow",
        debug: "blue"
    }
});

logger.level = 'info';
logger.info('Hello');
module.exports = logger;

After running this code you will see a file is generated in logs folder with Hello content.

You can also import this file in other file and use logger.info for printing and saving the logs

Solution 2:[2]

You can use the alwaysIncludePattern, just set it to true, like alwaysIncludePattern: true and dont forget to set the pattern with pattern: 'yyyy-MM-dd.log

const log4js = require("log4js");
logger = log4js.getLogger();

log4js.configure({
  appenders: {
    appender: {
      type: 'file',
      filename: 'log',
      keepFileExt: true,
      compress: true,
      pattern: 'yyyy-MM-dd.log',
      alwaysIncludePattern: true,
    },
  },
  categories: {
    default: {
      appenders: ['appender'],
      level: 'all',
    },
  },
});

logger.debug(`up and running`);

Filename: log.2022-01-26.log Content: [2022-01-26T14:44:32.769] [DEBUG] default - up and running

Source: Date Rolling File Appender

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 abdulbarik
Solution 2 MeerArtefakt