winston http transport example - node.js

I need a working example which post the logs on server using http transport. I'm able to use file transport and console transport to log message in file and on console. Same way I tried doing for http transport also, the source cod for winston clien looks something like this :
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.Http)({ host: 'localhost', port:8080 })
]
});
logger.log('info', 'Hello world');
While runnign this code I get error like :
D:\Balwant\Devlopment-Env\LoggingDemo\node_modules\winston\lib\winston\transports\http.js:52
req = (self.ssl ? https : http).request({
^
ReferenceError: self is not defined
at Http._request (D:\Balwant\Devlopment- Env\LoggingDemo\node_modules\winston\lib\winston\transports\http.js:52:10)
at Http.log (D:\Balwant\Devlopment-Env\LoggingDemo\node_modules\winston\lib\winston\transports\http.js:109:8)
at emit (D:\Balwant\Devlopment-Env\LoggingDemo\node_modules\winston\lib\winston\logger.js:175:17)
at D:\Balwant\Devlopment-Env\LoggingDemo\node_modules\winston\node_modules\async\lib\async.js:111:13
at Array.forEach (native)
at _each (D:\Balwant\Devlopment-Env\LoggingDemo\node_modules\winston\node_modules\async\lib\async.js:32:24)
at Object.async.each (D:\Balwant\Devlopment-Env\LoggingDemo\node_modules\winston\node_modules\async\lib\async.js:110:9)
at Logger.log (D:\Balwant\Devlopment-Env\LoggingDemo\node_modules\winston\lib\winston\logger.js:203:9)
at Object.<anonymous> (D:\Balwant\Devlopment-Env\LoggingDemo\logger.js:10:8)
at Module._compile (module.js:456:26)
Since I'm new to node.js, I've no idea how to deal with it. I tried googling for solution but could not get any.
Plese help me.
Thanks

First winston and winstond are different packages. You can check this blog post about the difference.
You might also need to whip-up your own HTTP transport for winston (if you really want to use winston). So it can work with your specific endpoint protocol.
You can create your custom winston transport as specified here. Then you can use something like request to send the log data to your HTTP endpoint.
Good luck.
Web Transport
I don't believe winston.transports.Http exists but I think you're looking for this:
new winston.transports.Webhook({ 'host': 'localhost', 'port': 8080, 'path': '/collectdata' })
As shown in this example.
Winstond
My mistake, it does have winston.transports.Http but you'll need winstond.
You can check this example to use winstond as a http daemon. Then send your Http logs to it.
So this:
new winston.transports.Http({ host: 'localhost', port: 8080})
Should be pointing to a winstond daemon like:
var winstond = require('winstond');
var http = winstond.http.createServer({
services: ['collect', 'query', 'stream'],
port: 8080
});
http.add(winstond.transports.Console, {});
http.listen();

var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
],
exceptionHandlers: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
],
exitOnError: false
});
module.exports = logger;
add this line were ever u wanted to lg the error message
var logger = require('../../config/logger.js');
logger.info("the default logger with my tricked out transports is rockin this module");

Related

Loggly Subdomain is required

I'm trying to implement to my NodeJs API a logging system using:
Loggly
Winston
Morgan
When I run my server I got the error:
Error: Loggly Subdomain is required
But the subdomain is defined as follows
What I was trying to do to put the Loggly config inside of a module:
module.exports = {
loggly: {
token: process.env.LOG_TOKEN,
subdomain: process.env.SUBDOMAIN,
tags: ["Winston-NodeJS"],
json: true
}
};
Using also the ENV which are defined and contains the right info.
Then I created a new file called logger.js
// Requiring libs Loggly & Winston
const Loggly = require("winston-loggly-bulk").Loggly;
const winston = require("winston");
// Loggly config
const config = require("../config/config");
// Creating the logging
const logger = winston.createLogger({
transports: [
new Loggly(config.loggly), ==> Here the error occur!
new winston.transports.Console({ level: "info" })
]
});
// Logging stream
logger.stream = {
write: (info) => {
logger.info(info);
}
};
module.exports = logger;
In this script, the error occurs when I call new Loggly(...) seems cannot read my SUBDOMAIN and I cannot understand a different way of doing as it is the first time I'm trying this implementation.
Put this line require("dotenv").config(); on line 1 in server.js.

