Socket
Socket
Sign inDemoInstall

morgan

Package Overview
Dependencies
1
Maintainers
6
Versions
26
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    morgan

http request logger middleware for node.js


Version published
Maintainers
6
Install size
15.7 kB
Created

Package description

What is morgan?

Morgan is a middleware for Node.js that enables HTTP request logging. It is commonly used with Express.js applications to log information about incoming requests, which can be helpful for debugging, monitoring, and analytics purposes.

What are morgan's main functionalities?

Logging HTTP requests

This code sets up an Express server and uses Morgan to log all incoming HTTP requests in the 'combined' Apache format.

const express = require('express');
const morgan = require('morgan');
const app = express();

app.use(morgan('combined'));

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Customizing log formats

This code demonstrates how to customize the log format to include specific details such as the HTTP method, URL, status code, content length, and response time.

const express = require('express');
const morgan = require('morgan');
const app = express();

app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Creating custom tokens

This code shows how to create a custom token 'id' that can be used in the log format. The token function returns a value from the request object, which is then logged.

const express = require('express');
const morgan = require('morgan');
const app = express();

morgan.token('id', function getId(req) {
  return req.id;
});

app.use(morgan(':id :method :url'));

app.get('/', (req, res) => {
  req.id = 'abc123';
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Writing logs to a file

This code snippet demonstrates how to configure Morgan to write logs to a file named 'access.log' instead of outputting to the console.

const fs = require('fs');
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();

const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });

app.use(morgan('combined', { stream: accessLogStream }));

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Other packages similar to morgan

Readme

Source

morgan NPM version Build Status Coverage Status

Logging middleware for node.js http apps.

Named after Dexter, a show you should not watch until completion.

API

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

var app = express()
app.use(morgan())

morgan(options)

Morgan may be passed options to configure the logging output. The options may be passed as a predefined format, formatting string, function, or object.

morgan() // default
morgan('short')
morgan('tiny')
morgan({ format: 'dev', immediate: true })
morgan(':method :url - :referrer')
morgan(':req[content-type] -> :res[content-type]')
morgan(function(tokens, req, res){ return 'some format string' })
morgan({ format: 'dev', skip: function(req, res){ return res.statusCode === 304; }})
Predefined Formats
  • default - Standard output.
  • short - Shorter than default, also including response time.
  • tiny - The minimal.
  • dev - Concise output colored by response status for development use.
Options

Morgan accepts these properties in the options object.

  • format - Format string or Setting, see below for format tokens.
  • stream - Output stream, defaults to stdout.
  • buffer - Buffer duration, defaults to 1000 ms when true.
  • immediate - Write log line on request instead of response (for response times).
  • skip - Function to determine if logging is skipped, called as skip(req, res), defaults to false.

All default formats are defined this way, however the api is also public:

morgan.format('name', 'string or function')
Tokens
  • :req[header] ex: :req[Accept]
  • :res[header] ex: :res[Content-Length]
  • :http-version
  • :response-time
  • :remote-addr
  • :date
  • :method
  • :url
  • :referrer
  • :user-agent
  • :status

To define a token, simply invoke morgan.token() with the name and a callback function. The value returned is then available as ":type" in this case:

morgan.token('type', function(req, res){ return req.headers['content-type']; })

License

The MIT License (MIT)

Copyright (c) 2014 Jonathan Ong me@jongleberry.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

FAQs

Last updated on 21 May 2014

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc