Winston rotate writing to mutiple files - javascript

So Im using winston-daily-rotate-file.
In app.js I have:
var logger = require('./logger');
and then:
logger.info("logging to info");
logger.error("logging to error");
In logger/index.js I have:
var error_transport = new winston.transports.DailyRotateFile({
filename: '../logs/error',
datePattern: 'yyyy-MM-dd.',
prepend: true,
level: 'error',
name: 'error'
});
var info_transport = new winston.transports.DailyRotateFile({
filename: '../logs/info',
datePattern: 'yyyy-MM-dd.',
prepend: true,
level: 'info',
name: 'info'
});
var logger = new (winston.Logger)({
transports: [
error_transport,
info_transport
]
});
module.exports = logger;
What happens is that the file
logs/DATE_error
contains:
logging to error
BUT: the file
logs/DATE_info
contains:
logging to info
logging to error
Why is the info file also including logs from error?

You can read about Winston's logging levels here: Logging Levels
The basic reason that info is including logs from error is that "levels" with a higher priority number will always log messages for any level "below" them in priority. See the example under Using Logging Levels
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ level: 'warn' }),
new (winston.transports.File)({ filename: 'somefile.log', level: 'error' })
]
});
logger.debug("Will not be logged in either transport!");
logger.transports.console.level = 'debug';
logger.transports.file.level = 'verbose';
logger.verbose("Will be logged in both transports!");

Related

Winston not logging correct values

Hey everyone i need help setting up my Winston logging config.
I am migrating an existing project with 300 + console.logs to winston and now the values of the logs are not printed anymore.
I researched online and only found hacky solutions that didn't work for me.
Any help is appreciated.
This is my logger config
// logger config
const winston = require('winston')
const { combine, timestamp, colorize, align, printf } = winston.format
const logger = winston.createLogger({
// level: process.env.LOG_LEVEL || 'info',
level: 'silly',
format: combine(
colorize({ all: true }),
timestamp({
format: 'YYYY-MM-DD hh:mm:ss',
}),
align(),
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
), transports: [new winston.transports.Console()],
})
module.exports = logger
This is how the console log was before:
console.log('active jobs : ',
(await queue.getActive()).length)
Output:
active jobs : 12
This is how it is now:
logger.info(
'active jobs : ',
(await queue.getActive()).length
)
Output:
[2022-05-23 03:57:29] info: active jobs :
I would appreciate if there is a possibility without changing the console.logs since they are so many.

Winston javascript logger is creating two separate log files. How do I log all entries into a single file?

I'm attempting to use Winston and winston-daily-rotate-file to log all my console/log output from a node.js server to a single file that will (hopefully) get rotated daily at midnight.
The issue I'm encountering is that unhandled exceptions seem to generate a new log file rather than write to the existing one. See the example code below for the duplication behaviour. How do I get all output to be saved to a single logfile as well as output to the console? At present, the console side of things appears to be fine but feel free to point out anything obvious that I'm missing.
OS: Win 10
node: v12.16.0
npm: v6.13.4
winston: v3.2.1
winston-daily-rotate-file: v4.4.2
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const path = require('path');
var logger = new (winston.createLogger)({
transports: [
new (winston.transports.Console)({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.colorize({ all: true }),
winston.format.printf((info) => {
const {
timestamp, level, message
} = info;
return `${timestamp} - ${level}: ${message}`;
}),
),
handleExceptions: true
}),
new DailyRotateFile({
name: 'file',
datePattern: 'YYYY-MM-DDTHH-mm-ss',
handleExceptions: true,
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf((info) => {
const {
timestamp, level, message
} = info;
return `${timestamp} - ${level}: ${message}`;
}),
),
filename: path.join(__dirname, 'logs', '%DATE%.log')
}),
]
});
logger.info("This is an info message");
logger.error("This is an error message");
setTimeout(() => {throw new Error('oh dear!')}, 5000);
My issue was caused by the datePattern option. winston-daily-rotate-file uses this pattern to determine the frequency of file rotation. As I had included seconds in the pattern it was looking for a file with the current timestamp (to the nearest second) and creating it before writing to file.
To get daily files I just needed to change
datePattern: 'YYYY-MM-DDTHH-mm-ss'
to
datePattern: 'YYYY-MM-DD'