Show uncaught exception in console when using winston (node.js)

Here's the code I'm working with:
var winston = require('winston');
winston.add(winston.transports.File, { filename: 'test.log', handleExceptions: true, humanReadableUnhandledException: true });
throw "test";
In test.log, winston does log the error properly.
But I'd also like it to show the error in the console as well like it normally does.
Is this possible?
Add Console transport to winston, along with existing File transport:
winston.add(winston.transports.Console, options)
https://github.com/winstonjs/winston/blob/master/docs/transports.md#console-transport

NodeJS Winston DailyRotateFile not writing

I'm trying to setup a simple daily rotation log write with:
// Create file transport
transports.push(new winston.transports.DailyRotateFile({
name: 'file',
datePattern: '.yyyy-MM-ddTHH',
filename: path.join(logPath, 'http')
}));
// Create new logger
var logger = new winston.Logger({
transports: transports
});
It's creating the log file just fine, however logger.info(some_data) doesn't write anything to the log.
Any thoughts, or even another solution?
This one works with minute rotation:
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.DailyRotateFile)({ filename: 'logFile', datePattern: '.yyyy-MM-dd_HH-mm' })
]
});
logger.info('Hello my friend');

Set default winston logger for all modules

I am trying to setup winston to work in all my modules in the same fashion as in here:
using winston in several modules
But I am running in problems.
I have setup a logger.js file to configure the console logger:
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
timestamp: true,
level: 'verbose',
colorize: true
})
]
});
module.exports = logger;
I then require that logger in my main app.js file:
var logger = require('./logger.js');
logger.info('Starting server'); // this console log looks great, just as I configured
However when I try an require winston in al other modules I lose the config I setup for winston in the logger.js
Other Module:
var logger = require('winston');
logger.info('in another module'); // this is back to winstons default console transport
According to the link I referenced above I should be able to require winston in all other modules and the transports I defined/configured should still be the same. Only thing I can think is that this is not true for the Console transport. If not what gives? How do I configure the Console transport once and then use winston in all other modules?
For your current solution to work, you have to make sure you have one version of winston. You shouldn't have it installed once under your main app and another time under your other module. Then in here you are creating a new instance of logger and not using the default.
You should instead of above do this:
var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {
timestamp: true,
level: 'verbose',
colorize: true
});
I think this should work. If that didn't work, you can try one of these methods:
Get them to use your ./logger module instead. This works great in internal modules that are part of the app codebase.
Or make your other module configurable. Do something like require('other-module').logger = require('./logger'); or require('other-module').setLogger(require('./logger'));. You can check this question if you want to know more about this method.

Node winston cannot support multiple file transport?

I want to show error logs in one file and all logs in another file. To do that, I wrote two file transports which give the following error on compilation:
'use strict';
var winston = require('winston'),
config = require('./config');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({level:'debug',handleExceptions: true,prettyPrint: true,silent:false,timestamp: true,colorize: true,json: false}),
new (winston.transports.File)({ filename: './server/logs/bv_common.log',level:'debug',maxsize: 1024000,maxFiles: 10, handleExceptions: true,json: false}),
new (winston.transports.File)({ filename: './server/logs/bv_error.log',level:'debug',maxsize: 1024000,maxFiles: 10, handleExceptions: true,json: false,level:'error'})
]
});
module.exports = logger;
Result:
[ 'Error: Transport already attached: file',
var logger = new (winston.Logger)({
exitOnError: false, //don't crash on exception
transports: [
new (winston.transports.Console)({level:'debug',handleExceptions: true,prettyPrint: true,silent:false,timestamp: true,colorize: true,json: false}),
new (winston.transports.File)({ filename: './server/logs/' + config.appname +'_common.log',name:'file.all',level:'debug',maxsize: 1024000,maxFiles: 10, handleExceptions: true,json: false}),
new (winston.transports.File)({ filename: './server/logs/' + config.appname +'_error.log',name:'file.error',level:'error',maxsize: 1024000,maxFiles: 10, handleExceptions: true,json: false})
]
});
The above code , especially with name parameter for shared transport, we can use multiple file transports for loggers.
You are getting this error because you are not providing a 'name' attribute to your file transports.

Resources