@archivehub/logger
v1.0.0
Published
Unified enterprise-grade logging package for ArchiveHub services. Pino v10 structured JSON logging with AsyncLocalStorage context propagation, automatic redaction, rotating file streams, security/audit loggers, and Express middleware.
Maintainers
Readme
@archivehub/logger
Unified enterprise-grade logging package for ArchiveHub services.
Built on Pino v10 with AsyncLocalStorage context propagation, automatic sensitive data redaction, rotating file streams, security/audit loggers, and Express middleware.
Features
- Structured JSON logging — Pino v10 with service/env/version base bindings
- Request context propagation — AsyncLocalStorage for traceId, userId, database, ip across async chains
- Automatic redaction — Passwords, tokens, authorization headers, SAMLResponse auto-masked
- Security logger — Dual-write to stdout + dedicated
security.logfile - Audit logger — Fixed-schema events for DATA_ACCESS, AUTH, AUTHORIZATION, ADMIN
- Rotating file streams — Daily rotation with size limits via
rotating-file-stream - Express middleware — Request context setup, HTTP logging, error logging
- Startup display — Professional startup output with Unicode tables and phase indicators
- Timezone-aware timestamps — Configurable via
APP_TIMEZONEorCOUNTRYenv vars
Installation
npm install @archivehub/loggerQuick Start
const {
initLogger,
createSecurityLogger,
createAuditLogger,
requestContextMiddleware,
httpLoggerMiddleware
} = require('@archivehub/logger');
// Initialize logger
const { logger, getLogger } = initLogger({
service: 'my-service',
version: '1.0.0',
logDir: './logs'
});
// Optional: create specialized loggers
const securityLogger = createSecurityLogger(logger);
const auditLogger = createAuditLogger(logger);
// Express middleware
app.use(requestContextMiddleware());
app.use(httpLoggerMiddleware());
// In route handlers — context-aware logging
getLogger().info({ userId, action: 'create' }, 'User created record');
// Security events
securityLogger.loginSuccess(userId, 'local');
// Audit events
auditLogger.logDataAccess('read', 'BKPF', { rowCount: 100 });API Reference
Core Logger
| Export | Description |
|--------|-------------|
| initLogger(options) | Initialize logger, returns { logger, getLogger } |
| createLogger(options) | Create a configured Pino logger |
| getLogger() | Get context-aware child logger (auto-enriches with request context) |
| setBaseLogger(logger) | Cache the base logger instance |
| getBaseLogger() | Retrieve cached logger |
Context Management
| Export | Description |
|--------|-------------|
| runWithContext(context, callback) | Run async code within a context |
| setContext(key, value) | Set a context value |
| getContext(key) | Get a context value |
| getAllContext() | Get entire context object |
| getTraceId() / setTraceId() | Trace ID accessor/setter |
| getUserId() / setUserId() | User ID accessor/setter |
| getEmail() / setEmail() | Email accessor/setter |
| getDatabase() / setDatabase() | Database accessor/setter |
| getIp() | Client IP accessor |
| getUserAgent() | User-Agent accessor |
| hasContext() | Check if in active context |
| asyncLocalStorage | Shared AsyncLocalStorage instance |
Specialized Loggers
| Export | Description |
|--------|-------------|
| createSecurityLogger(baseLogger, options) | Dual-write security event logger |
| createAuditLogger(baseLogger, options) | Structured audit event logger |
| AuditCategory | Enum: DATA_ACCESS, AUTH, AUTHORIZATION, ADMIN |
| AuditOutcome | Enum: SUCCESS, FAILURE |
Security logger methods:
loginSuccess(userId, method, details)loginFailure(identifier, method, reason, details)accessDenied(userId, resource, action, details)logout(userId, reason)adminAction(adminUserId, action, targetUserId, details)
Audit logger methods:
logDataAccess(action, resource, options)logAuthEvent(action, success, options)logAuthorizationEvent(resource, action, allowed, options)logAdminAction(action, options)
Express Middleware
| Export | Description |
|--------|-------------|
| requestContextMiddleware(options) | Establish AsyncLocalStorage context per request |
| httpLoggerMiddleware(options) | Log HTTP requests/responses with timing |
| simpleRequestLogger(options) | One-line request logger |
| errorLoggerMiddleware() | Error handler logging |
| enrichContextWithUser(userId, email, data) | Add user info to context |
| getDuration() | Get request elapsed time (ms) |
| DEFAULT_SKIP_PATHS | Paths excluded from logging |
Startup Display
| Export | Description |
|--------|-------------|
| printBanner(info) | Print startup banner with service info |
| printPhase(num, title) | Print phase header |
| printStatus(emoji, label, detail) | Print status line |
| printServiceTable(services) | Print connection status table |
| printSystemsTable(systems, totals) | Print ERP systems summary |
| printLogRotation(config) | Print log rotation settings |
| printReady(durationMs) | Print boot completion banner |
Redaction & Sanitization
| Export | Description |
|--------|-------------|
| defaultRedactPaths | List of auto-redacted field paths |
| createRedactConfig(options) | Build Pino redact config |
| redactObject(obj, fields, censor) | Manual object redaction |
| sanitizeData(data, options) | Truncate large values for logging |
Streams
| Export | Description |
|--------|-------------|
| createMultistream(options) | Composite stream (console + files) |
| createDedicatedStream(name, options) | Single-purpose stream |
| getRotationConfig(overrides) | Get rotation settings |
Timezone
| Export | Description |
|--------|-------------|
| getTimezone() | Get configured IANA timezone |
| now(format) | Current time in configured timezone |
| formatInTimezone(date, format, tz) | Format date in specific timezone |
| resolveTimezone() | Resolve timezone from env vars |
Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| LOG_LEVEL | info | Minimum log level (error, warn, info, debug, trace) |
| LOG_DIR | ./logs | Directory for log files |
| LOG_MAX_SIZE | 10M | Max file size before rotation |
| LOG_MAX_FILES | 30 | Rotated files to retain |
| LOG_INTERVAL | 1d | Rotation interval |
| LOG_COMPRESS | false | Gzip compression on rotation |
| NODE_ENV | production | development enables pino-pretty console output |
| APP_TIMEZONE | — | IANA timezone override (e.g., Asia/Kolkata) |
| COUNTRY | — | Country code for timezone lookup (e.g., US, IN, DE) |
License
MIT
