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.
Related
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;
I tried to logging info and errors in log file using winston.If any info stored info.log. If uncaught exception errors occurred its stored only error.log file.but If commom errors are occurred its stored both file(info .log and error.log) how to fix it any one give some solution.
winston.js
const winston = require('winston');
require('winston-mongodb');
require('express-async-errors');
const winstonLogger = function () {
winston.add(new winston.transports.Console({
format: winston.format.combine(
winston.format.simple(),
winston.format.timestamp(),
winston.format.prettyPrint(),
winston.format.colorize()
),
handleExceptions: true
}));
// Info Log messages to file
winston.add(new winston.transports.File({
filename: 'logs/info.log',
level: 'info'
}));
// Error Log Messages file
winston.add(new winston.transports.File({
filename: 'logs/error.log',
level: 'error',
handleExceptions: true,
}));
};
module.exports = winstonLogger;
I want info message stored on info.log file and error message stored on error.log file.uncaught exception error stored in separate file using winston
Winston logging is based on the level you specify. All logs below that level go to a specified file.
logging levels 0 to 5 (highest to lowest):
0: error
1: warn
2: info
3: verbose
4: debug
5: silly
Below is the sample code from winston documentation :
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
You can filter out logs by creating two loggers and adding name property to them.
This worked for me.
const winston = require('winston');
const infoLogger = winston.createLogger({
defaultMeta: { service: "log-service" },
transports: [
new winston.transports.File({
name: "info",
filename: "./logs/info.log",
level: "info",
})
],
});
const errorLogger = winston.createLogger({
defaultMeta: { service: "log-service" },
transports: [
new winston.transports.File({
name: "error",
filename: "./logs/error.log",
level: "error",
})
],
});
const logger = {
info: (params) => {
return infoLogger.info(params);
},
error: (params) => {
return errorLogger.error(params);
},
};
logger.info("info 1"); // Will go to info.log
logger.error("error 1"); // Will go to error.log
logger.info("info 2"); // Will go to info.log
logger.error("error 2 "); // Will go to error.log
I'm trying to create a logger with winston#3 that handles unhandled exceptions in my Node.js application by logging the exception to the console and to a log file, but it is only being logged on the console.
const { path } = require('app-root-path');
const { createLogger, format, transports } = require('winston');
const unhandledExceptions = createLogger({
exceptionHandlers: [
new transports.File({
filename: `${path}/logging/logs/exceptions.log`,
}),
new transports.Console()
],
format: format.combine(
format.label({ label: 'Unhandled exception' }),
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
format.prettyPrint()
)
});
throw new Error('wtf');
Any ideas on how I can get the exception written to the log file as well? Happy to provide more info.
Thanks in advance.
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.
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