Convert Figma logo to code with AI

expressjs logomorgan

HTTP request logger middleware for node.js

7,933
531
7,933
27

Top Related Projects

22,753

A logger for just about everything.

14,148

🌲 super fast, all natural json logger

A port of log4js to node.js

a simple and fast JSON logging module for node.js services

8,911

Highly configurable logging utility

11,101

A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers

Quick Overview

Morgan is an HTTP request logger middleware for Node.js. It is a popular logging library that can be used to log incoming requests and their responses in a web application. It provides a flexible and customizable way to log request and response data, making it useful for debugging, monitoring, and analyzing web traffic.

Pros

  • Flexible Logging: Morgan allows for highly customizable logging, with the ability to specify the format of the log output and the data to be logged.
  • Middleware Integration: Morgan integrates seamlessly with Express.js and other Node.js web frameworks, making it easy to set up and use in web applications.
  • Performance: Morgan is designed to be efficient and performant, with minimal impact on the overall performance of the web application.
  • Community Support: Morgan has a large and active community of users and contributors, ensuring ongoing development and support.

Cons

  • Limited Functionality: While Morgan is a powerful logging tool, it may not provide all the features and functionality that some developers may require for more advanced logging and monitoring needs.
  • Dependency on Express.js: Morgan is primarily designed to work with Express.js, and may not be as easily integrated with other web frameworks or Node.js applications that do not use Express.js.
  • Potential Security Concerns: Depending on the data being logged, there may be potential security risks if sensitive information is inadvertently included in the log output.
  • Lack of Advanced Filtering: Morgan's logging capabilities are relatively basic, and may not provide the advanced filtering and searching capabilities that some developers may require for more complex logging needs.

Code Examples

Here are a few examples of how to use Morgan in a Node.js/Express.js application:

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

const app = express();

// Use Morgan as middleware to log all requests
app.use(morgan('combined'));

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

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

This example sets up a basic Express.js application and uses Morgan to log all incoming requests using the 'combined' log format.

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

const app = express();

// Use Morgan to log only errors
app.use(morgan('dev', {
  skip: (req, res) => res.statusCode < 400
}));

app.get('/', (req, res) => {
  res.status(200).send('OK');
});

app.get('/error', (req, res) => {
  res.status(500).send('Internal Server Error');
});

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

This example uses Morgan to log only error responses (status codes 400 and above) using the 'dev' log format.

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

const app = express();

// Use Morgan to log to a file
const accessLogStream = fs.createWriteStream('access.log', { flags: 'a' });
app.use(morgan('combined', { stream: accessLogStream }));

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

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

This example uses Morgan to log all incoming requests to a file named 'access.log' using the 'combined' log format.

Getting Started

To get started with Morgan, you can install it using npm:

npm install morgan

Once installed, you can use Morgan as middleware in your Express.js application, as shown in the examples above. You can customize the log format, specify which requests to log, and even log to a file or other output stream.

Here's a basic example of how to use Morgan in an Express.js application:

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

const app = express();

// Use Morgan to log all requests
app.use(morgan('dev'));

// Define your routes and other middleware here
app.get('/', (

Competitor Comparisons

22,753

A logger for just about everything.

Pros of Winston

  • More flexible and customizable logging options
  • Supports multiple transports (file, console, database, etc.)
  • Offers log levels and filtering capabilities

Cons of Winston

  • Steeper learning curve due to more complex configuration
  • Requires more setup for basic logging compared to Morgan

Code Comparison

Morgan (HTTP request logging):

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

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

Winston (General-purpose logging):

const winston = require('winston');
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [new winston.transports.Console()]
});

logger.info('Hello, Winston!');

Morgan is specifically designed for HTTP request logging in Express applications, making it simpler to set up for that purpose. It provides pre-defined logging formats and is easy to integrate with Express middleware.

Winston, on the other hand, is a more general-purpose logging library that can be used in various contexts, not just for HTTP requests. It offers greater flexibility in terms of log formatting, storage options, and custom transports.

