![Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility](https://cdn.sanity.io/images/cgdhsj6q/production/97774ea8c88cc8f4bed2766c31994ebc38116948-1664x1366.png?w=400&fit=max&auto=format)
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
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.
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');
});
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 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 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.
HTTP request logger middleware for node.js
Named after Dexter, a show you should not watch until completion.
var express = require('express')
var morgan = require('morgan')
var app = express()
app.use(morgan('combined'))
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.
// a pre-defined name
morgan('combined')
// a format string
morgan(':remote-addr :method :url')
// a custom function
morgan(function (req, res) {
return req.method + ' ' + req.url
})
Morgan accepts these properties in the options object.
Buffer duration before writing logs to the stream
, defaults to false
. When
set to true
, defaults to 1000 ms
.
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 cannot be logged (like the response code).
Function to determine if logging is skipped, defaults to false
. This function
will be called as skip(req, res)
.
// only log error responses
morgan('combined', {
skip: function (req, res) { return res.statusCode < 400 }
})
Output stream for writing log lines, defaults to process.stdout
.
There are various pre-defined formats provided:
Standard Apache combined log output.
:remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
Standard Apache common log output.
:remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length]
Concise output colored by response status for development use. The :status
token will be colored red for server error codes, yellow for client error
codes, cyan for redirection codes, and uncolored for all other codes.
:method :url :status :response-time ms - :res[content-length]
Shorter than default, also including response time.
:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
The minimal output.
:method :url :status :res[content-length] - :response-time ms
:req[header]
ex: :req[Accept]
:res[header]
ex: :res[Content-Length]
:http-version
:response-time
:remote-addr
:remote-user
: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']; })
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
HTTP request logger middleware for node.js
The npm package morgan receives a total of 4,555,867 weekly downloads. As such, morgan popularity was classified as popular.
We found that morgan demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
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.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.