middleware-logging
v0.1.0
Published
middleware-logging is a simple logging middleware for Express.js applications. It logs incoming requests and their details to the console.
Maintainers
Readme
middleware-logging
Flexible and extensible request/response logging middleware for Express.
middleware-logging is an Express middleware for structured HTTP request logging. It supports request and response body logging, execution time measurement, response status and size logging, configurable endpoint exclusion, and customizable context enrichment.
Designed for production applications, it allows applications to inject their own logic for correlation IDs, distributed tracing, masking sensitive data, or encrypting logged content without modifying the middleware.
Examples:
- mongo-modular-sample: REST API with MongoDB.
- sql-modular-sample: REST API with MySQL.
- sql-simple-modular-sample: REST API with PostgreSQL.
Features
- Request logging
- Response body logging
- Request duration measurement
- HTTP status logging
- Response size logging
- Skip logging for selected endpoints
- Structured logging
- Runtime configuration
- Correlation ID and custom context support
- Request data masking or encryption
- Response data masking or encryption
- Logger-agnostic design
Installation
npm install middleware-loggingBasic Usage
import express from "express"
import { MiddlewareLogger } from "middleware-logging"
const app = express()
const logger = new MiddlewareLogger(
(message, context) => {
console.log(message, context)
},
{
log: true,
request: "request",
response: "response",
duration: "duration",
status: "status",
size: "size",
},
)
app.use(logger.log)Configuration
interface MiddlewareLogConfig {
log?: boolean
separate?: boolean
skips?: string
request?: string
response?: string
duration?: string
status?: string
size?: string
}| Property | Description |
| ---------- | -------------------------------------------------- |
| log | Enable or disable logging |
| separate | Write request and response as separate log entries |
| skips | Comma-separated list of endpoints to ignore |
| request | Field name for request body |
| response | Field name for response body |
| duration | Field name for execution time |
| status | Field name for HTTP status |
| size | Field name for response size |
Add Custom Context
Applications often need to include additional information in every log entry.
Examples include:
- Correlation ID
- Request ID
- Trace ID
- User ID
- Tenant ID
- Client IP
- Session ID
Use buildContext to enrich the structured log before it is written.
const logger = new MiddlewareLogger(write, config, (req, context) => {
context.correlationId = req.header("X-Correlation-Id") ?? ""
context.clientIp = req.ip
return context
})Protect Sensitive Request Data
Sensitive information should not appear in application logs.
Use encryptRequest to sanitize or encrypt request bodies before logging.
const logger = new MiddlewareLogger(write, config, undefined, undefined, (body) => {
return JSON.stringify({
...body,
password: "***",
confirmPassword: "***",
})
})You may also encrypt the entire payload before writing it to the log.
Protect Sensitive Response Data
Use encryptResponse to sanitize or encrypt response bodies.
const logger = new MiddlewareLogger(write, config, undefined, (response) => {
return response.replace(/"accessToken":"[^"]+"/, '"accessToken":"***"')
})Separate Request and Response Logs
Enable separate logging when request and response should be written independently.
{
separate: true
}Example
POST /users
{
request: ...
}POST /users
{
response: ...,
status: 201,
duration: 18.7
}Skip Endpoints
Ignore health checks or other endpoints.
{
skips: "/health,/metrics"
}Runtime Configuration
The library provides MiddlewareController, allowing logging behavior to be updated without restarting the application.
Configuration can be changed at runtime, including:
- Enable or disable logging
- Update skipped endpoints
- Enable or disable request logging
- Enable or disable response logging
- Change field names
Utility Functions
The library includes helper functions for masking sensitive strings.
import { mask, maskMargin } from "middleware-logging"Example
mask("1234567890123456", 4, 4, "*")Result
1234********3456Design Philosophy
middleware-logging focuses on extensibility rather than assumptions.
Instead of embedding application-specific logic, it provides extension points that allow applications to customize logging behavior.
buildContextenriches log entries with custom metadata.encryptRequestsanitizes or encrypts request bodies.encryptResponsesanitizes or encrypts response bodies.
This keeps the middleware reusable across different applications while allowing each project to implement its own logging and security policies.
Related Projects
| Library | Responsibility |
| ------------------------------------------------------------------------ | ---------------------------------------- |
| health-service | Health checks |
| config-plus | Configuration |
| logger-core | Structured logging |
| validation-core | Data validation |
| rabbitmq-transport | RabbitMQ transport and Health Check |
| activemq | ActiveMQ transport and Health Check |
| kafka-plus | Kafka transport and Health Check |
| google-pubsub | Google Pubsub transport and Health Check |
| nats-plus | NATS transport and Health Check |
| ibmmq-plus | IBM MQ transport and Health Check |
| redis-messaging | Redis Pubsub transport and Health Check |
| mysql2-core | MySQL access and Health Check |
| postgres-kit | PostgreSQL access and Health Check |
| mongodb-kit | MongoDB access and Health Check |
License
MIT
