Winston logger different file for different date - node.js

Does winston provide a way to write logs to different file when the date is changed?
e.g. errorLogs_10_04_2016.log, errorLogs_11_04_2016.log, errorLogs_12_04_2016.log
I need to export these logs, provide admin a way to export logs to a specific date.
Update:
As suggested by krakig, I tried using DailyRotateFile transport.
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.DailyRotateFile)({
filename: 'logs.log',
datePattern:'_dd-MM-yyyy'
})
]
});
But I'm getting winston.transports.DailyRotateFile is not a function error.
My winston version is 2.2.0

The feature was added a while ago :
winston.add(winston.transports.DailyRotateFile, {
filename: './logs/my.log',
datePattern: '.dd-MM-yyyy'
});
EDIT :
I didn't mention it, but the package is independant. You have to get it from npm :
winston.transports.DailyRotateFile = require('winston-daily-rotate-file');

Related

How to use winston in NodeJs?

I am trying to create a sample nodeJs program to use and understand winston library for nodeJs,
I had a sample code from one of the existing projects and I am trying to create a sample code sample,
The code contains winston configuration and a simple test function to print logs using different log levels.
I'm using node version 4.6.2, I know it's pretty old but, the existing application is using the same, therefore I wanted to understand the implementation on the same version, The example consists of the following code and a log folder, in which I wish to print the log.
Following is a sample code which I am trying to run -
var winston = require('winston');
var envData = require('dotenv').config({path: 'server.env'})
require('winston-daily-rotate-file');
var levelLog = 'debug';
var winstonTransports = [];
const logDTFormat = () => (new Date().toFormat('DD MMM YYYY HH24:MI:SS'));
// Winston Rotate File Logs
var transportDailyRotate = new (winston.transports.DailyRotateFile)({
filename: './logs/hrfid_app_',
datePattern: 'yyyy-MM-dd.log',
prepend: false,
level: levelLog,
timestamp: function() {
var dateTime = new Date(Date.now());
return dateTime.toFormat('DD/MM/YYYY HH24:MI:SS');
}
});
winstonTransports.push(transportDailyRotate);
// Winston Console Log
var trasportConsole = new (winston.transports.Console)({
timestamp: logDTFormat,
colorize: true,
level: levelLog
});
winstonTransports.push(trasportConsole);
// Winston Config
winston.configure({
level: levelLog,
transports: winstonTransports
});
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
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' })
]
});
//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// Validate Server Configuration
if (envData.error) {
winston.error('[APP-CONFIG]:', JSON.stringify(envData.error))
winston.error('[APP-CONFIG]:', 'Error on Server Configuration')
return
}
var test = function(){
winston.error("ERROR log");
winston.info("INFO log");
winston.debug("DEBUG log");
}
test();
I am getting the following error,Can someone please help fix my sample code?
Upgrade to node 6 or 8.
Latest winston require at least node 6.4
https://github.com/winstonjs/winston/blob/c42ab7fdc51b88db180a7dd90c52ce04ddd4e054/package.json#L69
Or use an older version of winston by deleting the existing one and execute npm install winston#2.4.4

How to add multiple transport for parse-server logger?

I can access to the winston logger exposer by parse-server with let logger = require('parse-server').logger;
I would like to configure several transport file to have separate file with different logging levels like I can do with Winston:
var logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({
name: 'info-file',
filename: 'filelog-info.log',
level: 'info'
}),
new (winston.transports.File)({
name: 'silly-file',
filename: 'filelog-silly.log',
level: 'silly'
})
]
});
I've tried by usgin winston function like:
logger.add(winston.transports.File, { ... });
And with:
winston.configure({
transports: [
new (winston.transports.File)({ filename: 'somefile.log' })
]
});
But it doesn't work.
I also saw this PR https://github.com/parse-community/parse-server/pull/2363 but I coudn't understand how to add these transports from my index.js in parse-server.
Can someone give me some hints? Thanks!
Additional info:
parse-server version: 2.6.2
I was trying to do similar as you. I wanted to add a transport to send logs to loggly.
I think the way to do it, is to use the logger object, that is exported together with the ParseServer object from the parse-server package.
The way how I added the loggly additional transport is the following:
const {ParseServer, logger} = require('parse-server');
const loggly = require('winston-loggly');
const parseApi = new ParseServer({
...
});
logger.adapter.addTransport(new loggly.Loggly({
subdomain: 'my-subdomain',
token: 'myToken',
json: true
}));
I believe this is safe to do, as the logger is exported by the package in the same way as ParseServer.
Hope it helps. Lukas
for future reference (an example how I use winston-mongoDB), I'll just add my way as well:
1) create custom logger adapter
var _WinstonLoggerAdapter = require('parse-server/lib/Adapters/Logger/WinstonLoggerAdapter');
import * as WinstonMongoDb from 'winston-mongodb';
export function createCustomLoggerAdapter(options) {
var winston = new _WinstonLoggerAdapter.WinstonLoggerAdapter(options);
var WinstonMongoDbInstance: any = WinstonMongoDb.MongoDB;
const transport = new WinstonMongoDbInstance({
...options,
collection: 'ServerLog',
level: 'error'
});
winston.addTransport(transport);
return winston;
}
2) use it in parse config
var parseConfig = {
....,
loggerAdapter: createCustomLoggerAdapter({db: databaseUri}),
}

