
Pino Logging
- 133 installs
- 14 repo stars
- Updated March 2, 2026
- oakoss/agent-skills
Helps with ai & agent building tasks during AI-assisted development.
About
pino-logging is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- pino-logging
- AI & Agent Building
- AI-coding skill
Pino Logging by the numbers
- 133 all-time installs (skills.sh)
- +13 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,627 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/oakoss/agent-skills --skill pino-loggingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 133 |
|---|---|
| repo stars | ★ 14 |
| Last updated | March 2, 2026 |
| Repository | oakoss/agent-skills ↗ |
What it does
Helps with ai & agent building tasks during AI-assisted development.
Files
Pino Logging
High-performance JSON logger for Node.js. Transports run in worker threads to keep the main event loop free. Produces NDJSON by default with automatic level, time, pid, hostname, and msg fields.
When to use: Structured logging in Node.js applications, request-scoped logging with correlation IDs, sensitive data redaction, multi-destination log routing, framework logging integration.
When NOT to use: Browser-only logging (pino has limited browser support), simple console.log debugging during development, projects that need human-readable logs by default (pino outputs JSON; use pino-pretty for dev).
Package: pino (v10+)
Quick Reference
| Pattern | API | Key Points |
|---|---|---|
| Basic logger | pino() | Defaults: level info, JSON to stdout |
| Set level | pino({ level: 'debug' }) | fatal > error > warn > info > debug > trace |
| Log with context | logger.info({ userId }, 'msg') | First arg is merged object, second is message |
| Error logging | logger.error({ err }, 'failed') | Pass errors as err key for serialization |
| Child logger | logger.child({ requestId }) | Bindings persist on all child logs |
| Redaction | pino({ redact: ['password'] }) | Paths use dot notation, supports wildcards |
| Transport (worker) | pino({ transport: { target } }) | Runs in worker thread, non-blocking |
| Multiple transports | transport: { targets: [...] } | Different levels per destination |
| Pretty print (dev) | target: 'pino-pretty' | Dev only — not for production |
| File transport | target: 'pino/file' | Built-in, with mkdir option |
| Rotating files | target: 'pino-roll' | Size and time-based rotation |
| HTTP middleware | pinoHttp() from pino-http | Auto request/response logging |
| Request ID | genReqId option in pino-http | Generate or forward X-Request-Id |
| Serializers | serializers: { req, res, err } | Transform objects before logging |
| Formatters | formatters: { level, log } | Rename fields, transform output |
| Custom levels | customLevels: { http: 35 } | Add levels between built-in ones |
| Async destination | pino.destination({ sync: false }) | Buffered async writes |
| Fastify | fastify({ logger: true }) | Built-in pino, request.log |
| Hono | hono-pino middleware | c.get('logger') in handlers |
Common Mistakes
| Mistake | Fix |
|---|---|
Using pino-pretty in production | Use JSON output in production; pretty-print only in dev via transport |
| Logging sensitive data (tokens, passwords) | Use redact option with paths to sensitive fields |
| Creating a new logger per request | Use logger.child({ requestId }) for request-scoped context |
| Blocking main thread with file writes | Use pino.transport() — runs in a worker thread |
Using JSON.stringify on errors | Pass errors as { err } — pino serializes stack, cause chain |
Not forwarding X-Request-Id header | Use genReqId in pino-http to check headers first |
| Logging inside hot loops | Check logger.isLevelEnabled('debug') before expensive operations |
Missing fetch-depth: 0 with transports | Transports are separate packages — install them as dependencies |
Delegation
If the hono skill is available, delegate Hono middleware and routing patterns to it.If the vitest-testing skill is available, delegate test setup and mocking patterns to it.If thesentry-setup-loggingskill is available, delegate Sentry integration to it — it coversSentry.pinoIntegration()for forwarding pino logs to Sentry.
Otherwise, recommend: pnpm dlx skills add getsentry/sentry-for-claude -s sentry-setup-logging -a claude-code -yReferences
- Setup, configuration, and core API
- Transports, destinations, and log routing
- Child loggers, serializers, and redaction
- HTTP logging, correlation IDs, and framework integrations
Child Loggers and Redaction
Child Loggers
Child loggers inherit parent configuration and permanently bind key-value pairs to every log they emit. This is pino's primary mechanism for request-scoped context.
import pino from 'pino';
const logger = pino();
const requestLogger = logger.child({
requestId: 'abc-123',
module: 'auth',
});
requestLogger.info('Processing request');
// {"level":30,"time":...,"requestId":"abc-123","module":"auth","msg":"Processing request"}Nested Children
Bindings accumulate through the chain:
const requestLogger = logger.child({ requestId: 'abc-123' });
const userLogger = requestLogger.child({ userId: 'user-456' });
userLogger.info('User action');
// {"level":30,"requestId":"abc-123","userId":"user-456","msg":"User action"}Child with Different Level
const debugChild = logger.child({ component: 'database' }, { level: 'debug' });
debugChild.debug('Query executed');msgPrefix Accumulation
const apiLogger = pino({ msgPrefix: '[API] ' });
const authLogger = apiLogger.child({}, { msgPrefix: '[Auth] ' });
authLogger.info('Token validated');
// msg: "[API] [Auth] Token validated"Serializers
Serializers transform objects before they are logged. They run synchronously and are keyed to field names.
Standard Serializers
import pino from 'pino';
const logger = pino({
serializers: {
req: pino.stdSerializers.req,
res: pino.stdSerializers.res,
err: pino.stdSerializers.err,
},
});| Serializer | Serializes | Output Fields |
|---|---|---|
pino.stdSerializers.req | IncomingMessage | method, url, headers, remoteAddress, remotePort |
pino.stdSerializers.res | ServerResponse | statusCode, headers |
pino.stdSerializers.err | Error | type, message, stack, code, cause |
Custom Serializers
const logger = pino({
serializers: {
req: (req) => ({
method: req.method,
url: req.url,
headers: {
host: req.headers.host,
'user-agent': req.headers['user-agent'],
},
}),
user: (user) => ({
id: user.id,
username: user.username,
}),
err: pino.stdSerializers.err,
},
});Error with Cause Chain
const cause = new Error('Database timeout');
const error = new Error('Operation failed', { cause });
(error as NodeJS.ErrnoException).code = 'ERR_OPERATION';
logger.error({ err: error }, 'Request failed');
// Serializes: type, message, stack, code, and cause chainChild Serializer Override
const child = logger.child(
{},
{
serializers: {
user: (user) => ({ id: user.id }),
},
},
);Redaction
Redaction removes or masks sensitive data before logging. Uses fast-json-stringify internally with near-zero overhead.
Simple Path Array
const logger = pino({
redact: ['password', 'creditCard', 'user.ssn', 'users[*].token'],
});
logger.info({ password: 'secret', name: 'John' }, 'User login');
// {"password":"[Redacted]","name":"John","msg":"User login"}Custom Censor
const logger = pino({
redact: {
paths: ['secret', 'data.apiKey', 'headers.authorization'],
censor: '**REDACTED**',
},
});Remove Keys Entirely
const logger = pino({
redact: {
paths: ['tempData', 'internal.*'],
remove: true,
},
});Dynamic Censor Function
const logger = pino({
redact: {
paths: ['email'],
censor: (value: string) => {
if (typeof value === 'string' && value.includes('@')) {
return value.replace(/(.{2}).*(@.*)/, '$1***$2');
}
return '[Redacted]';
},
},
});
logger.info({ email: 'john.doe@example.com' }, 'Email sent');
// email: "jo***@example.com"Wildcard Patterns
| Pattern | Matches |
|---|---|
password | Top-level password field |
user.ssn | Nested ssn inside user |
users[*].token | token on every element in users array |
internal.* | All direct children of internal |
path["with-hyphen"] | Keys with special characters |
Common Redaction Paths
const logger = pino({
redact: [
'password',
'token',
'accessToken',
'refreshToken',
'headers.authorization',
'headers.cookie',
'body.password',
'body.creditCard',
'user.ssn',
'user.dateOfBirth',
'*.secret',
],
});streamWrite Hook
Post-serialization mutation for edge cases where redaction paths are not known ahead of time:
const logger = pino({
hooks: {
streamWrite(str) {
return str.replace(
/api[_-]?key['"]\s*:\s*['"][^'"]+['"]/gi,
'apiKey":"[REMOVED]"',
);
},
},
});HTTP and Frameworks
pino-http
Automatic HTTP request/response logging as middleware.
pnpm add pino-httpExpress
import express from 'express';
import pinoHttp from 'pino-http';
const app = express();
app.use(pinoHttp());
app.get('/users/:id', (req, res) => {
req.log.info({ userId: req.params.id }, 'fetching user');
res.json({ id: req.params.id });
});Each completed request automatically logs req, res, responseTime (ms), and msg: "request completed".
Request ID Generation
import { randomUUID } from 'crypto';
import pinoHttp from 'pino-http';
app.use(
pinoHttp({
genReqId: (req, res) => {
const existing = req.headers['x-request-id'] as string;
if (existing) return existing;
const id = randomUUID();
res.setHeader('X-Request-Id', id);
return id;
},
}),
);Custom Attribute Keys
app.use(
pinoHttp({
customAttributeKeys: {
req: 'request',
res: 'response',
err: 'error',
responseTime: 'duration',
reqId: 'requestId',
},
}),
);Custom Log Level per Response
app.use(
pinoHttp({
customLogLevel: (req, res, err) => {
if (res.statusCode >= 500 || err) return 'error';
if (res.statusCode >= 400) return 'warn';
return 'info';
},
}),
);Request Body Logging with Redaction
app.use(
pinoHttp({
serializers: {
req(req) {
const serialized = pinoHttp.stdSerializers.req(req);
serialized.body = req.raw.body;
if (serialized.body?.password) {
serialized.body = { ...serialized.body, password: '[REDACTED]' };
}
return serialized;
},
},
redact: {
paths: ['req.headers.authorization', 'req.headers.cookie'],
censor: '[REDACTED]',
},
}),
);Quiet Routes
Skip logging for health checks and static assets:
app.use(
pinoHttp({
autoLogging: {
ignore: (req) => {
const url = req.url ?? '';
return url === '/health' || url.startsWith('/static/');
},
},
}),
);Fastify (Built-in)
Fastify ships with pino as its built-in logger. No extra package needed.
import Fastify from 'fastify';
const fastify = Fastify({
logger: {
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
transport:
process.env.NODE_ENV !== 'production'
? { target: 'pino-pretty' }
: undefined,
redact: ['req.headers.authorization'],
},
});
fastify.get('/users/:id', async (request, reply) => {
request.log.info({ userId: request.params.id }, 'fetching user');
return { id: request.params.id };
});Fastify automatically:
- Generates a request ID (from
requestIdHeaderor incremental) - Logs request received and response sent with
responseTime - Provides
request.logas a child logger with request bindings
Custom Request ID
const fastify = Fastify({
logger: true,
requestIdHeader: 'x-request-id',
genReqId: (req) => (req.headers['x-request-id'] as string) ?? randomUUID(),
});Hono
Use hono-pino for pino integration:
pnpm add hono-pino pinoimport { Hono } from 'hono';
import { pinoLogger } from 'hono-pino';
import pino from 'pino';
const app = new Hono();
app.use(
pinoLogger({
pino: pino({ level: 'info' }),
}),
);
app.get('/', (c) => {
c.get('logger').info('handling root');
return c.text('ok');
});For development, hono-pino provides a built-in debug transport:
import { pinoLogger } from 'hono-pino';
import debugLog from 'hono-pino/debug-log';
app.use(
pinoLogger({
pino: pino({
level: 'debug',
transport: { target: debugLog },
}),
}),
);Request Tracing Pattern
Use child loggers for request-scoped context that flows through all service calls:
import express from 'express';
import pino from 'pino';
import { randomUUID } from 'crypto';
const logger = pino();
const app = express();
app.use((req, _res, next) => {
req.log = logger.child({
requestId: (req.headers['x-request-id'] as string) ?? randomUUID(),
method: req.method,
url: req.url,
});
next();
});
app.get('/orders', async (req, res) => {
req.log.info('fetching orders');
const orders = await getOrders(req.log);
req.log.info({ count: orders.length }, 'orders fetched');
res.json(orders);
});
async function getOrders(log: pino.Logger) {
log.info('querying database');
const result = await db.query('SELECT * FROM orders');
log.info({ rows: result.length }, 'query complete');
return result;
}Structured Error Logging
app.use(
(
err: Error,
req: express.Request,
res: express.Response,
_next: express.NextFunction,
) => {
req.log.error(
{
err,
userId: req.user?.id,
operation: `${req.method} ${req.path}`,
},
'Unhandled error',
);
res.status(500).json({ error: 'Internal server error' });
},
);Framework Comparison
| Framework | Package | Logger Access | Request ID | Auto Logging |
|---|---|---|---|---|
| Fastify | Built-in | request.log | Auto (configurable) | Yes |
| Express | pino-http | req.log | Via genReqId | Yes |
| Hono | hono-pino | c.get('logger') | Via middleware | Yes |
| NestJS | nestjs-pino | Logger DI | Via genReqId | Yes |
| Koa | koa-pino-logger | ctx.log | Via genReqId | Yes |
Setup and Configuration
Installation
pnpm add pino
pnpm add -D pino-prettyBasic Usage
import pino from 'pino';
const logger = pino();
logger.info('hello world');
// {"level":30,"time":1234567890,"pid":1234,"hostname":"my-host","msg":"hello world"}Configuration Options
import pino from 'pino';
const logger = pino({
level: 'debug',
name: 'my-app',
base: { env: process.env.NODE_ENV },
timestamp: pino.stdTimeFunctions.isoTime,
msgPrefix: '[API] ',
});Key Options
| Option | Type | Default | Description |
|---|---|---|---|
level | string | 'info' | Minimum log level |
name | string | — | Adds name field to every log |
base | `object \ | null` | { pid, hostname } |
timestamp | `boolean \ | function` | true (epoch ms) |
msgPrefix | string | — | Prefix prepended to every msg |
formatters | object | — | Transform level, bindings, or log objects |
serializers | object | — | Transform specific fields |
redact | `string[] \ | object` | — |
transport | object | — | Worker thread transport config |
customLevels | object | — | Additional log levels |
hooks | object | — | streamWrite hook for post-serialization |
Log Levels
| Level | Number | Method |
|---|---|---|
fatal | 60 | logger.fatal() |
error | 50 | logger.error() |
warn | 40 | logger.warn() |
info | 30 | logger.info() |
debug | 20 | logger.debug() |
trace | 10 | logger.trace() |
silent | — | Disables all logging |
Logging Methods
// Message only
logger.info('Server started');
// Object + message (object merged into log entry)
logger.info({ port: 3000, host: '0.0.0.0' }, 'Server started');
// Error logging (use `err` key for automatic serialization)
logger.error({ err: new Error('Connection failed') }, 'Database error');
// Error shorthand
logger.error(new Error('Database connection failed'));
// Printf-style interpolation
logger.info('User %s performed %s', username, action);Timestamp Options
import pino from 'pino';
// Epoch milliseconds (default)
pino();
// ISO 8601 string
pino({ timestamp: pino.stdTimeFunctions.isoTime });
// "time":"2024-01-15T10:30:00.000Z"
// Unix epoch seconds
pino({ timestamp: pino.stdTimeFunctions.epochTime });
// Disable timestamp
pino({ timestamp: false });
// Custom format
pino({
timestamp: () => `,"time":"${new Date().toISOString()}"`,
});Formatters
Formatters transform the output structure before serialization.
const logger = pino({
formatters: {
level(label) {
return { severity: label.toUpperCase() };
},
bindings(bindings) {
return { pid: bindings.pid, host: bindings.hostname };
},
log(object) {
return object;
},
},
});GCP / Cloud Logging Format
const logger = pino({
formatters: {
level(label) {
return { severity: label.toUpperCase() };
},
},
messageKey: 'message',
});Custom Levels
const logger = pino({
customLevels: {
http: 35,
verbose: 15,
},
});
logger.http('Request received');
logger.verbose('Detailed trace');TypeScript
Pino ships its own types — no @types/pino needed.
import pino, { type Logger, type LoggerOptions } from 'pino';
const options: LoggerOptions = {
level: 'info',
transport: { target: 'pino-pretty' },
};
const logger: Logger = pino(options);Custom Levels with TypeScript
const logger = pino<'http'>({
customLevels: { http: 35 },
level: 'http',
});
logger.http('Request received');Enforcing Structured Fields
declare module 'pino' {
interface LogFnFields {
requestId: string;
}
}
logger.info({ requestId: 'abc-123' }, 'ok');
// logger.info({}, 'missing requestId'); // TypeScript errorEnvironment-Based Configuration
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
transport:
process.env.NODE_ENV !== 'production'
? { target: 'pino-pretty', options: { colorize: true } }
: undefined,
});Async Destination
For high-throughput logging, use buffered async writes:
const logger = pino(
pino.destination({
dest: './app.log',
minLength: 4096,
sync: false,
}),
);
// Flush before process exit
process.on('beforeExit', () => {
logger.flush();
});Transports
Transports run in worker threads via pino.transport(), keeping the main event loop free from I/O. The main thread serializes JSON and passes it through a shared buffer.
Single Transport
import pino from 'pino';
const logger = pino({
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'SYS:standard',
ignore: 'pid,hostname',
},
},
});File Transport (Built-in)
const logger = pino({
transport: {
target: 'pino/file',
options: {
destination: '/var/log/app.log',
mkdir: true,
},
},
});Multiple Transports
Route logs to different destinations based on level:
const logger = pino({
level: 'debug',
transport: {
targets: [
{
target: 'pino-pretty',
level: 'info',
options: { destination: 1 },
},
{
target: 'pino/file',
level: 'error',
options: { destination: '/var/log/error.log' },
},
{
target: 'pino/file',
level: 'debug',
options: { destination: '/var/log/debug.log' },
},
],
},
});Each target filters independently — a log at error level goes to both the info+ and error+ destinations.
Pipeline Transport
Chain transforms before sending to a destination:
const logger = pino({
transport: {
pipeline: [
{ target: 'pino-syslog' },
{
target: 'pino-socket',
options: { address: 'syslog.example.com', port: 514 },
},
],
},
});Rotating File Transport (pino-roll)
pnpm add pino-rollconst logger = pino({
transport: {
target: 'pino-roll',
options: {
file: '/var/log/app.log',
frequency: 'daily',
size: '10m',
limit: { count: 7 },
},
},
});pino-roll Options
| Option | Type | Description |
|---|---|---|
file | string | Log file path (rotation number appended) |
size | `string \ | number` |
frequency | string | Time-based rotation ('daily', 'hourly') |
limit.count | number | Rotated files to retain (plus active file) |
dateFormat | string | Date format appended to filename |
Using pino.transport() Directly
For more control, create a transport instance:
import pino from 'pino';
const transport = pino.transport({
targets: [
{
target: 'pino/file',
options: { destination: './app.log' },
},
{
target: 'pino-pretty',
options: { destination: 1 },
},
],
});
const logger = pino(transport);Custom Transport
Write a custom transport as a module that exports a function:
// my-transport.ts
import build from 'pino-abstract-transport';
export default async function (opts: { url: string }) {
return build(async function (source) {
for await (const obj of source) {
await fetch(opts.url, {
method: 'POST',
body: JSON.stringify(obj),
headers: { 'Content-Type': 'application/json' },
});
}
});
}const logger = pino({
transport: {
target: './my-transport.ts',
options: { url: 'https://logs.example.com/ingest' },
},
});Transport Comparison
| Transport | Package | Use Case |
|---|---|---|
pino-pretty | pino-pretty | Human-readable dev output |
pino/file | Built-in | Simple file logging |
pino-roll | pino-roll | Rotating file logs |
pino-socket | pino-socket | TCP/UDP log shipping |
pino-syslog | pino-syslog | Syslog protocol |
pino-elasticsearch | pino-elasticsearch | Elasticsearch ingest |
pino-datadog-transport | pino-datadog-transport | Datadog log shipping |
Production Recommendations
- Never use
pino-prettyin production — JSON output is parsed by log aggregators - Use multi-target transports to split error logs from info logs
- Set
sync: falseonpino.destination()for high-throughput apps - Prefer piping (
node app.js | pino-pretty) over in-process pretty printing for dev