Skip to main content

Interface

interface LogData {
  method: string;
  url: string;
  statusCode: number;
  timeTaken: number;
  requestSize: number;
  responseSize: number;
  timestamp: Timestamp;
  headers: Record<string, string | string[] | undefined>;
  queryParams: Record<string, unknown>;
  body?: unknown;
  responseBody?: unknown;
  ipInfo?: IpInfo;
  error?: LogError;
  userAgent?: string;
  referer?: string;
  requestContentType?: string;
  responseContentType?: string;
  httpVersion?: string;
  requestId?: string;
  hostname?: string;
  logLevel?: LogLevel;
}

Core Fields

method

method
string
required
The HTTP method of the request (e.g., GET, POST, PUT, DELETE, PATCH).
{
  "method": "POST"
}

url

url
string
required
The complete URL path including query parameters. This is the originalUrl from Express, or url if originalUrl is not available.
{
  "url": "/api/users?page=1&limit=10"
}

statusCode

statusCode
number
required
The HTTP status code of the response (e.g., 200, 404, 500).
{
  "statusCode": 200
}

timeTaken

timeTaken
number
required
Time taken for the complete request-response cycle, measured in milliseconds with high precision using process.hrtime().
{
  "timeTaken": 45.234
}

requestSize

requestSize
number
required
Size of the request body in bytes. Calculated from the stringified request body or Content-Length header.
{
  "requestSize": 256
}

responseSize

responseSize
number
required
Size of the response body in bytes. Calculated from the stringified response body.
{
  "responseSize": 1024
}

timestamp

timestamp
Timestamp
required
Object containing ISO 8601 formatted timestamps for request start and response completion.
{
  "timestamp": {
    "request": "2024-03-20T10:30:00.000Z",
    "response": "2024-03-20T10:30:00.045Z"
  }
}

headers

headers
Record<string, string | string[] | undefined>
required
Request headers object. Headers specified in excludedHeaders option are filtered out. Header values can be strings or string arrays.
{
  "headers": {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
    "accept": "application/json",
    "content-type": "application/json",
    "accept-encoding": ["gzip", "deflate", "br"]
  }
}

queryParams

queryParams
Record<string, unknown>
required
Query parameters from the URL. Included only if logQueryParams option is true (default).
{
  "queryParams": {
    "page": "1",
    "limit": "10",
    "sort": "createdAt",
    "filter": ["active", "verified"]
  }
}

Optional Fields

body

body
unknown
Request body content. Included only if logBody option is true (default). Can be any valid JSON type.Fields specified in maskFields option will have their values replaced with "***MASKED***".
{
  "body": {
    "username": "john.doe",
    "email": "[email protected]",
    "password": "***MASKED***"
  }
}

responseBody

responseBody
unknown
Response body content. Included only if logResponse option is true (default). Can be any valid JSON type.Fields specified in maskFields option will have their values replaced with "***MASKED***".
{
  "responseBody": {
    "id": "123",
    "username": "john.doe",
    "email": "[email protected]",
    "createdAt": "2024-03-20T10:30:00.000Z"
  }
}

ipInfo

ipInfo
IpInfo
IP address information returned by the getIpInfo option function. Contains geolocation and other IP-related data.
{
  "ipInfo": {
    "ip": "203.0.113.42",
    "country": "US",
    "region": "CA",
    "city": "San Francisco",
    "timezone": "America/Los_Angeles"
  }
}

error

error
LogError
Error information if an error occurred during request processing. Captured from middleware errors or response errors.
{
  "error": {
    "message": "Database connection failed",
    "name": "DatabaseError",
    "code": "ECONNREFUSED",
    "stack": "Error: Database connection failed\n    at Connection.connect (/app/db.js:45:10)..."
  }
}

userAgent