While Morgan excels at its specific task of HTTP logging, Winston provides a more comprehensive logging solution for applications with diverse logging needs. The choice between the two depends on the specific requirements of your project and the level of customization you need for your logging system.

14,148

🌲 super fast, all natural json logger

Pros of Pino

  • Higher performance and lower overhead compared to Morgan
  • More flexible and customizable logging options
  • Built-in support for JSON logging, making it easier to parse and analyze logs

Cons of Pino

  • Steeper learning curve due to more advanced features
  • Requires additional configuration for HTTP request logging (Morgan's primary focus)
  • May be overkill for simple logging needs in small projects

Code Comparison

Morgan:

const morgan = require('morgan');
app.use(morgan('combined'));

Pino:

const pino = require('pino-http')();
app.use(pino);

app.get('/', (req, res) => {
  req.log.info('Hello world');
  res.send('hello world');
});

Summary

Morgan is a simpler, more straightforward logging middleware specifically designed for HTTP request logging in Express applications. It's easy to set up and use, making it ideal for basic logging needs.

Pino, on the other hand, is a more powerful and flexible logging library that can be used for various logging purposes, including HTTP request logging. It offers better performance and more advanced features, but may require more setup and configuration.

Choose Morgan for quick and easy HTTP request logging in small to medium-sized Express applications. Opt for Pino when you need high-performance logging, advanced customization options, or JSON-formatted logs for easier parsing and analysis in larger, more complex applications.

A port of log4js to node.js

Pros of log4js-node

  • More flexible and configurable logging options
  • Supports multiple appenders for different output destinations
  • Offers hierarchical logging levels for fine-grained control

Cons of log4js-node

  • Steeper learning curve due to more complex configuration
  • Potentially higher overhead for simple logging needs
  • Requires more setup code compared to Morgan's simplicity

Code Comparison

Morgan:

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

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

log4js-node:

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

log4js.configure({
  appenders: { console: { type: 'console' } },
  categories: { default: { appenders: ['console'], level: 'info' } }
});

const logger = log4js.getLogger();
app.use(log4js.connectLogger(logger, { level: 'info' }));

Key Differences

  • Morgan is specifically designed for HTTP request logging in Express.js applications, while log4js-node is a more general-purpose logging framework.
  • log4js-node offers more advanced features like log rotation, multiple output formats, and custom appenders.
  • Morgan provides pre-defined logging formats, making it easier to get started quickly.
  • log4js-node allows for more granular control over log levels and categories.

Use Cases

  • Choose Morgan for simple, out-of-the-box HTTP request logging in Express.js applications.
  • Opt for log4js-node when you need more advanced logging capabilities, multiple output destinations, or fine-grained control over log levels and categories.

a simple and fast JSON logging module for node.js services

Pros of Bunyan

  • More structured logging with JSON output
  • Supports log levels and child loggers for better organization
  • Offers built-in CLI tools for log analysis

Cons of Bunyan

  • Steeper learning curve compared to Morgan's simplicity
  • Requires more setup and configuration
  • May be overkill for simple logging needs in small projects

Code Comparison

Morgan:

const morgan = require('morgan');
app.use(morgan('combined'));

Bunyan:

const bunyan = require('bunyan');
const log = bunyan.createLogger({name: 'myapp'});
log.info('Hello World');

Key Differences

  • Morgan is designed specifically for HTTP request logging in Express.js, while Bunyan is a more general-purpose logging library.
  • Morgan outputs logs in various predefined formats, whereas Bunyan uses structured JSON logging.
  • Bunyan provides more advanced features like log levels, child loggers, and serializers, making it more suitable for complex applications.

Use Cases

  • Morgan: Ideal for simple HTTP request logging in Express.js applications.
  • Bunyan: Better suited for larger applications requiring detailed, structured logging across different components.

Community and Maintenance

  • Morgan: Part of the Express.js ecosystem, widely used in web applications.
  • Bunyan: Standalone project with a strong focus on Node.js logging, actively maintained.

Both libraries have their strengths, and the choice depends on the specific needs of your project, its complexity, and your logging requirements.

8,911

Highly configurable logging utility

Pros of Signale

  • More versatile logging options with customizable loggers and themes
  • Supports interactive logging for progress bars and spinners
  • Cross-platform with consistent output styling

Cons of Signale

  • Heavier and more complex than Morgan for simple logging needs
  • Not specifically designed for HTTP request logging like Morgan

Code Comparison

Morgan (HTTP request logging):

const morgan = require('morgan');
app.use(morgan('combined'));

Signale (Custom logging):

const { Signale } = require('signale');
const options = {
  types: {
    error: { badge: '!!', color: 'red' },
    success: { badge: '✔', color: 'green' }
  }
};
const signale = new Signale(options);
signale.success('Operation successful');
signale.error('Operation failed');

Summary

Morgan is a lightweight, HTTP request logging middleware for Express.js, while Signale is a more feature-rich, general-purpose logging library. Morgan excels at simple, standardized HTTP logging, whereas Signale offers greater customization and interactive logging capabilities. Choose Morgan for straightforward Express.js request logging, and Signale for more complex, application-wide logging needs with enhanced visual output.

11,101

A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers

Pros of debug

  • More flexible and can be used in various environments, not limited to Express.js
  • Allows for namespaced debugging, making it easier to filter and manage debug output
  • Supports multiple output streams, including browser console

Cons of debug

  • Requires more setup and configuration for HTTP logging compared to Morgan
  • Lacks built-in predefined logging formats for common HTTP scenarios
  • May require additional parsing for detailed HTTP request/response information

Code Comparison

Morgan:

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

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

debug:

const express = require('express');
const debug = require('debug')('http');
const app = express();

app.use((req, res, next) => {
  debug(`${req.method} ${req.url}`);
  next();
});

Summary

Morgan is specifically designed for HTTP request logging in Express.js applications, offering pre-defined logging formats and easy setup. debug, on the other hand, is a more general-purpose debugging tool that can be used across various JavaScript environments. While debug provides more flexibility and granular control over debugging output, it requires more manual configuration for HTTP logging compared to Morgan's out-of-the-box solution.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

morgan

NPM Version NPM Downloads Build Status Coverage Status

HTTP request logger middleware for node.js

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

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install morgan

API

var morgan = require('morgan')

morgan(format, options)

Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry.

The format function will be called with three arguments tokens, req, and res, where tokens is an object with all defined tokens, req is the HTTP request and res is the HTTP response. The function is expected to return a string that will be the log line, or undefined / null to skip logging.

Using a predefined format string

morgan('tiny')

Using format string of predefined tokens

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

Using a custom format function

morgan(function (tokens, req, res) {
  return [
    tokens.method(req, res),
    tokens.url(req, res),
    tokens.status(req, res),
    tokens.res(req, res, 'content-length'), '-',
    tokens['response-time'](req, res), 'ms'
  ].join(' ')
})

Options

Morgan accepts these properties in the options object.

immediate

Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data from the response (like the response code, content length, etc.) cannot be logged.

skip

Function to determine if logging is skipped, defaults to false. This function will be called as skip(req, res).

// EXAMPLE: only log error responses
morgan('combined', {
  skip: function (req, res) { return res.statusCode < 400 }
})
stream

Output stream for writing log lines, defaults to process.stdout.

Predefined Formats

There are various pre-defined formats provided:

combined

Standard Apache combined log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
common

Standard Apache common log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
dev

Concise output colored by response status for development use. The :status token will be colored green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for information codes.

:method :url :status :response-time ms - :res[content-length]
short

Shorter than default, also including response time.

:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
tiny

The minimal output.

:method :url :status :res[content-length] - :response-time ms

Tokens

Creating new tokens

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

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

Calling morgan.token() using the same name as an existing token will overwrite that token definition.

The token function is expected to be called with the arguments req and res, representing the HTTP request and HTTP response. Additionally, the token can accept further arguments of it's choosing to customize behavior.

:date[format]

The current date and time in UTC. The available formats are:

  • clf for the common log format ("10/Oct/2000:13:55:36 +0000")
  • iso for the common ISO 8601 date time format (2000-10-10T13:55:36.000Z)
  • web for the common RFC 1123 date time format (Tue, 10 Oct 2000 13:55:36 GMT)

If no format is given, then the default is web.

:http-version

The HTTP version of the request.

:method

The HTTP method of the request.

:referrer

The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.

:remote-addr

The remote address of the request. This will use req.ip, otherwise the standard req.connection.remoteAddress value (socket address).

:remote-user

The user authenticated as part of Basic auth for the request.

:req[header]

The given header of the request. If the header is not present, the value will be displayed as "-" in the log.

:res[header]

The given header of the response. If the header is not present, the value will be displayed as "-" in the log.

:response-time[digits]

The time between the request coming into morgan and when the response headers are written, in milliseconds.

The digits argument is a number that specifies the number of digits to include on the number, defaulting to 3, which provides microsecond precision.

:status

The status code of the response.

If the request/response cycle completes before a response was sent to the client (for example, the TCP socket closed prematurely by a client aborting the request), then the status will be empty (displayed as "-" in the log).

:total-time[digits]

The time between the request coming into morgan and when the response has finished being written out to the connection, in milliseconds.

The digits argument is a number that specifies the number of digits to include on the number, defaulting to 3, which provides microsecond precision.

:url

The URL of the request. This will use req.originalUrl if exists, otherwise req.url.

:user-agent

The contents of the User-Agent header of the request.

morgan.compile(format)

Compile a format string into a format function for use by morgan. A format string is a string that represents a single log line and can utilize token syntax. Tokens are references by :token-name. If tokens accept arguments, they can be passed using [], for example: :token-name[pretty] would pass the string 'pretty' as an argument to the token token-name.

The function returned from morgan.compile takes three arguments tokens, req, and res, where tokens is object with all defined tokens, req is the HTTP request and res is the HTTP response. The function will return a string that will be the log line, or undefined / null to skip logging.

Normally formats are defined using morgan.format(name, format), but for certain advanced uses, this compile function is directly available.

Examples

express/connect

Sample 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!')
})

