Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Express Log Every Call Made

Is there a way to just log every call made to my nodejs server. Literally just the URL of the call. I know this is possible because I saw a super quick example in a tutorial once but I have no idea where I saw it.

Here is a crappy example of what I am looking for:

app.listen(port, (call)=>{
    console.log(call);
    console.log(`Server running on http://localhost:${port}...`);
})
like image 605
Freddy Bonda Avatar asked Mar 06 '23 07:03

Freddy Bonda


2 Answers

Is there a way to just log every call made to my nodejs server?

There you go: https://github.com/expressjs/morgan

Example

Simple app that will log all request in the Apache combined format to STDOUT

var express = require('express')
var morgan = require('morgan')

var app = express()

app.use(morgan('combined'))

app.get('/', function (req, res) {
  res.send('hello, world!')
})
like image 177
You Nguyen Avatar answered Mar 23 '23 18:03

You Nguyen


Since the morgan answer has been posted, if you plan on some custom-weird-logging-with-some-aditional-logic you can always create your own middleware:

var express = require('express')
var app = express()

/**
 *  Custom middleware with options
 */
var myUrlLogger = (upperCase)=>{
  
  if( typeof uppercase !== 'boolean' ){
    upperCase = true;
  }
  
  return (req,res,next) =>{
   
   console.log('Logging:', (upperCase ? req.url.toUpperCase() : req.url.toLowerCase()));
   
   next();
  }
}

// Set the middleware before your routes
app.use(myUrlLogger(false));

app.get('/', function (req, res) {
  res.send('hello, world!')
})
like image 39
darklightcode Avatar answered Mar 23 '23 18:03

darklightcode