morgan

repository·master·Indexed 27 days ago

https://github.com/expressjs/morgan

HTTP request logger middleware for Node.js (version 1.11.0). It allows developers to log request details to stdout or files using predefined formats like 'combined', 'common', 'dev', 'short', and 'tiny', or via custom format strings and tokens. Features include the ability to define custom tokens with morgan.token(), compile format strings with morgan.compile(), and configure logging behavior via options such as 'immediate', 'skip', and 'stream'.

Tokens
1.7K
Snippets
5
Records
14
Agent score
43%

What's inside morgan

  1. Configure morgan options

    master

    The options object in morgan(format, options) accepts the following properties:

    • immediate: (Boolean) Write the log line on request instead of response. Note that response data (like status code or content length) will not be available.
    • skip: (Function) A function skip(req, res) that returns true to skip logging.
    • stream: (Stream) The output stream for writing log lines. Defaults to process.stdout.
    // Example: only log error responses
    morgan('combined', {
      skip: function (req, res) { return res.statusCode < 400 }
    })
  2. Integrate morgan with Express

    master

    To use morgan in an Express application, require it and pass the desired format to app.use().

    var express = require('express')
    var morgan = require('morgan')
    
    var app = express()
    
    app.use(morgan('combined'))
    
    app.get('/', function (req, res) {
      res.send('hello, world!')
    })
  3. Log requests to a file using a write stream

    master

    To log to a file instead of stdout, create a write stream using Node's fs module and pass it to the stream option in morgan.

    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!')
    })
  4. Define new custom tokens with morgan.token()

    master

    You can define new tokens by calling morgan.token(name, callback). The callback function is called with req and res and should return a string. Calling morgan.token() with an existing name will overwrite the previous definition.

    morgan.token('type', function (req, res) { return req.headers['content-type'] })
  5. Compile a format string with morgan.compile()

    master
    Use morgan.compile(format) to transform a format string (utilizing :token-name syntax) into a function that accepts (tokens, req, res). This is useful for advanced custom formatting logic.
  6. Use morgan(format, options) to create logger middleware

    master

    Create a new morgan logger middleware function. The format argument can be a predefined name (string), a custom format string using tokens, or a function that produces a log entry.

    Format Function Arguments:

    • tokens: An object containing all defined tokens.
    • req: The HTTP request object.
    • res: The HTTP response object.

    The function should return a string for the log line, or undefined/null to skip logging.

  7. Use predefined morgan formats

    master

    Morgan provides several built-in format strings:

    • combined: Standard Apache combined log output.
    • common: Standard Apache common log output.
    • dev: Concise, color-coded output for development (status codes are colored).
    • short: A shorter format including response time.
    • tiny: The minimal output format.
  8. Reference available morgan tokens

    master

    Tokens are referenced in format strings using the : prefix.

    Standard Tokens:

    • :date[format]: Current UTC date/time. Formats: clf, iso, or web (default).
    • :http-version: The HTTP version of the request.
    • :method: The HTTP method.
    • :pid: The Node.js process ID.
    • :referrer: The Referrer header.
    • :remote-addr: The remote address (req.ip or socket address).
    • :remote-user: Authenticated user (Basic auth).
    • :req[header]: A specific request header.
    • :res[header]: A specific response header.
    • :response-time[digits]: Time between request and response headers written (ms). digits defaults to 3.
    • :status: The HTTP response status code.
    • :total-time[digits]: Time between request and response finished (ms). digits defaults to 3.
    • :url: The request URL.
    • :user-agent: The User-Agent header.
  9. Define custom morgan tokens

    master

    You can extend morgan's logging capabilities by defining custom tokens using morgan.token(name, fn). The function fn receives (req, res, [args]) and should return the string value to be logged.

    Example of defining a custom token:

  10. Register a named format

    master

    Use morgan.format(name, fmt) to register a new named format. This allows you to use the name as a string in the morgan() middleware factory.

    • name: The string identifier for the format.
    • fmt: A format string or a function that generates the log line.
  11. Initialize morgan middleware

    master

    Use morgan(format, options) to create an HTTP request logger middleware.

    • format: A string representing a predefined format (like 'dev', 'combined', 'tiny'), a custom format string with tokens, or a function.
    • options: An optional configuration object:
      • immediate: If true, logs the request immediately instead of waiting for the response to finish.
      • skip: A function (req, res) => boolean that determines if a log entry should be skipped.
      • stream: A writable stream to which logs are written (defaults to process.stdout).
      • buffer: A number representing the buffer duration in milliseconds. If provided, logs are buffered and flushed at intervals.