userAgent
string
The User-Agent header value from the request, providing information about the client application or browser.
{
  "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}

referer

referer
string
The Referer header value from the request, indicating the URL that referred to this request.
{
  "referer": "https://example.com/dashboard"
}

requestContentType

requestContentType
string
The Content-Type header of the request, indicating the media type of the request body.
{
  "requestContentType": "application/json"
}

responseContentType

responseContentType
string
The Content-Type header of the response, indicating the media type of the response body.
{
  "responseContentType": "application/json; charset=utf-8"
}

httpVersion

httpVersion
string
The HTTP protocol version used for the request (e.g., 1.0, 1.1, 2.0).
{
  "httpVersion": "1.1"
}

requestId

requestId
string
Request ID from the X-Request-ID header or auto-generated if autoGenerateRequestId option is enabled.Useful for distributed tracing and correlating logs across services.
{
  "requestId": "550e8400-e29b-41d4-a716-446655440000"
}

hostname

hostname
string
The hostname of the server handling the request, from req.hostname or Host header.
{
  "hostname": "api.example.com"
}

logLevel

logLevel
LogLevel
The log level for this request, determining which console method is used (console.log, console.warn, or console.error).Set by customLogLevel option or determined automatically:
  • 'error' if error is present
  • 'warn' if status code >= 400
  • 'info' otherwise
{
  "logLevel": "info"
}

Complete Example

Successful Request

{
  "method": "POST",
  "url": "/api/users",
  "statusCode": 201,
  "timeTaken": 123.45,
  "requestSize": 256,
  "responseSize": 512,
  "timestamp": {
    "request": "2024-03-20T10:30:00.000Z",
    "response": "2024-03-20T10:30:00.123Z"
  },
  "headers": {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
    "accept": "application/json",
    "content-type": "application/json"
  },
  "queryParams": {},
  "body": {
    "username": "john.doe",
    "email": "[email protected]",
    "password": "***MASKED***"
  },
  "responseBody": {
    "id": "123",
    "username": "john.doe",
    "email": "[email protected]",
    "createdAt": "2024-03-20T10:30:00.123Z"
  },
  "ipInfo": {
    "ip": "203.0.113.42",
    "country": "US",
    "city": "San Francisco"
  },
  "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
  "requestContentType": "application/json",
  "responseContentType": "application/json; charset=utf-8",
  "httpVersion": "1.1",
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "hostname": "api.example.com",
  "logLevel": "info"
}

Failed Request with Error

{
  "method": "GET",
  "url": "/api/users/999",
  "statusCode": 404,
  "timeTaken": 45.23,
  "requestSize": 0,
  "responseSize": 128,
  "timestamp": {
    "request": "2024-03-20T10:35:00.000Z",
    "response": "2024-03-20T10:35:00.045Z"
  },
  "headers": {
    "user-agent": "curl/7.68.0",
    "accept": "*/*"
  },
  "queryParams": {},
  "responseBody": {
    "error": "User not found",
    "code": "USER_NOT_FOUND"
  },
  "error": {
    "message": "User not found",
    "name": "NotFoundError",
    "code": "USER_NOT_FOUND"
  },
  "userAgent": "curl/7.68.0",
  "responseContentType": "application/json",
  "httpVersion": "1.1",
  "requestId": "660e9511-f30c-52e5-b827-557766551111",
  "hostname": "api.example.com",
  "logLevel": "warn"
}

Server Error

{
  "method": "POST",
  "url": "/api/orders",
  "statusCode": 500,
  "timeTaken": 2345.67,
  "requestSize": 512,
  "responseSize": 256,
  "timestamp": {
    "request": "2024-03-20T10:40:00.000Z",
    "response": "2024-03-20T10:40:02.345Z"
  },
  "headers": {
    "user-agent": "axios/1.6.0",
    "accept": "application/json",
    "content-type": "application/json"
  },
  "queryParams": {},
  "body": {
    "items": [
      { "id": "1", "quantity": 2 }
    ],
    "paymentToken": "***MASKED***"
  },
  "responseBody": {
    "error": "Internal Server Error",
    "message": "Database connection failed"
  },
  "error": {
    "message": "Database connection failed",
    "name": "DatabaseError",
    "code": "ECONNREFUSED",
    "stack": "Error: Database connection failed\n    at Connection.connect (/app/db.js:45:10)..."
  },
  "userAgent": "axios/1.6.0",
  "requestContentType": "application/json",
  "responseContentType": "application/json",
  "httpVersion": "1.1",
  "requestId": "770f0622-040d-63f6-c938-668877662222",
  "hostname": "api.example.com",
  "logLevel": "error"
}

Usage

The LogData structure is:
  1. Generated automatically by the logger middleware for each request
  2. Passed to the onLog callback if provided in options
  3. Passed to customLogLevel for determining log level
  4. Passed to customFormatter for custom formatting
  5. Logged to console as JSON (unless custom formatter returns different format)

Accessing in onLog Callback

logger({
  onLog: async (logData: LogData) => {
    // Access any field from LogData
    console.log(`Request to ${logData.url} took ${logData.timeTaken}ms`);
    
    // Send to external service
    if (logData.statusCode >= 400) {
      await alertService.notify({
        url: logData.url,
        statusCode: logData.statusCode,
        error: logData.error
      });
    }
  }
})

Using in Custom Formatter

logger({
  customFormatter: (logData: LogData) => {
    // Transform LogData to custom format
    return {
      '@timestamp': logData.timestamp.response,
      'http.method': logData.method,
      'http.url': logData.url,
      'http.status_code': logData.statusCode,
      'http.response_time': logData.timeTaken,
      'user_agent.original': logData.userAgent,
      'error.message': logData.error?.message
    };
  }
})

See Also

Build docs developers (and LLMs) love