Yes! It is all right to use Morgan as a logger on production mode.
Morgan: Morgan is an HTTP request level Middleware. It is a great tool that logs the requests along with some other information depending upon its configuration and the preset used. It proves to be very helpful while debugging and also if you want to create Log files. Prerequisites: Basic understanding of Nodejs.
use(require("morgan")("combined", { "stream": logger. stream })); This will set up Winston to write a log to the console as well as a file. Then you can use the last expression to pass output from the morgan middleware into winston.
Seems you too are confused with the same thing as I was, the reason I stumbled upon this question. I think we associate logging with manual logging as we would do in Java with log4j (if you know java) where we instantiate a Logger and say log 'this'.
Then I dug in morgan code, turns out it is not that type of a logger, it is for automated logging of requests, responses and related data. When added as a middleware to an express/connect app, by default it should log statements to stdout showing details of: remote ip, request method, http version, response status, user agent etc. It allows you to modify the log using tokens or add color to them by defining 'dev' or even logging out to an output stream, like a file.
For the purpose we thought we can use it, as in this case, we still have to use:
console.log(..);
Or if you want to make the output pretty for objects:
var util = require("util");
console.log(util.inspect(..));
I think I have a way where you may not get exactly get what you want, but you can integrate Morgan's logging with log4js -- in other words, all your logging activity can go to the same place. I hope this digest from an Express server is more or less self-explanatory:
var express = require("express");
var log4js = require("log4js");
var morgan = require("morgan");
...
var theAppLog = log4js.getLogger();
var theHTTPLog = morgan({
"format": "default",
"stream": {
write: function(str) { theAppLog.debug(str); }
}
});
....
var theServer = express();
theServer.use(theHTTPLog);
Now you can write whatever you want to theAppLog and Morgan will write what it wants to the same place, using the same appenders etc etc. Of course, you can call info() or whatever you like in the stream wrapper instead of debug() -- that just reflects the logging level you want to give to Morgan's req/res logging.
Morgan should not be used to log in the way you're describing. Morgan was built to do logging in the way that servers like Apache and Nginx log to the error_log or access_log. For reference, this is how you use morgan:
var express = require('express'),
app = express(),
morgan = require('morgan'); // Require morgan before use
// You can set morgan to log differently depending on your environment
if (app.get('env') == 'production') {
app.use(morgan('common', { skip: function(req, res) { return res.statusCode < 400 }, stream: __dirname + '/../morgan.log' }));
} else {
app.use(morgan('dev'));
}
Note the production line where you see morgan called with an options hash {skip: ..., stream: __dirname + '/../morgan.log'}
The stream
property of that object determines where the logger outputs. By default it's STDOUT (your console, just like you want) but it'll only log request data. It isn't going to do what console.log()
does.
If you want to inspect things on the fly use the built in util
library:
var util = require('util');
console.log(util.inspect(anyObject)); // Will give you more details than console.log
So the answer to your question is that you're asking the wrong question. But if you still want to use Morgan for logging requests, there you go.
I faced the same problem ago and instead, I used winston. As fellas above said, morgan is for automated logging of request/response. Winston can be configured pretty much same way as log4Net/log4J, has severity levels, different streams to which you can log etc.
For example:
npm install winston
Then, if you call the below code somewhere on you application initialization:
var winston = require('winston');
// setup default logger (no category)
winston.loggers.add('default', {
console: {
colorize: 'true',
handleExceptions: true,
json: false,
level: 'silly',
label: 'default',
},
file: {
filename: 'some/path/where/the/log/file/reside/default.log',
level: 'silly',
json: false,
handleExceptions: true,
},
});
//
// setup logger for category `usersessions`
// you can define as many looggers as you like
//
winston.loggers.add('usersessions', {
console: {
level: 'silly',
colorize: 'true',
label: 'usersessions',
json: false,
handleExceptions: true,
},
file: {
filename: 'some/path/where/the/log/file/reside/usersessions.log',
level: 'silly',
json: false,
handleExceptions: true,
},
});
note: before calling above code, winston.loggers is empty, i.e you dont have any loggers configured yet. Pretty much like Log4Net/J XmlConfigure methods - you need to first call them, to init your logging.
Then, later wherever in you application server side code you may do:
var winston = require('winston');
// log instances as defined in first snippet
var defaultLog = winston.loggers.get('default');
var userSessionsLog = winston.loggers.get('usersessions');
defaultLog.info('this goes to file default.log');
userSessionsLog.debug('this goes to file usersessions.log')
Hope that helps.
for further documentation reference: https://www.npmjs.com/package/winston
Morgan :- Morgan is a middleware which will help us to identify the clients who are accessing our application. Basically a logger.
To Use Morgan, We need to follow below steps :-
npm install --save morgan
This will add morgan to json.package file
var morgan = require('morgan');
3> // create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(
path.join(__dirname, 'access.log'), {flags: 'a'}
);
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
Note: Make sure you do not plumb above blindly make sure you have every conditions where you need .
Above will automatically create a access.log file to your root once user will access your app.
var express = require('express');
var fs = require('fs');
var morgan = require('morgan')
var app = express();
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(__dirname + '/access.log',{flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))
app.get('/', function (req, res) {
res.send('hello, world!')
});
example nodejs + express + morgan
In my case:
-console.log() // works
-console.error() // works
-app.use(logger('dev')) // Morgan is NOT logging requests that look like "GET /myURL 304 9.072 ms - -"
FIX: I was using Visual Studio code, and I had to add this to my Launch Config
"outputCapture": "std"
Suggestion, in case you are running from an IDE, run directly from the command line to make sure the IDE is not causing the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With