Node JS with Socket IO Winston Logger not outputting debug

I'm trying to have the winston logging output logger.debug for a node.js/socket.io project I'm working on but I can't get the debug to show up in the console.
I create logger with:
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)()
]
});
On connection I'm trying to get the the debug to say it has connected
io.on('connection', function (socket) {
socket.emit('init','init-yes');
logger.debug("Socket.on has connected");
logger.log('debug', 'This is the debug');
...
but nothing appears in the console. I checked out the git page but still seem to be not understanding something.
EDIT
As was suggested I updated the logger creation to:
var logger = new winston.Logger({
transports: [
new winston.transports.Console({ level : 'debug' })
]
});
but I'm still not getting the logger.debug("Message here") to work.
Any help would be greatly appreciated. Thank you for your time!
The fine manual states: "note that the default level of a transport is info".
Since you don't set the log level for your transport, any messages with a level below info (like debug) won't get shown.
To fix this:
var logger = new winston.Logger({
transports: [
new winston.transports.Console({ level : 'debug' })
]
});

Sailsjs - Custom Logging with Winston

I am currently trying to write a custom logger for sailsjs that will use winston to send files to either an s3 bucket or a mongodb database.
The documentation seems to be lacking but so far i have found this:
var customLogger = new winston.Logger({
transports: [
new(winston.transports.File)({
level: 'debug',
filename: './logs/my_log_file.log'
})
]
});
module.exports.log = {
colors: false, // To get clean logs without prefixes or color codings
custom: customLogger
};
Which overall is not working for me.
Any ideas?
After extending above MayBeColin's work, the working solution:
Create a new js file inside a config folder(code inside of this will be executed automatically by sails) and add mongodb transports as below,
var winston = require('winston');
var MongoDB = require('winston-mongodb').MongoDB;
var customLogger = new(winston.Logger)({
transports: [
new(winston.transports.MongoDB)({
db: 'mongodb://localhost:27017/test',
collection: 'logs',
level: 'debug'
})
]
});
module.exports.logging = {
colors: false, // To get clean logs without prefixes or color codings
custom: customLogger
};
And use it anywhere like
sails.config.logging.custom.debug("winston mongodb transport logging");

Winston: how to rotate logs

How can I rotate logs when using Winston to handle logging for node.js. That is, how can I create a new file for each day the app runs?
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: '2012-07-09.log' })
]
});
logger.log('info', 'Test Log Message', { anything: 'This is metadata' });
winston author and maintainer here.
Logging to a new file everyday is currently an open feature request: https://github.com/flatiron/winston/issues/10. Would love to see someone implement it.
That said, there are other options:
The File transport accepts a maxsize option which will rotate the logfile when it exceeds a certain size in bytes.
There is also an open pull-request with a new transport I haven't had a chance to really dig into "fileRotate", which it seems does this kind of date-based rotation: https://github.com/flatiron/winston/pull/120/files
The feature is present and we are using it in production, winston.transports.DailyRotateFile:
var timeFormatFn = function() {
'use strict';
return moment().format(cfg.timeFormat);
};
var logger = new(winston.Logger)({
exitOnError: false,
transports: [
new(winston.transports.DailyRotateFile)({
filename: cfg.appLogName,
dirname: __dirname + '/../' + cfg.logsDirectory,
datePattern: cfg.rollingDatePattern,
timestamp: timeFormatFn
}),
new(winston.transports.Console)({
colorize: true,
timestamp: timeFormatFn
})
]
});
You can use the following code to rotate the log files daily:
var winston = require('winston');
require('winston-daily-rotate-file');
var transport = new (winston.transports.DailyRotateFile)({
filename: './log',
datePattern: 'yyyy-MM-dd.',
prepend: true,
level: 'info'
});
var logger = new (winston.createLogger)({
transports: [
transport
]
});
logger.info('Hello World!');
According to the author of winston-filerotatedate it is a:
File transport for winston that allows the log files to be rotated depending on size and time.
The File transport accepts a filename via the 'filename' option and uses that file as the primary logging target.
Should the file grow past 'maxsize' bytes then the current log file is renamed and a new primary log tile is created.
The name of the renamed log file is formated as such 'basenameYYYYMMDD[a-z].bak'.
Available options are:
level: Level of messages that this transport should log.
silent: Boolean flag indicating whether to suppress output.
timestamp: Boolean flag indicating if we should prepend output with timestamps (default true). If function is specified, its return value will be used instead of timestamps.
filename: The filename of the logfile to write output to.
dirname: The folder the logfile will be created in.
maxsize: Max size in bytes of the logfile, if the size is exceeded then a new file is created.
json: If true, messages will be logged as JSON (default true).
Other people have already given good answers for this problem. But for those people looking for an example of how to do this in more modern JavaScript syntax(ES6 and beyond) using winston-daily-rotate-file, the following code should help:
const { createLogger, transports } = require('winston');
require('winston-daily-rotate-file');
const logger = createLogger({
level: 'info',
transports: [
new transports.DailyRotateFile({
filename: 'info-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
level: 'info'
})
]
});
logger.log('info', 'Test Log Message', { anything: 'This is metadata' });
As of Dec 18, 2012, this feature is now available in Winston (see https://github.com/flatiron/winston/pull/205)

Resources