Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS morgan log only route request

Im using NodeJS web framework Expressjs and one middleware to log requests to a file (morgan).

My conf:

// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(__dirname + '/logs/access.log', {flags: 'a'})

// setup the logger
app.use(logger('short', {stream: accessLogStream}))

And my log looks like:

192.168.1.3 - GET /signup HTTP/1.1 304 - - 19.194 ms 
192.168.1.3 - GET /assets/css/admin/module.admin.stylesheet-complete.sidebar_type.collapse.no_min2.css HTTP/1.1 304 - - 15.500 ms 
192.168.1.3 - GET /assets/components/library/jquery/jquery.min.js?v=v1.0.3-rc2&amb;sv=v0.0.1.1 HTTP/1.1 304 - - 14.244 ms 

Is there some way to ONLY log route request? for example if user enters /signup/:

192.168.1.3 - GET /signup HTTP/1.1 304 - - 19.194 ms

and not the assets required for the route.

Thanks in advance.

like image 934
mdv Avatar asked Nov 15 '14 06:11

mdv


People also ask

How do you use Morgan logger Express?

To use morgan in your Express server, you can invoke an instance and pass as an argument in the . use() middleware before your HTTP requests. morgan comes with a suite of presets, or predefined format strings, to create a new logger middleware with built-in format and options.

How do you log in with Morgan?

This means even if your application is using some custom HTTP headers, you can still use morgan to log them. All you need to do is first define your own token and use it for your log format. To create a custom token, you need to invoke morgan. token() and pass the name and a callback function to it.

Can I use Morgan in production?

Yes! It is all right to use Morgan as a logger on production mode. Arguably, if I can generalize to answer your question, the best practice in production is to log as many details as possible. The idea is that the logs on your server show you as much relevant information as you need.

What is Morgan logger?

Morgan is a popular HTTP request middleware logger for Node. js and basically used as a logger. It can be used with node js' winston package to consolidate HTTP request data logs with other information.


1 Answers

I had the same problem, I've found simple solution, maybe it will help somebody. If you use express.static you can move this call above morgan call, for example:

app.use(express.static(__dirname + '/public'));
...
app.use(logger('short'));

Static assets won't be logged. Notice: your assets files must exist, otherwise they will be still logged (tested in express 4.12).

like image 129
Kris Avatar answered Nov 02 '22 18:11

Kris