logging using winston not making new file - node.js

i am using winston to add logs in my nodejs project which is basically a kakfka based service which runs 24 x 7, below code only generate log on separate file(the file dated when the service restarted) but it only changes file when the i restart the server after the change date, is their anything which automatically changes the log file when the day changes.
const {createLogger, format, transports} = require("winston");
const {combine, timestamp, label, prettyPrint} = format;
const logger = createLogger({
level: "info",
format: format.combine(
format.splat(),
format.simple(),
format.json(),
timestamp(),
prettyPrint()
),
transports: [
new transports.File({
filename: `${appRoot}/Log/error/Log_${new Date().getUTCDate()}-${new Date().getMonth()}-${new Date().getFullYear()}.log`,
level: "error",
handleExceptions: true,
json: true,
stack: true,
}),
],
exitOnError: false,
});
module.exports = logger;

Related

How to have winston save a file immediately after it writes logs to it

I am using winston to write logs to a file on a host that I have mounted to a docker container. The mounted volume inside the docker container is supposed to tail the file that we mounted, but when winston writes logs to the file location I either have to close the app or manually go into the log file and save it in order for the file contents to be synced to the mounted volume in docker which eventually tails the file.
Is there a way for winston to write the logs and save the file so the contents are synced immediately? Below is my winston config
const winston = require('winston');
const path = require('path');
let logsPath = path.join(__dirname, '../logs/');
const options = {
file: {
timestamp: true,
level: 'info',
filename: logsPath + `app.logs`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: true,
json: true,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
let logger;
logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console),
],
exitOnError: false, // do not exit on handled exceptions
});
module.exports = logger;

Logging file and function name with Winston

Is it possible to log filename and method name with Winston?
I am using following code to create the logger:
var logger = winston.createLogger({
transports: [
new winston.transports.DailyRotateFile({
level: 'debug',
datePattern: 'YYYY-MM',
filename: logDir + '/workflow/%DATE%-workflow.log',
format: winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
winston.format.json()
)
})
]
});
Now let us assume I am running following code in the file login.js and doLogin()
logger.info('Test');
This generates the following entry:
{"message":"Test","level":"info","timestamp":"2020-06-18 06:17:37"}
I want to do something like this:
{"message":"Test","level":"info", "file": "login.js", "method": "doLogin", "timestamp":"2020-06-18 06:17:37"}
I don't want to pass the file name and method name in very call.

Winston is not properly working, I am unable to get all the console values in log file using winston

I want to store all the console values in log file using Winstone, but I have ended up to store only the morgan values and not the console.log values in my log file.
And I also want to store the error values in my error.log file which I am unable to get it right now. Here below is my code.
winston.js file
var appRoot = require('app-root-path');
var winston = require('winston');
// define the custom settings for each transport (file, console)
var options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
errorFile: {
level: 'error',
name: 'file.error',
filename: `${appRoot}/logs/error.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 100,
colorize: true,
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
var logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.File(options.errorFile),
new winston.transports.Console(options.console)
],
exitOnError: false, // do not exit on handled exceptions
});
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write: function(message, encoding) {
logger.info(message);
},
};
module.exports = logger;
main.js file
const express = require('express');
const app=express();
const morgon=require("morgan");
var winston = require('./config/winston');
app.use(morgon("combined", { stream: winston.stream }));

Winston not logging uncaught exceptions

I'm trying to use winston to log unhandled exceptions to file and console. The problem is that it is not logging them. Here my setup:
var winston = require('winston');
let file = process.env.APP_TOOL_SET_API_PROJECT+"/logs/app.log";
console.log(process.env.APP_TOOL_SET_API_PROJECT);
// define the custom settings for each transport (file, console)
var options = {
file: {
level: 'info',
filename: file,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: false,
json: true,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
var logger = winston.createLogger({
format: winston.format.combine(
//winston.format.label({ label: '[my-label]' }),
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
//
// The simple format outputs
// `${level}: ${message} ${[Object with everything else]}`
//
winston.format.simple(),
//
// Alternatively you could use this custom printf format if you
// want to control where the timestamp comes in your final message.
// Try replacing `format.simple()` above with this:
//
winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
),
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console)
],
exceptionHandlers: [
new winston.transports.File({ filename: process.env.APP_TOOL_SET_API_PROJECT+"/logs/exceptions.log" }),
],
exitOnError: false, // do not exit on handled exceptions
});
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write: function(message, encoding) {
// use the 'info' log level so the output will be picked up by both transports (file and console)
logger.info(message);
},
};
module.exports = logger;
To add a bit more of information, if I wrap a thrown exception with setTimer it then is logged correctly.
setTimeout(() => {
throw new Error('hello world');
}, 250);
But this only would work for user thrown exceptions and feels really ugly to have to wrap each throw with setTimeout.
Is there any solution for this?
Well, just after posting the answer, my mental background thread spit the possible problem.
Obviously I was throwing the exception (just testing) too early and I wasn't given winston enough time to init properly.
This is why waiting with the setTimer was logging correctly.

Logging only the message using winston

I am using winston logger in my node app and i want to log my custom message to the log file.
var logger = new winston.Logger({
transports: [
new winston.transports.File({
level: 'info',
filename: '/tmp/test.log',
handleExceptions: true,
json: true,
maxsize: 20971520 //20MB
})
],
exitOnError: false
});
I only need to log message in the log, i dont need to log level and timestamp in the log file. Current logged sample is as below.
{"level":"info","message":"sample entry to log","timestamp":"2015-12-11T09:43:50.507Z"}
My intention is to get entry in the log file as below
sample entry to log
How to achieve this?
Winston 3:
import winston from 'winston';
const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.Console({
format: winston.format.printf(log => log.message),
})
]
});
logger.info('eat my shorts');
On Winston 2.x
If you want to print only the message, you can achieve this by setting:
json: false,
timestamp: false,
showLevel: false
Full Logger example:
let logger = new Logger({
transports: [
new (transports.File)({
name: 'info-file',
filename: 'filelog-info.log',
json: false,
timestamp: false,
showLevel: false
})
],
exitOnError: false
});
logger.log('info', 'eat my shorts');
gives in filelog-info.log: eat my shorts
FYI: filters and rewriters didn't help here
If anyone, as did I, finds this question in hopes of making express-winston log only message (to the console in my case)
Here is what I did:
const winston = require('winston');
const expressWinston = require('express-winston');
const { MESSAGE } = require('triple-beam');
expressWinston.logger({
transports: [
new winston.transports.Console({
format: simpleformatter()
})
]
});
const simpleformatter = winston.format(info => {
info[MESSAGE] = info.message;
return info;
});
Yep got the one i was looking for
https://github.com/winstonjs/winston#filters-and-rewriters
https://github.com/winstonjs/winston#custom-log-format

Resources