### Basic pino-http Example Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/COMPLETION_REPORT.txt A simple example demonstrating the basic usage of pino-http middleware. ```javascript const pinoHttp = require('pino-http')() app.use(pinoHttp()) app.use((req, res) => { res.end('Hello world!') }) ``` -------------------------------- ### Express Request Logging Example Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/serialization-and-output.md Example of setting up pino-http with dynamic custom properties and logging a GET request in an Express application. ```javascript const express = require('express') const pinoHttp = require('pino-http') const app = express() const logger = pinoHttp({ customProps: (req, res) => ({ userId: req.headers['x-user-id'] }) }) app.use(logger) app.get('/api/users', (req, res) => { req.log.info({ count: 5 }, 'fetching users') res.json([ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, // ... 3 more ]) }) app.listen(3000) ``` -------------------------------- ### Install pino-http Source: https://github.com/pinojs/pino-http/blob/master/README.md Install the pino-http package using npm. ```bash npm i pino-http --save ``` -------------------------------- ### Example Log Output with pino-pretty Source: https://github.com/pinojs/pino-http/blob/master/README.md Demonstrates the log output generated by the pino-http example when piped through 'pino-pretty' for formatted display. It shows logs for custom messages and request completion, including request and response details. ```bash $ node example.js | pino-pretty [2016-03-31T16:53:21.079Z] INFO (46316 on MBP-di-Matteo): something else req: { "id": 1, "method": "GET", "url": "/", "headers": { "host": "localhost:3000", "user-agent": "curl/7.43.0", "accept": "*/*" }, "remoteAddress": "::1", "remotePort": 64386 } [2016-03-31T16:53:21.087Z] INFO (46316 on MBP-di-Matteo): request completed res: { "statusCode": 200, "header": "HTTP/1.1 200 OK\r\nX-Powered-By: restify\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 11\r\nETag: W/\"b-XrY7u+Ae7tCTyyK7j1rNww\" Date: Thu, 31 Mar 2016 16:53:21 GMT\r Connection: keep-alive\r \r " } responseTime: 10 req: { "id": 1, "method": "GET", "url": "/", "headers": { "host": "localhost:3000", "user-agent": "curl/7.43.0", "accept": "*/*" }, "remoteAddress": "::1", "remotePort": 64386 } ``` -------------------------------- ### Manual Response Time Start Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/serialization-and-output.md Demonstrates how to manually set the start time for response time calculation when the logger middleware is not the first operation. ```javascript const http = require('http') const logger = require('pino-http')() http.createServer((req, res) => { res[logger.startTime] = Date.now() // Other processing... expensiveSetup(req, res) // Now call logger logger(req, res) res.end('hello') }).listen(3000) ``` -------------------------------- ### Koa Basic Setup Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/framework-integration.md Integrate pino-http with Koa by applying it as middleware in the application's chain. ```javascript const Koa = require('koa') const pinoHttp = require('pino-http') const app = new Koa() const logger = pinoHttp() // Wrap pino-http for Koa app.use(async (ctx, next) => { logger(ctx.req, ctx.res) await next() }) app.use(ctx => { ctx.log.info('handler') ctx.body = 'hello' }) app.listen(3000) ``` -------------------------------- ### Manual Start Time for Logging Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/quick-reference.md Manually set the start time for a request to be used by the logger, useful for custom server implementations. ```javascript const logger = pinoHttp() http.createServer((req, res) => { res[logger.startTime] = Date.now() doOtherWork() logger(req, res) }).listen(3000) ``` -------------------------------- ### Fastify Basic Setup Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/framework-integration.md Integrate pino-http with Fastify by disabling Fastify's default logger and adding pino-http as a request hook. ```javascript const fastify = require('fastify')({ logger: false // Disable Fastify's default logger }) const pinoHttp = require('pino-http') const pinoLogger = pinoHttp() // Add hook to wrap pino-http fastify.addHook('onRequest', async (request, reply) => { pinoLogger(request.raw, reply.raw) }) fastify.get('/', async (request, reply) => { request.raw.log.info('handler') return { hello: 'world' } }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Attach Start Time Manually with pinoHttp.startTime Source: https://github.com/pinojs/pino-http/blob/master/README.md Manually attach the start time to the res object using pinoHttp.startTime symbol to correct responseTime offset when pinoHttp is not the first middleware. ```javascript const http = require('http') const logger = require('pino-http')() const someImportantThingThatHasToBeFirst = require('some-important-thing') http.createServer((req, res) => { res[logger.startTime] = Date.now() someImportantThingThatHasToBeFirst(req, res) logger(req, res) res.log.info('log is available on both req and res'); res.end('hello world') }).listen(3000) ``` -------------------------------- ### Custom Format pino-http Example Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/COMPLETION_REPORT.txt An advanced example showing how to customize the log message format in pino-http. ```javascript const pinoHttp = require('pino-http') app.use(pinoHttp({ customReceivedMessage: function (req, res) { return 'request received' }, customReceivedObject: function (req, res, val) { return { ...val, custom: { foo: 'bar' } } }, customSuccessMessage: function (req, res) { return 'request completed' }, customErrorMessage: function (req, res, err) { return 'request failed' }, customSuccessObject: function (req, res, val) { return { ...val, custom: { foo: 'bar' } } }, customErrorObject: function (req, res, err, val) { return { ...val, custom: { foo: 'bar' } } } })) app.use((req, res) => { res.end('Hello world!') }) ``` -------------------------------- ### Manual Start Time for Logging Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/quick-reference.md Allows for manual setting of the request start time using a Symbol, which can be useful for custom logging logic before the middleware is invoked. ```APIDOC ## Manual Start Time ```js const logger = pinoHttp() http.createServer((req, res) => { res[logger.startTime] = Date.now() doOtherWork() logger(req, res) }).listen(3000) ``` ``` -------------------------------- ### Basic Express.js Setup with Pino-HTTP Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/framework-integration.md Set up pino-http middleware in an Express.js application for basic HTTP request logging. ```javascript const express = require('express') const pinoHttp = require('pino-http') const app = express() const logger = pinoHttp() app.use(logger) app.get('/', (req, res) => { res.send('hello') }) app.listen(3000) ``` -------------------------------- ### startTime Symbol Usage Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/internals.md Demonstrates how the startTime symbol is used to record the start time of a response and calculate the duration. ```javascript res[startTime] = Date.now() const responseTime = Date.now() - res[startTime] ``` -------------------------------- ### Example Response Time Values Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/serialization-and-output.md Shows typical numerical values for responseTime in milliseconds, including values over 2 seconds. ```json { "responseTime": 5, // 5ms "responseTime": 145, // 145ms "responseTime": 2050 // 2050ms (over 2 seconds) } ``` -------------------------------- ### Request Received Log Example Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/serialization-and-output.md Shows the structure of an optional log entry generated when a request first arrives, including level, time, PID, hostname, request details, and a message. ```json { "level": 30, "time": "2024-01-15T10:30:45.120Z", "pid": 12345, "hostname": "localhost", "req": { ... }, "msg": "request received", "v": 1 } ``` -------------------------------- ### Custom Attribute Keys Output Example Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/serialization-and-output.md Illustrates the log output structure when custom attribute keys are defined for request, response, error, and responseTime. ```json { "request": { ... }, // instead of "req" "response": { ... }, // instead of "res" "error": { ... }, // instead of "err" "duration_ms": 42 // instead of "responseTime" } ``` -------------------------------- ### Start Time Symbol Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/exported-symbols.md The `startTime` symbol is a unique symbol that can be used to attach a request start time to the response object, useful for calculating request duration. ```APIDOC ## Symbol: startTime ### Description A unique symbol used to record the start time of an HTTP request on the response object. ### Usage ```javascript const logger = require('pino-http')() http.createServer((req, res) => { res[logger.startTime] = Date.now() // ... other code ... logger(req, res) }).listen(3000) ``` ``` -------------------------------- ### Response Time Calculation Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/serialization-and-output.md Illustrates the formula for calculating request response time using Date.now() and a stored start time. ```javascript responseTime = Date.now() - res[startTime] ``` -------------------------------- ### Minimal HTTP Server Integration with Pino-HTTP Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/usage-examples.md Integrate pino-http into a basic Node.js HTTP server with minimal configuration. This setup logs all incoming requests and their completion. ```javascript const http = require('http') const pinoHttp = require('pino-http') const logger = pinoHttp() http.createServer((req, res) => { logger(req, res) res.end('hello') }).listen(3000) ``` ```json {"level":30,"time":"...","pid":...,"hostname":"...","msg":"request completed","res":{"statusCode":200,"header":"..."},"responseTime":15,"req":{"id":1,"method":"GET","url":"/","headers":{...}}} ``` -------------------------------- ### Use pino-http as Express middleware Source: https://github.com/pinojs/pino-http/blob/master/README.md Integrates pino-http into an Express application to log incoming requests and responses. Requires Express and pino-http to be installed. ```javascript const express = require('express') const logger = require('pino-http') const app = express() app.use(logger()) function handle (req, res) { req.log.info('something else') res.end('hello world') } app.listen(3000) ``` -------------------------------- ### Set Start Time for Response Time Calculation Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/logging-behavior.md Manually set the start time for response time calculation if the logger middleware is called after other initial processing. This ensures that the duration of subsequent operations is included in the response time. ```javascript const http = require('http') const logger = require('pino-http')() http.createServer((req, res) => { res[logger.startTime] = Date.now() someOtherProcessing(req, res) logger(req, res) // Will account for someOtherProcessing }).listen(3000) ``` -------------------------------- ### Native Node.js HTTP: Router Pattern Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/framework-integration.md Implement a simple routing pattern with Node.js's http module and pino-http. This example defines routes and associates them with handler functions that use the logger. ```javascript const http = require('http') const pinoHttp = require('pino-http') const logger = pinoHttp() const routes = { 'GET /': (req, res, log) => { log.info('home') res.end('home') }, 'GET /api/users': (req, res, log) => { log.info('fetching users') res.end(JSON.stringify([{ id: 1, name: 'Alice' }])) }, 'POST /api/users': (req, res, log) => { log.info('creating user') res.end('created') } } http.createServer((req, res) => { logger(req, res) const route = routes[`${req.method} ${req.url}`] if (route) { route(req, res, req.log) } else { res.statusCode = 404 res.end('not found') } }).listen(3000) ``` -------------------------------- ### Log Error Response Example with Pino-HTTP Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/serialization-and-output.md Demonstrates how pino-http logs an error response from an Express.js application. This includes server code and the resulting JSON log output. ```javascript const express = require('express') const pinoHttp = require('pino-http') const app = express() const logger = pinoHttp() app.use(logger) app.get('/api/users/:id', (req, res, next) => { if (isNaN(req.params.id)) { const err = new Error('Invalid user ID') err.statusCode = 400 return next(err) } // Simulate DB error const dbErr = new Error('Connection timeout') dbErr.code = 'ECONNREFUSED' res.statusCode = 500 res.err = dbErr res.end('error') }) app.listen(3000) ``` ```json { "level": 50, "time": "2024-01-15T10:30:45.187Z", "pid": 12345, "hostname": "localhost", "req": { "id": 2, "method": "GET", "url": "/api/users/invalid", "headers": { "host": "localhost:3000", "user-agent": "curl/7.43.0" }, "remoteAddress": "::1", "remotePort": 50205 }, "res": { "statusCode": 500, "header": "HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\n" }, "err": { "type": "Error", "message": "Connection timeout", "stack": "Error: Connection timeout\n at Object. (/app/routes.js:15:13)\n at Module._load (internal/modules/loader.js:926:17)" }, "responseTime": 67, "msg": "request errored", "v": 1 } ``` -------------------------------- ### Default Request Serializer Output Source: https://github.com/pinojs/pino-http/blob/master/README.md Example output of the default pinoHttp.stdSerializers.req, which generates a JSONifiable object from the HTTP request. ```json { "pid": 93535, "hostname": "your host", "level": 30, "msg": "my request", "time": "2016-03-07T12:21:48.766Z", "v": 0, "req": { "id": 42, "method": "GET", "url": "/", "headers": { "host": "localhost:50201", "connection": "close" }, "remoteAddress": "::ffff:127.0.0.1", "remotePort": 50202 } } ``` -------------------------------- ### Express Request Log Output (Completed) Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/serialization-and-output.md Example log output for a completed Express request, showing request and response details along with custom properties. ```json { "level": 30, "time": "2024-01-15T10:30:45.167Z", "pid": 12345, "hostname": "api.example.com", "userId": "user-456", "req": { "id": 1, "method": "GET", "url": "/api/users?role=admin", "headers": { "host": "api.example.com", "authorization": "Bearer token123", "user-agent": "Mozilla/5.0" }, "remoteAddress": "203.0.113.42", "remotePort": 54321 }, "res": { "statusCode": 200, "header": "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 512\r\nDate: Mon, 15 Jan 2024 10:30:45 GMT\r\n\r\n" }, "responseTime": 42, "msg": "request completed", "v": 1 } ``` -------------------------------- ### Direct Symbol Usage for Timestamp Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/exported-symbols.md Manually record the start time of a request using the startTime symbol before calling the logger middleware. ```javascript const logger = require('pino-http')() // In request handler http.createServer((req, res) => { res[logger.startTime] = Date.now() // ... other code ... logger(req, res) }).listen(3000) ``` -------------------------------- ### Express Request Log Output (Info) Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/serialization-and-output.md Example log output for an info message within an Express request handler, including dynamic custom properties. ```json { "level": 30, "time": "2024-01-15T10:30:45.125Z", "pid": 12345, "hostname": "api.example.com", "userId": "user-456", "count": 5, "msg": "fetching users", "v": 1 } ``` -------------------------------- ### Configure Pino-HTTP Logger Options Source: https://github.com/pinojs/pino-http/blob/master/README.md Configure various aspects of the pino-http logger, including custom request ID generation, serializers, log levels, custom messages, attribute keys, and additional properties. This setup reuses an existing pino logger instance. ```javascript 'use strict' const http = require('http') const server = http.createServer(handle) const { randomUUID } = require('node:crypto') const pino = require('pino') const logger = require('pino-http')({ // Reuse an existing logger instance logger: pino(), // Define a custom request id function genReqId: function (req, res) { const existingID = req.id ?? req.headers["x-request-id"] if (existingID) return existingID const id = randomUUID() res.setHeader('X-Request-Id', id) return id }, // Define custom serializers serializers: { err: pino.stdSerializers.err, req: pino.stdSerializers.req, res: pino.stdSerializers.res }, // Set to `false` to prevent standard serializers from being wrapped. wrapSerializers: true, // Logger level is `info` by default useLevel: 'info', // Define a custom logger level customLogLevel: function (req, res, err) { if (res.statusCode >= 400 && res.statusCode < 500) { return 'warn' } else if (res.statusCode >= 500 || err) { return 'error' } else if (res.statusCode >= 300 && res.statusCode < 400) { return 'silent' } return 'info' }, // Define a custom success message customSuccessMessage: function (req, res) { if (res.statusCode === 404) { return 'resource not found' } return `${req.method} completed` }, // Define a custom receive message customReceivedMessage: function (req, res) { return 'request received: ' + req.method }, // Define a custom error message customErrorMessage: function (req, res, err) { return 'request errored with status code: ' + res.statusCode }, // Override attribute keys for the log object customAttributeKeys: { req: 'request', res: 'response', err: 'error', responseTime: 'timeTaken' }, // Define additional custom request properties customProps: function (req, res) { return { customProp: req.customProp, // user request-scoped data is in res.locals for express applications customProp2: res.locals.myCustomData } } }) function handle (req, res) { logger(req, res) req.log.info('something else') res.log.info('just in case you need access to logging when only the response is in scope') res.end('hello world') } server.listen(3000) ``` -------------------------------- ### pinoHttp([opts], [stream]) Source: https://github.com/pinojs/pino-http/blob/master/README.md The main function to initialize the pino-http middleware. It accepts an optional options object and a stream for logging output. The options allow extensive customization of request and response logging. ```APIDOC ## pinoHttp([opts], [stream]) ### Description Initializes the pino-http middleware with customizable options. ### Parameters #### Options (`opts`) * `logger` (object): Parent pino instance for a child logger. * `genReqId` (function): Function to generate a request ID. Arguments: `(req, res)`. Returns: `string` or `number`. * `useLevel` (string): Logger level for response logging. Default: `info`. * `customLogLevel` (function): Custom function to determine log level. Arguments: `(req, res, err)`. Returns: `string`. * `autoLogging` (boolean or object): Enable/disable automatic logging. If object, can have `ignore` property. * `autoLogging.ignore` (function): Function to ignore requests. Arguments: `(req, res)`. Returns: `boolean`. * `stream` (stream): Destination stream for logs. Can also be passed as the second parameter. * `customReceivedMessage` (function): Custom message for received requests. Arguments: `(req, res)`. Returns: `string`. * `customReceivedObject` (function): Custom object for received requests. Arguments: `(req, res, loggableObject)`. Returns: `object`. * `customSuccessMessage` (function): Custom message for successful responses. Arguments: `(req, res)`. Returns: `string`. * `customSuccessObject` (function): Custom object for successful responses. Arguments: `(req, res, loggableObject)`. Returns: `object`. * `customErrorMessage` (function): Custom message for failed responses. Arguments: `(req, res, err)`. Returns: `string`. * `customErrorObject` (function): Custom object for failed responses. Arguments: `(req, res, err, loggableObject)`. Returns: `object`. * `customAttributeKeys` (object): Object to override default log attribute keys (e.g., `req`, `res`, `err`, `responseTime`). * `wrapSerializers` (boolean): Whether to wrap custom serializers. Defaults to `true`. * `customProps` (function or object): Additional properties to log. Arguments for function: `(req, res)`. Returns: `object`. * `quietReqLogger` (boolean): If true, `req.log` will only have `reqId` bound. Defaults to `false`. * `quietResLogger` (boolean): If true, `res.log` will only have `reqId` bound. Defaults to `false`. #### Stream * `stream` (stream): The destination stream for logs. This can also be passed as an option. ### Examples #### Use as Express middleware ```javascript const express = require('express') const logger = require('pino-http') const app = express() app.use(logger()) function handle (req, res) { req.log.info('something else') res.end('hello world') } app.listen(3000) ``` ``` -------------------------------- ### Basic Usage with HTTP Server Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/api-reference-pinohttp.md Demonstrates the basic integration of pino-http middleware with Node.js's built-in HTTP module. ```javascript const http = require('http') const pinoHttp = require('pino-http') const logger = pinoHttp() http.createServer((req, res) => { logger(req, res) req.log.info('handler logic') res.end('hello') }).listen(3000) ``` -------------------------------- ### Default Response Serializer Output Source: https://github.com/pinojs/pino-http/blob/master/README.md Example output of the default pinoHttp.stdSerializers.res, which generates a JSONifiable object from the HTTP response. ```json { "pid": 93581, "hostname": "myhost", "level": 30, "msg": "my response", "time": "2016-03-07T12:23:18.041Z", "v": 0, "res": { "statusCode": 200, "header": "HTTP/1.1 200 OK\r\nDate: Mon, 07 Mar 2016 12:23:18 GMT\r\nConnection: close\r\nContent-Length: 5\r\n\r\n" } } ``` -------------------------------- ### Basic HTTP Server Integration Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/README.md Integrates pino-http middleware with Node.js native HTTP server. Ensure logger is called before handler logic. ```javascript const http = require('http') const pinoHttp = require('pino-http') const logger = pinoHttp() http.createServer((req, res) => { logger(req, res) // ... handler logic res.end('response') }).listen(3000) ``` -------------------------------- ### pinoHttp Options Interface Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/types.md The `Options` interface defines all available configuration parameters for the `pinoHttp()` factory. These options allow for fine-grained control over logging behavior, including custom loggers, request ID generation, log levels, and message formatting. ```APIDOC ## pinoHttp Options Interface ### Description Complete configuration interface for the `pinoHttp()` factory. ### Type Parameters - `IM` (default: `IncomingMessage`): Request type - `SR` (default: `ServerResponse`): Response type - `CustomLevels` (default: `never`): Custom log level names ### Fields | Field | Type | Optional | Description | |---|---|---|---| | `logger` | `pino.Logger` | Yes | Parent logger for creating child instance | | `genReqId` | `GenReqId` | Yes | Custom request ID generator function | | `useLevel` | `pino.LevelWithSilent | CustomLevels` | Yes | Static log level for responses | | `stream` | `pino.DestinationStream` | Yes | Output stream for logs | | `autoLogging` | `boolean | AutoLoggingOptions` | Yes | Enable/disable automatic request/response logging | | `customLogLevel` | `(req, res, error?) => string` | Yes | Dynamic log level function (mutually exclusive with `useLevel`) | | `customReceivedMessage` | `(req, res) => string` | Yes | Custom message for request received event | | `customSuccessMessage` | `(req, res, responseTime) => string` | Yes | Custom message for successful response | | `customErrorMessage` | `(req, res, error) => string` | Yes | Custom message for failed response | | `customReceivedObject` | `(req, res, val?) => any` | Yes | Custom object structure for received event | | `customSuccessObject` | `(req, res, val) => any` | Yes | Custom object structure for successful response | | `customErrorObject` | `(req, res, error, val) => any` | Yes | Custom object structure for error response | | `customAttributeKeys` | `CustomAttributeKeys` | Yes | Override default log property names | | `wrapSerializers` | `boolean` | Yes | Wrap custom serializers with standard wrappers | | `customProps` | `(req, res) => object | object` | Yes | Additional properties to include in logs | | `quietReqLogger` | `boolean` | Yes | Remove full request from `req.log` | | `quietResLogger` | `boolean` | Yes | Remove full request from `res.log` | ``` -------------------------------- ### Configure pino-http with Custom Transport for Formatting Source: https://github.com/pinojs/pino-http/blob/master/README.md Customize log output format by passing a Pino transport, using 'pino-http-print' for formatting with options for destination, showing all logs, and translating time. ```javascript const logger = require('pino-http')({ quietReqLogger: true, // turn off the default logging output transport: { target: 'pino-http-print', // use the pino-http-print transport and its formatting output options: { destination: 1, all: true, translateTime: true } } }) ``` -------------------------------- ### Usage with Configuration Options Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/api-reference-pinohttp.md Illustrates advanced configuration of pino-http, including custom logger, log level, request ID generation, and custom log levels. ```javascript const pinoHttp = require('pino-http') const pino = require('pino') const logger = pinoHttp({ logger: pino(), useLevel: 'debug', genReqId: (req) => req.headers['x-request-id'] || generateId(), customLogLevel: (req, res, err) => { if (res.statusCode >= 500) return 'error' if (res.statusCode >= 400) return 'warn' return 'info' } }) ``` -------------------------------- ### Native Node.js HTTP: Basic Server Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/framework-integration.md Set up a basic HTTP server using Node.js's native http module and integrate pino-http for logging. The logger is applied directly to the request and response objects. ```javascript const http = require('http') const pinoHttp = require('pino-http') const logger = pinoHttp() http.createServer((req, res) => { logger(req, res) if (req.url === '/') { req.log.info('home page') res.end('hello') } else { res.statusCode = 404 res.end('not found') } }).listen(3000) ``` -------------------------------- ### Integrate pino-http with Fastify Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/usage-examples.md Shows how to disable Fastify's default logger and integrate pino-http as a request hook. ```javascript const fastify = require('fastify') const pinoHttp = require('pino-http') const app = fastify({ logger: false // Disable Fastify's default logger }) // Create pino-http logger const pinoLogger = pinoHttp() // Wrap as Fastify hook app.addHook('onRequest', async (request, reply) => { pinoLogger(request.raw, reply.raw) }) app.get('/', async (request, reply) => { request.raw.log.info('route handler') return 'hello' }) app.listen(3000) ``` -------------------------------- ### Basic HTTP Server with pino-http Source: https://github.com/pinojs/pino-http/blob/master/README.md Set up a basic Node.js HTTP server and integrate pino-http for logging requests and responses. The logger is applied to the request and response objects, and custom log messages can be added. ```javascript 'use strict' const http = require('http') const server = http.createServer(handle) const logger = require('pino-http')() function handle (req, res) { logger(req, res) req.log.info('something else') res.end('hello world') } server.listen(3000) ``` -------------------------------- ### pinoHttp(opts?, stream?) Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/api-reference-pinohttp.md The main factory function that creates an HTTP logging middleware. It can be configured with options or a stream destination. ```APIDOC ## pinoHttp(opts?, stream?) ### Description Creates and returns an HTTP logging middleware function. The middleware automatically captures incoming request and outgoing response details, calculates request duration, and logs the result. ### Signature ```typescript function pinoHttp( opts?: Options, stream?: pino.DestinationStream ): HttpLogger function pinoHttp( stream?: pino.DestinationStream ): HttpLogger ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | opts | `Options \| undefined` | No | — | Configuration object. If first argument is a stream-like object (has `_writableState` property), it is treated as the stream parameter instead. | | stream | `pino.DestinationStream \| undefined` | No | — | Destination stream for log output. Can also be passed via `opts.stream`. | ### Return Type ```typescript interface HttpLogger { (req: IM, res: SR, next?: () => void): void logger: pino.Logger } ``` The returned function is the middleware itself, callable as `logger(req, res)`. It also has a `.logger` property containing the underlying Pino logger instance. ### Throws - `Error`: When both `opts.useLevel` and `opts.customLogLevel` are provided simultaneously. These options are mutually exclusive. ### Usage Examples **Basic usage with HTTP server:** ```js const http = require('http') const pinoHttp = require('pino-http') const logger = pinoHttp() http.createServer((req, res) => { logger(req, res) req.log.info('handler logic') res.end('hello') }).listen(3000) ``` **With stream destination:** ```js const pinoHttp = require('pino-http') const { createWriteStream } = require('fs') const logStream = createWriteStream('./logs.jsonl') const logger = pinoHttp(logStream) ``` **With configuration options:** ```js const pinoHttp = require('pino-http') const pino = require('pino') const logger = pinoHttp({ logger: pino(), useLevel: 'debug', genReqId: (req) => req.headers['x-request-id'] || generateId(), customLogLevel: (req, res, err) => { if (res.statusCode >= 500) return 'error' if (res.statusCode >= 400) return 'warn' return 'info' } }) ``` **With middleware next() callback (for frameworks):** ```js const express = require('express') const pinoHttp = require('pino-http') const app = express() const logger = pinoHttp() app.use((req, res, next) => { logger(req, res, next) }) ``` **Accessing the underlying logger:** ```js const logger = pinoHttp() logger.logger.level = 'silent' logger.logger.info('message') ``` ``` -------------------------------- ### Change Custom Attribute Names Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/usage-examples.md Customize attribute names in log output for compatibility with other systems. This example renames default keys like 'req', 'res', 'err', and 'responseTime'. ```javascript const pinoHttp = require('pino-http') const logger = pinoHttp({ customAttributeKeys: { req: 'request', res: 'response', err: 'error', responseTime: 'duration_ms' } }) // Log output will have 'request', 'response', 'error', 'duration_ms' // instead of default 'req', 'res', 'err', 'responseTime' ``` -------------------------------- ### startTime Symbol Declaration Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/internals.md Declares a unique symbol used to prevent property conflicts. This symbol is used internally to store the response start timestamp for calculating response time. ```javascript const startTime = Symbol('startTime') ``` -------------------------------- ### Create Custom Pino Middleware Wrapper Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/framework-integration.md Use this wrapper for frameworks with non-standard middleware signatures. It ensures the logger function matches the expected signature. ```javascript const pinoHttp = require('pino-http') function createPinoMiddleware(options) { const logger = pinoHttp(options) // Return a function matching your framework's signature return function middleware(req, res, next) { logger(req, res, next) } } // Usage in your framework const logger = createPinoMiddleware({ customLogLevel: (req, res, err) => { if (res.statusCode >= 500) return 'error' if (res.statusCode >= 400) return 'warn' return 'info' } }) // Pass to your framework's middleware system app.use(logger) ``` -------------------------------- ### Get Function or Default Value Utility Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/internals.md Conditionally returns a function if the provided value is a function, otherwise returns a default value. Used for handling optional callback parameters. ```javascript function getFunctionOrDefault (value, defaultValue) { if (value && typeof value === 'function') { return value } return defaultValue } ``` -------------------------------- ### pinoHttp() Factory Function Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/MANIFEST.txt The main entry point for pino-http is the pinoHttp() factory function. It returns an HTTP logger middleware that can be used with Node.js HTTP servers and frameworks. ```APIDOC ## pinoHttp() ### Description The `pinoHttp()` function is a factory that creates and returns a Node.js HTTP logger middleware. This middleware can be integrated into various web frameworks or used with the native Node.js `http` module. ### Method Factory function ### Parameters This function accepts an optional `Options` object to configure the logger's behavior. Refer to `configuration.md` for a complete list of options. ### Return Type `HttpLogger` interface, which is a middleware function with signature `(req, res, next) => void`. ### Usage Example ```javascript const pinoHttp = require('pino-http') const http = require('http') const logger = pinoHttp({ // options go here }) const server = http.createServer((req, res) => { logger(req, res, () => { res.end('hello world') }) }) server.listen(3000) ``` ``` -------------------------------- ### CommonJS Default Import Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/exported-symbols.md Import the pino-http middleware factory using the default import syntax in CommonJS. ```javascript // Default import const pinoHttp = require('pino-http') ``` -------------------------------- ### Custom Request Serializer for Pino-HTTP Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/usage-examples.md Configure custom serializers to include additional request properties like userId and custom headers in logs. This example shows how to extend the default request serializer. ```javascript const pinoHttp = require('pino-http') const pino = require('pino') const logger = pinoHttp({ serializers: { req(req) { // Start with default serialized request const serialized = pino.stdSerializers.req(req) // Add custom properties if (req.user) { serialized.userId = req.user.id } // Add custom headers serialized.xCustomHeader = req.headers['x-custom'] return serialized } } }) ``` -------------------------------- ### Configure Auto-Logging Ignore Function Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/logging-behavior.md When autoLogging is configured with an ignore function, it is called during response events. Returning true skips all logging for that request. This example shows how to ignore health check requests. ```javascript const logger = pinoHttp({ autoLogging: { ignore: (req, res) => { // Don't log health checks return req.url === '/health' } } }) ``` -------------------------------- ### Log to File Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/quick-reference.md Direct pino-http logs to a specified file using a Node.js stream. Ensure the file path is correct. ```javascript const fs = require('fs') pinoHttp({ stream: fs.createWriteStream('logs.ndjson') }) ``` -------------------------------- ### startTime Symbol Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/exported-symbols.md A unique Symbol used internally to store the request start time on the response object. It is exposed publicly to allow manual timing when the middleware is not the first operation in a request handler. ```APIDOC ## Named Export: startTime Symbol ### Description A unique Symbol used to store the request start time on the response object. The internal symbol used to attach the start time timestamp to response objects. Exposed publicly to allow manual timing when the middleware cannot be the first operation in a request handler. ### Usage ```js const http = require('http') const logger = require('pino-http')() http.createServer((req, res) => { // Must run some code before calling logger? // Manually set the start time res[logger.startTime] = Date.now() someOtherProcessing(req, res) // Now call logger - response time will be calculated correctly logger(req, res) res.end('hello') }).listen(3000) ``` ### Why Use This By default, the middleware records the start time when `logger(req, res)` is called (line 175). If other code runs first, those operations add to the measured response time. Using `logger.startTime`, you can record the actual start time before any application logic runs. ``` -------------------------------- ### Performance Optimization Options Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/quick-reference.md Configure pino-http for performance by setting log levels, disabling request/response loggers, and ignoring specific routes. ```javascript pinoHttp({ level: 'warn', quietReqLogger: true, quietResLogger: true, autoLogging: { ignore: (req) => req.url === '/health' } }) ``` -------------------------------- ### Named Export: startTime Symbol Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/exported-symbols.md A unique symbol used internally to store the request start time on the response object. It allows manual timing when the middleware is not the first operation in a request handler. ```javascript module.exports.startTime = startTime ``` ```javascript const http = require('http') const logger = require('pino-http')() http.createServer((req, res) => { // Must run some code before calling logger? // Manually set the start time res[logger.startTime] = Date.now() someOtherProcessing(req, res) // Now call logger - response time will be calculated correctly logger(req, res) res.end('hello') }).listen(3000) ``` -------------------------------- ### Usage with Express Middleware Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/api-reference-pinohttp.md Demonstrates how to use pino-http as middleware in an Express.js application. ```javascript const express = require('express') const pinoHttp = require('pino-http') const app = express() const logger = pinoHttp() app.use((req, res, next) => { logger(req, res, next) }) ``` -------------------------------- ### Ignore Multiple Endpoints and User Agents Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/usage-examples.md Set up pino-http to ignore a list of specific paths and requests from certain user agents like Prometheus or NewRelic. This allows for more granular control over what gets logged. ```javascript const pinoHttp = require('pino-http') const IGNORED_PATHS = ['/health', '/ready', '/metrics', '/status'] const logger = pinoHttp({ autoLogging: { ignore: (req) => { // Check exact path matches if (IGNORED_PATHS.includes(req.url)) return true // Check user agent const ua = req.headers['user-agent'] || '' if (ua.includes('Prometheus') || ua.includes('NewRelic')) return true return false } } }) ``` -------------------------------- ### Usage with Stream Destination Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/api-reference-pinohttp.md Shows how to configure pino-http to write logs to a specific file stream. ```javascript const pinoHttp = require('pino-http') const { createWriteStream } = require('fs') const logStream = createWriteStream('./logs.jsonl') const logger = pinoHttp(logStream) ``` -------------------------------- ### Customize Pino-HTTP Log Property Names Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/types.md Configure pino-http with custom attribute keys to change the names of properties in log output. This example demonstrates renaming 'req', 'res', 'err', and 'responseTime' to 'request', 'response', 'error', and 'duration_ms' respectively. ```javascript const logger = pinoHttp({ customAttributeKeys: { req: 'request', res: 'response', err: 'error', responseTime: 'duration_ms' } }) // Log output will contain 'request', 'response', 'error', 'duration_ms' // instead of 'req', 'res', 'err', 'responseTime' ``` -------------------------------- ### Configuration Options Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/MANIFEST.txt pino-http offers a wide range of configuration options to customize logging behavior, including log level, serializers, request IDs, and more. ```APIDOC ## Configuration Options ### Description The `pinoHttp()` factory function accepts an `Options` object to customize its behavior. This object allows fine-grained control over logging, including formatting, level, request ID generation, and more. ### Key Options (Refer to `configuration.md` for full details) - **`logger`** (pino.Logger): An existing Pino logger instance to use. If not provided, a default logger is created. - **`genReqId`** (function): A callback function to generate unique request IDs. - **`autoLogging`** (boolean | AutoLoggingOptions): Controls whether to automatically log requests and responses. Can be configured further with `AutoLoggingOptions`. - **`customLogLevel`** (function): A callback to dynamically set the log level based on the response status code. - **`serializers`** (object): Custom serializers for request and response objects. - **`formatters`** (object): Custom formatters for log messages and log objects. ### Example Usage ```javascript const pinoHttp = require('pino-http') const http = require('http') const server = http.createServer((req, res) => { const logger = pinoHttp({ genReqId: (req) => { return Date.now().toString(36) + Math.random().toString(36).substring(2) }, autoLogging: { ignore: (req) => req.url === '/health' }, customLogLevel: (res, err) => { if (res.statusCode >= 400) return 'warn' if (res.statusCode >= 300) return 'info' return 'info' } }) logger(req, res, () => { res.end('Hello World') }) }) server.listen(8080) ``` ``` -------------------------------- ### Pretty Console Output Source: https://github.com/pinojs/pino-http/blob/master/_autodocs/quick-reference.md Enable pretty-printing for console logs by specifying 'pino-pretty' as a transport target. This enhances readability in development environments. ```javascript pinoHttp({ transport: { target: 'pino-pretty' } }) ```