vanilla http server

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

var finalhandler = require('finalhandler')
var http = require('http')
var morgan = require('morgan')

// create "middleware"
var logger = morgan('combined')

http.createServer(function (req, res) {
  var done = finalhandler(req, res)
  logger(req, res, function (err) {
    if (err) return done(err)

    // respond to request
    res.setHeader('content-type', 'text/plain')
    res.end('hello, world!')
  })
})

write logs to a file

single file

Sample app that will log all requests in the Apache combined format to the file access.log.

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

var app = express()

// 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 }))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

log file rotation

Sample app that will log all requests in the Apache combined format to one log file per day in the log/ directory using the rotating-file-stream module.

var express = require('express')
var morgan = require('morgan')
var path = require('path')
var rfs = require('rotating-file-stream') // version 2.x

var app = express()

// create a rotating write stream
var accessLogStream = rfs.createStream('access.log', {
  interval: '1d', // rotate daily
  path: path.join(__dirname, 'log')
})

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

app.get('/', function (req, res) {
  res.send('hello, world!')
})

split / dual logging

The morgan middleware can be used as many times as needed, enabling combinations like:

  • Log entry on request and one on response
  • Log all requests to file, but errors to console
  • ... and more!

Sample app that will log all requests to a file using Apache format, but error responses are logged to the console:

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

var app = express()

// log only 4xx and 5xx responses to console
app.use(morgan('dev', {
  skip: function (req, res) { return res.statusCode < 400 }
}))

// log all requests to access.log
app.use(morgan('common', {
  stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
}))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

use custom token formats

Sample app that will use custom token formats. This adds an ID to all requests and displays it using the :id token.

var express = require('express')
var morgan = require('morgan')
var uuid = require('node-uuid')

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

var app = express()

app.use(assignId)
app.use(morgan(':id :method :url :response-time'))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

function assignId (req, res, next) {
  req.id = uuid.v4()
  next()
}

License

MIT

NPM DownloadsLast 30 Days