How to categorize the log file based on current date? - node.js

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.

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

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

Related

node log4j No output from the console

app.js :
const log4js = require('log4js');
log4js.configure({
appenders: { app: { type: 'dateFile', filename: './log/', pattern: 'yyyy-MM-dd.log', alwaysIncludePattern: true } },
categories: { default: { appenders: ['app'], level: 'trace' } }
});
const Logger = log4js.getLogger('app');
Logger.level = 'trace';
Logger.error('log4js start.');
run
node app.js
No output from the console, But the file has a record
and. Log file name: log.2020-02-08.log, Instead of what I expected ./log/2020-02-08.log
I don't understand the documentation a bit, hope to help me correct my configuration
There is a documentation for output to console: https://github.com/log4js-node/log4js-node/blob/master/docs/console.md.
This is my snippet after appending one more config:
const log4js = require("log4js");
log4js.configure({
appenders: {
app: { type: 'dateFile', filename: './log/', pattern: 'yyyy-MM-dd.log', alwaysIncludePattern: true },
console: { type: "console" }
},
categories: { default: { appenders: ["app", "console"], level:

log4js is not working in node , How to configure it...?

I have installed log4js npm and try to implement logger to my node api...
I am trying to use log4js for the first time.
Code:
var log4js = require('log4js'); // include log4js
log4js.configure({ // configure to use all types in different files.
appenders: [
{ type: 'file',
filename: "/logs/error.log", // specify the path where u want logs folder error.log
category: 'error',
maxLogSize: 20480,
backups: 10
},
{ type: "file",
filename: "/logs/info.log", // specify the path where u want logs folder info.log
category: 'info',
maxLogSize: 20480,
backups: 10
},
{ type: 'file',
filename: "/logs/debug.log", // specify the path where u want logs folder debug.log
category: 'debug',
maxLogSize: 20480,
backups: 10
}
]
});
var loggerinfo = log4js.getLogger('info'); // initialize the var to use.
var loggererror = log4js.getLogger('error'); // initialize the var to use.
var loggerdebug = log4js.getLogger('debug'); // initialize the var to use.
loggerinfo.info('This is Information Logger');
loggererror.info('This is Error Logger');
loggerdebug.info('This is Debugger');
I got error:
****throw new Error(`Problem with log4js configuration: (${util.inspect(config, { depth: 5 })})`
^
Error: Problem with log4js configuration: ({ appenders:
[ { type: 'file',
filename: '/logs/error.log',
category: 'error',
maxLogSize: 20480,
backups: 10 },
{ type: 'file',
filename: '/logs/info.log',
category: 'info',
maxLogSize: 20480,
backups: 10 },
{ type: 'file',
filename: '/logs/debug.log',
category: 'debug',
maxLogSize: 20480,
backups: 10 } ] }) - must have a property "appenders" of type object.****
I have run a log4js sample code in my application using cmd node log4js.js(this file name)
Please help me...
I have this.
File name: myHelperlog4js.js
const { configure, getLogger } = require("log4js");
configure({
appenders: {
console: { type: 'console' ,"layout": { "type": "pattern", "pattern": "%d - %c:[%p]: %m" }},
fileLog: { type: 'file', filename: '/logs/application.log' }
},
categories: {
default: { appenders: ['console','fileLog'], level: 'trace' },
}
});
const logger = getLogger();
module.exports = {logger};
in your file to use, have this:
const {logger } = require('MY PAHT OF MY JS CONFIGURED/myHelperlog4js');
and for use only:
logger.info(msg);
logger.info(msg);
logger.debug(msg);
logger.info(msg);
logger.warn(msg);
logger.error(msg);
logger.fatal(msg);
logger.info(msg);
/logs/application.log: save log in:
Windows (C:/logs/)
linux (/logs/)

log4js appenders with different levels of logging levels

I'm trying to create a logger configuration which logs only "ERROR" level information to console and "DEBUG" level information to file appenders.
Can anyone help on how to create a logger with above config?
Thanks in advance. Help is very much appreciated
var log4js = require('log4js');
log4js.configure({
appenders: {
everything: { type: 'stdout' },
file_log: { type: 'file', filename: 'anyPath/all-logs.log' },
logLevelFilter: {
type: 'logLevelFilter',
level: 'debug',
appender: 'file_log',
},
},
categories: {
default: {
appenders: ['logLevelFilter', 'everything'],
level: 'all',
},
},
});
const logger = log4js.getLogger();
in this example all logs will be shown in the console , but only debug level and above will be add to file (in this example file located in 'Logs_and_others/all-the-logs.log')
For ERROR in console, you can directly have console.log statements. For DEBUG, you can add that in your config feel like below-
const log4js = require('log4js'); // include log4js
log4js.configure({
appenders: { app: { type: 'file', filename: 'app.log' } },
categories: { default: { appenders: ['app'], level: 'debug' } }
});
const logger = log4js.getLogger('app');
logger.debug('Your debug message');
You need to provide the level category inside categories in your config file.
Hope this should help.

How add two or more logger using different files?

I am working on node Js logging library. I am using winston for this.I created log files but I stuck when I want to create two log files.Suppose I have to create all log file which contain all logs and error log file which contain only error logs.But I stuck here:
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const tsFormat = () => (new Date()).toLocaleTimeString();
let logger = new(winston.Logger)({
transports: [
new(winston.transports.Console)({
level: 'debug',
timestamp: tsFormat,
handleExceptions: true,
colorize: true,
json: false
}),
new(winston.transports.File)({
name: 'all-file',
handleExceptions: true,
filename: `${logDir}/all-file.log`,
level: 'debug',
maxsize: 100000000,
json: true
}),
new(winston.transports.File)({
name: 'error-file',
handleExceptions: true,
filename: `${logDir}/error-file.log`,
level: 'error',
maxsize: 100000000,
json: false
})
]
});
I want that error log show different type of console than debug console.But by default its only taking debug one. how can I manually add console config for both files.When I try to add another transport.console it shows error.
Transport already attached: console, assign a different name
var winston = require('winston');
let consoleLogger = function(options){
return new (winston.Logger)({
transports: [
new (winston.transports.Console)(options),
]
});
}
// the CustomTransport is to prevent error log show multiple times
class CustomTransport extends winston.Transport {
constructor(options) {
super(options);
this.options = options;
this.levels = options && options.levels || [this.level];
}
log(level, msg, meta, callback) {
if(this.levels.indexOf(level) > -1){
consoleLogger(this.options)[level](msg, meta);
}
callback(null, true);
}
}
winston.transports.CustomTransport = CustomTransport;
const tsFormat = () => (new Date()).toLocaleTimeString();
var logger = new (winston.Logger)({
transports: [
// add name attribute to prevent Transport already attached error
// no error log for this transport
new (winston.transports.CustomTransport)(
{
name: 'info-console',
level: 'debug',
levels : ['debug', 'verbose', 'info', 'warn'],
timestamp: tsFormat,
handleExceptions: true,
colorize: true,
json: false
}
),
// only error log for this transport, modify the configuration as you need
new (winston.transports.CustomTransport)(
{
name: 'error-console',
level: 'error',
timestamp: tsFormat,
handleExceptions: true,
colorize: true,
json: false
}
),
new (winston.transports.File)(
{
name: 'info-file',
filename: 'info.log',
timestamp: true,
maxsize: 1024000,
level: 'info'
}),
new (winston.transports.File)(
{
name: 'error-file',
filename: 'error.txt',
timestamp: true,
maxsize: 1024000,
level: 'error'
})
]});
usage:
logger.debug('debug');
logger.error('error');

Log4js javascript create daily log file

I have a project nodejs and use log4js to write log.
I want create new file log when start new date.
Example:
daily.2017_07_31.log
daily.2017_08_01.log
daily.2017_08_02.log
daily.2017_08_03.log
In java, I know config log4j but in nodejs with log4js I don't know.
Thank every body for your help :)
winston is recommended for nodejs. Its pretty easy to use.
Create a logger.js file and have this configuration '
require('winston-daily-rotate-file');
var winston = require('winston');
winston.loggers.add('logger', {
transports: [
new (winston.transports.Console)(
{
level: config.debugLogLevel,
colorize: true
}),
//new files will be generated each day, the date patter indicates the frequency of creating a file.
new winston.transports.DailyRotateFile({
name: 'debug-log',
filename: '<log file name>',
level: '<level>',
prepend: true,
datePattern: '<pattern>',
maxFiles: <max file>
}
),
new (winston.transports.DailyRotateFile)({
name: 'error-log',
filename: '<log file name>',
level: '<level>',
prepend: true,
datePattern: '<pattern>',
maxFiles: <max file>
})
]
});
var logger = winston.loggers.get('logger');
Object.defineProperty(exports, "LOG", {value: logger});
now you can use it anywhere like
var log = require('./logger.js').LOG
log.error('hello');
See: https://github.com/log4js-node/log4js-node/blob/master/docs/dateFile.md
log4js.configure({
appenders: {
everything: { type: 'dateFile', filename: 'all-the-logs.log' }
},
categories: {
default: { appenders: [ 'everything' ], level: 'debug' }
}
});
This example will result in files being rolled every day. The initial
file will be all-the-logs.log, with the daily backups being
all-the-logs.log.2017-04-30, etc.
Not found for daily rolling, but for size the configuration of log4js allows file rolling. Pay attention to maxLogSize, backups and compress properties. Example from its docs:
log4js.configure({
appenders: {
everything: {
type: 'file',
filename: 'all-the-logs.log',
maxLogSize: 10485760,
backups: 3,
compress: true
}
},
categories: {
default: { appenders: [ 'everything' ], level: 'debug'}
}
});
See https://github.com/log4js-node/log4js-node/blob/master/docs/file.md

Resources