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
winston
Winston is a versatile logging library for Node.js. Unlike Morgan, which is specifically designed for HTTP request logging, Winston can be used for general-purpose application logging. It supports multiple transports (e.g., console, file, database) and is highly configurable.
pino
Pino is a very low-overhead Node.js logger. It is designed for speed and can be significantly faster than other logging solutions like Morgan, especially in high-throughput scenarios. Pino focuses on JSON logging and offers different log levels and custom serializers.
bunyan
Bunyan is a simple and fast JSON logging library for Node.js services. Like Pino, it focuses on JSON logging. Bunyan provides a set of standard log levels and includes a CLI tool for pretty-printing log files. It is more similar to Winston in terms of features but with a focus on JSON.
morgan
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()
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.