NodeJs Winston log line number

I am writing a module for logging in Nodejs using Winston. I am using a custom format and initialize my logger like this:
const logger = createLogger({
format: combine(
format.timestamp(),
format.printf(msg => `${JSON.stringify({timestamp: msg.timestamp,
shortmessage: msg.message,
level: msg.level,
source: config.programName,
file: __filename,
line: '' })}`) // how to get this?
),
transports: [new (transports.Console)({
level: config.logLevel, // logs up to specified level
})]
});
module.exports = {
error: function (message) {
logger.error(message);
},
info: function (message) {
logger.info(message);
},
debug: function (message) {
logger.debug(message);
}
};
As mentioned in the comment, I also need to include line number in my log. I did some research and found some workarounds (1, 2, 3), but it seems they can't be used in my case, as I use a custom format, which should be specified during the logger creation time and line number can be retrieved later.
I was thinking to use Winston's label feature, but it seems labels can contain only static data.
How can this be solved? Any ideas.

Hiding log-level in Winston logs

I am using Winston.js to log some information in a Javascript application. The problem is that the log level should be hidden in the printed log.
Instead of having something like this:
info: some pretty and cool log message
I need to have something like this:
some pretty and cool log message
I have a look at the Winston main page, but I did not find anything.
You need to use custom format:
const { createLogger, format, transports } = require('winston');
const winston = createLogger({
level: 'info',
transports: [
new transports.Console({
level: 'info',
format: format.combine(
format.colorize(),
format.printf(
(info) => {
// return `${info.level}: ${info.message}`;
return `${info.message}`;
})
)
}),
]
});
winston.info('Hello world');
winston.log('info', 'Hello world 2');
//or you can use wrapper to easy replace console.log
const logger = {
log:(msg) => {
winston.info(msg);
}
}
logger.log('Hello world 3');
Scrabbling the unit test of the library, I found this one: Custom formatter. Basically, declaring a custom formatter for a log level, you can basically do everything you want with the text that will be write to the log.
To write the log message only without any log level information, redefine the formatter for a log in the following way.
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'info',
pattern: /info\:/,
formatter: function(params) {
return undefined !== params.message ? params.message : "";
}
})
]
});
The above example defines a console logger that prints only the message for the logs of level info, without any additional information.
Hope it helps.

Winston - Logging with dynamic file name (separate log file for each .feature file)

I am using protractor cucumber framework for my test automation. For logging i am using 'Winston'. I have multiple feature files. I want to keep log files in the name of feature file for better tracking.
As of now i hard coded file name as shown below in 'filename' property [filename: 'c:\QAAutomation\info.log'].
Is there any option in Winston to assign dynamic file name ?
var winston = require('winston');
require('winston-daily-rotate-file');
var moment = require('moment-timezone');
winston.emitErrs = true;
var logger = new winston.Logger({
transports: [
new winston.transports.DailyRotateFile({
level: 'info',
name: 'info-file',
filename: 'c:\\QAAutomation\\info.log',
handleExceptions: true,
json: false,
prepend: true,
datePattern: 'yyyyMMdd',
maxsize: 5242880, //5MB
maxFiles: 60,
colorize: false,
formatter: customFileFormatter,
timestamp: function() {
return moment().format("MM-DD-YYYY HH:mm:ss.SSS");
}
})
],
exitOnError: false
});
module.exports = logger;
module.exports.stream = {
write: function(message, encoding) {
logger.verbose(message);
}
};
function customFileFormatter(options) {
// Return string will be passed to logger.
return `{"timestamp": "${options.timestamp()}", "level": "${options.level}", "message": "${(options.message ? options.message : '')
+ (options.meta && Object.keys(options.meta).length ? '\n\t' + JSON.stringify(options.meta) : '')}"}`;
}

Categories

Resources