How to use a Morgan recorder?

I can't log in with Morgan. It does not write information to the console. The documentation does not indicate how to use it.

I want to see what a variable is. This is the code from the response.js file of the expressjs framework:

 var logger = require("morgan"); res.render = function(view, options, fn){ options = options || {}; var self = this; var req = this.req; var app = req.app; // support callback function as second arg if ('function' == typeof options) { fn = options, options = {}; } // merge res.locals options._locals = self.locals; // default callback to respond fn = fn || function(err, str){ if (err) return req.next(err); self.send(str); }; // Here I want to see what fn is // But it doesn't show me anything in console // How to use it? logger(fn); // render app.render(view, options, fn); }; 

How to use Morgan?

+97
logging express
May 6 '14 at 12:37
source share
8 answers

It seems that you, too, are confused with the same as me, so I came across this question. I think we associate logging with manual logging, as it would be in Java with log4j (if you know java), where we create an instance of Logger and say the log 'this'.

Then I dug up the Morgan code, it turns out that this is not the type of registrar, it is designed to automatically keep requests, responses, and related data. When adding default express / connect application as middleware, it needs to write operators to stdout, where the details are indicated: remote ip, request method, http version, response status, user agent, etc. It allows you to change the log using tokens or add color to them by specifying "dev" or even by logging into an output stream, such as a file.

For this purpose, we decided to use it, since 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(..)); 
+104
May 12 '14 at 3:24
source share

I think I have a way that you cannot get what you want, but you can integrate Morgan magazine with log4js - in other words, all your registration activities can go to the same place. I hope that this digest from the Express server is more or less clear:

 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 in AppLog, and Morgan will write what he wants in the same place, using the same applications, etc. etc. Of course, you can call info () or whatever you like in the stream wrapper rather than debug () - this simply reflects the logging level that you want Morgan req / res logging to provide.

+54
May 23 '14 at 20:54
source share

Morgan should not be used to record how you describe. Morgan was created for logging so that servers such as Apache and Nginx are logged in 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')); } 

Pay attention to the production line where you can see the morgan with the hash parameter {skip: ..., stream: __dirname + '/../morgan.log'}

The stream property of this object determines where the recorder is issued. By default, this is STDOUT (your console, as you want), but it will only log request data. He is not going to do what console.log() does.

If you want to inspect things on the fly, use the util built-in 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 are asking the wrong question. But if you still want to use Morgan to register requests, you go.

+29
Jan 06 '15 at 21:23
source share

I ran into the same problem and I used winston instead. As stated above, morgan is designed to automatically register a request / response. Winston can be configured in the same way as log4Net / log4J, it has severity levels, various streams to which you can write, etc.

For example:

npm install winston

Then, if you call the code below somewhere when initializing the application:

 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 the code above winston.loggers is empty, i.e. You do not have any logs configured yet. To a large extent, like the Log4Net / J XmlConfigure methods - you need to call them first to start the registration.

Then, later, wherever you make the code on the application server side, you can:

 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 this helps.

for additional documentation: https://www.npmjs.com/package/winston

+15
Feb 28 '16 at 11:46
source share

Morgan: - Morgan is a middleware that will help us identify customers who access our application. This is mainly a registrar.

To use Morgan, we need to follow these steps: -

  1. Install Morgan using the following command:

npm install --save morgan

This will add morgan to the json.package file

  1. Include Morgan in your project

var morgan = require('morgan');

3> // create a recording stream (in add mode)

 var accessLogStream = fs.createWriteStream( path.join(__dirname, 'access.log'), {flags: 'a'} ); // setup the logger app.use(morgan('combined', {stream: accessLogStream})); 

Note: make sure that you are not distracted from above, make sure that you have all the conditions where you need to.

The above will automatically create the access.log file for your root as soon as the user gains access to your application.

+8
Nov 06 '16 at 18:12
source share
 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

+7
Mar 17 '15 at 14:07
source share

You might want to use mongo-morgan-ext

Using:

 var logger = require('mongo-morgan-ext'); var db = 'mongodb://localhost:27017/MyDB'; var collection = 'Logs' var skipfunction = function(req, res) { return res.statusCode > 399; } //Thiw would skip if HTTP request response is less than 399 ie no errors. app.use(logger(db,collection,skipfunction)); //In your express-application 

Expected Result:

 { "RequestID": "", "status": "", "method": "", "Remote-user": "", "Remote-address": "", "URL": "", "HTTPversion": "", "Response-time": "", "date":"", "Referrer": "", "REQUEST": { //10 "Accept": "", "Accept-Charset": "", "Accept-Encoding": "", "Accept-Language": "", "Authorization": "", "Cache-Control": "", "Connection": "", "Cookie": "", "Content-Length": "", "Content-MD5": "", "Content-Type": "", "Expect": "", "Forwarded": "", "From": "", "Host": "", "Max-Forwards": "", "Origin": "", "Pragma": "", "Proxy-Authorization": "", "Range": "", "TE": "", "User-Agent": "", "Via": "", "Warning": "", "Upgrade": "", "Referer": "", "Date": "", "X-requested-with": "", "X-Csrf-Token": "", "X-UIDH": "", "Proxy-Connection": "", "X-Wap-Profile": "", "X-ATT-DeviceId": "", "X-Http-Method-Override":"", "Front-End-Https": "", "X-Forwarded-Proto": "", "X-Forwarded-Host": "", "X-Forwarded-For": "", "DNT": "", "Accept-Datetime": "", "If-Match": "", "If-Modified-Since": "", "If-None-Match": "", "If-Range": "", "If-Unmodified-Since": "" }, "RESPONSE": { "Status": "", "Content-MD5":"", "X-Frame-Options": "", "Accept-Ranges": "", "Age": "", "Allow": "", "Cache-Control": "", "Connection": "", "Content-Disposition": "", "Content-Encoding": "", "Content-Language": "", "Content-Length": "", "Content-Location": "", "Content-Range": "", "Content-Type":"", "Date":"", "Last-Modified": "", "Link": "", "Location": "", "P3P": "", "Pragma": "", "Proxy-Authenticate": "", "Public-Key-Pins": "", "Retry-After": "", "Server": "", "Trailer": "", "Transfer-Encoding": "", "TSV": "", "Upgrade": "", "Vary": "", "Via": "", "Warning": "", "WWW-Authenticate": "", "Expires": "", "Set-Cookie": "", "Strict-Transport-Security": "", "Refresh":"", "Access-Control-Allow-Origin": "", "X-XSS-Protection": "", "X-WebKit-CSP":"", "X-Content-Security-Policy": "", "Content-Security-Policy": "", "X-Content-Type-Options": "", "X-Powered-By": "", "X-UA-Compatible": "", "X-Content-Duration": "", "Upgrade-Insecure-Requests": "", "X-Request-ID": "", "ETag": "", "Accept-Patch": "" } } 
0
Sep 12 '16 at
source share

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 used Visual Studio code and I had to add it to my launch configuration

 "outputCapture": "std" 

If you are working in an IDE, run it directly from the command line to ensure that the IDE is not causing a problem.

0
Aug 19 '19 at 2:05
source share



All Articles