nodejs-logging
Node.js logging with Winston, Pino, and built-in console. Covers structured logging, log levels, transports, async logging, and production best practices for Express/NestJS applications. USE WHEN: user mentions "node.js logging", "express logging", "nestjs logging", asks about "how to log in node", "winston vs pino", "node logging best practices" DO NOT USE FOR: Python logging - use `python-logging` instead, Java logging - use `slf4j` or `logback`, Browser logging - different environment and APIs
What this skill does
# Node.js Logging
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `nodejs` for comprehensive documentation.
## Library Comparison
| Library | Performance | Features | Best For |
|---------|-------------|----------|----------|
| **Pino** | Fastest (10x+ faster) | JSON-native, low overhead | High-performance APIs |
| **Winston** | Good | Flexible transports, formatting | Enterprise apps, flexibility |
| **Bunyan** | Good | JSON-native, streams | Legacy projects |
| **console** | Basic | Built-in, no deps | Simple scripts, debugging |
## Pino (Recommended for Performance)
### Installation
```bash
npm install pino pino-pretty # pino-pretty for dev
```
### Basic Setup
```typescript
import pino from 'pino';
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
transport: process.env.NODE_ENV !== 'production'
? { target: 'pino-pretty', options: { colorize: true } }
: undefined,
});
// Usage
logger.info('Server started');
logger.info({ userId: 123, action: 'login' }, 'User logged in');
logger.error({ err }, 'Database connection failed');
```
### Child Loggers (Request Context)
```typescript
import { Request, Response, NextFunction } from 'express';
export function requestLogger(req: Request, res: Response, next: NextFunction) {
req.log = logger.child({
requestId: crypto.randomUUID(),
method: req.method,
path: req.path,
});
req.log.info('Request started');
res.on('finish', () => {
req.log.info({ statusCode: res.statusCode }, 'Request completed');
});
next();
}
```
### Express Integration
```typescript
import express from 'express';
import pino from 'pino';
import pinoHttp from 'pino-http';
const app = express();
const logger = pino();
app.use(pinoHttp({ logger }));
app.get('/users/:id', (req, res) => {
req.log.info({ userId: req.params.id }, 'Fetching user');
// ...
});
```
### NestJS Integration
```typescript
// logger.module.ts
import { Module, Global } from '@nestjs/common';
import { LoggerModule as PinoLoggerModule } from 'nestjs-pino';
@Global()
@Module({
imports: [
PinoLoggerModule.forRoot({
pinoHttp: {
level: process.env.LOG_LEVEL || 'info',
transport: process.env.NODE_ENV !== 'production'
? { target: 'pino-pretty' }
: undefined,
},
}),
],
})
export class LoggerModule {}
// usage in service
import { Logger } from 'nestjs-pino';
@Injectable()
export class UserService {
constructor(private readonly logger: Logger) {}
findUser(id: string) {
this.logger.log({ userId: id }, 'Finding user');
}
}
```
## Winston
### Installation
```bash
npm install winston
```
### Basic Setup
```typescript
import winston from 'winston';
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
defaultMeta: { service: 'my-service' },
transports: [
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' }),
],
});
// Pretty console in development
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
),
}));
}
export { logger };
```
### Usage
```typescript
import { logger } from './logger';
// Basic logging
logger.info('Server started on port 3000');
logger.warn('Cache miss for key: user:123');
logger.error('Database connection failed', { error: err });
// With metadata
logger.info('User action', {
userId: user.id,
action: 'purchase',
amount: 99.99,
});
```
### Child Loggers
```typescript
const orderLogger = logger.child({ module: 'orders' });
orderLogger.info('Order created', { orderId: '12345' });
// Output: { module: 'orders', orderId: '12345', message: 'Order created', ... }
```
### Custom Transports
```typescript
import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
const rotateTransport = new DailyRotateFile({
filename: 'logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '100m',
maxFiles: '30d',
zippedArchive: true,
});
rotateTransport.on('rotate', (oldFilename, newFilename) => {
logger.info('Log file rotated', { oldFilename, newFilename });
});
logger.add(rotateTransport);
```
### Express Middleware
```typescript
import expressWinston from 'express-winston';
app.use(expressWinston.logger({
winstonInstance: logger,
meta: true,
msg: 'HTTP {{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms',
expressFormat: false,
colorize: false,
}));
app.use(expressWinston.errorLogger({
winstonInstance: logger,
}));
```
## Log Levels
| Level | Priority | Usage |
|-------|----------|-------|
| `fatal` | 60 | App crash imminent |
| `error` | 50 | Error conditions |
| `warn` | 40 | Warning conditions |
| `info` | 30 | Normal operations |
| `debug` | 20 | Debug information |
| `trace` | 10 | Very detailed tracing |
```typescript
// Pino
logger.fatal('Uncaught exception');
logger.error('Failed to connect to database');
logger.warn('Deprecated API called');
logger.info('Server started');
logger.debug('Query executed');
logger.trace('Entering function');
// Winston (no fatal, uses error)
logger.error('Critical error');
logger.warn('Warning');
logger.info('Info');
logger.verbose('Verbose'); // between info and debug
logger.debug('Debug');
logger.silly('Trace-level'); // lowest
```
## Structured Logging Best Practices
### DO
```typescript
// Include context
logger.info({ userId, orderId, action: 'checkout' }, 'Order placed');
// Log errors properly
logger.error({ err, userId }, 'Payment failed');
// Use child loggers for context
const reqLogger = logger.child({ requestId, userId });
reqLogger.info('Processing request');
```
### DON'T
```typescript
// Don't log sensitive data
logger.info({ password, creditCard }, 'User registered'); // BAD!
// Don't use string interpolation for objects
logger.info(`User ${JSON.stringify(user)} logged in`); // BAD!
// Don't log PII without masking
logger.info({ email: user.email }); // Consider masking
```
### Sensitive Data Handling
```typescript
import pino from 'pino';
const logger = pino({
redact: {
paths: ['password', 'creditCard', 'req.headers.authorization'],
censor: '[REDACTED]',
},
});
// Logs: { password: '[REDACTED]', username: 'john' }
logger.info({ password: 'secret123', username: 'john' });
```
## Production Configuration
### Environment Variables
```bash
LOG_LEVEL=info # Log level
LOG_FORMAT=json # json or pretty
LOG_FILE=logs/app.log # File output
```
### Docker/Container Logging
```typescript
// Log to stdout (Docker captures this)
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
// No file transport - Docker handles log collection
});
// Ensure logs are flushed
process.on('SIGTERM', () => {
logger.info('Received SIGTERM, shutting down');
logger.flush();
process.exit(0);
});
```
### Correlation IDs
```typescript
import { AsyncLocalStorage } from 'async_hooks';
const asyncLocalStorage = new AsyncLocalStorage<{ requestId: string }>();
export function withRequestContext(req: Request, res: Response, next: NextFunction) {
const requestId = req.headers['x-request-id'] || crypto.randomUUID();
asyncLocalStorage.run({ requestId }, () => next());
}
export function getRequestId(): string | undefined {
return asyncLocalStorage.getStore()?.requestId;
}
// In logger
const logger = pino({
mixin() {
return { requestId: getRequestId() };
},
});
```
## When NOT to Use This Skill
- **Python applications**: Use `python-logging` skill instead
- **Java/Spring Boot**: Use `slf4j` and `logback` skills instead
- **Browser/frontend logging**: Different APIs and requirements
- **Simple CLI tools**: conRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.