A comprehensive, multi-transport logging library for Node.js applications providing flexible and extensible logging capabilities.
—
Comprehensive log message formatting system with built-in formatters and composable format transformations for customizing log output across all transports.
Base interface for all format transformations that process log info objects.
/**
* Base format interface for log transformations
*/
interface Format {
/** Transform function that processes log info objects */
transform: (info: TransformableInfo, options?: any) => TransformableInfo | boolean;
}
interface TransformableInfo {
/** Log level (error, warn, info, etc.) */
level: string;
/** Log message */
message: string;
/** Timestamp if added by timestamp format */
timestamp?: string;
/** Any additional metadata */
[key: string]: any;
}Core formatting functions available through winston.format.
/**
* JSON format - outputs log as JSON string
* @returns Format that stringifies log info as JSON
*/
function json(): Format;
/**
* Simple format - basic level and message output
* @returns Format that outputs "level: message" format
*/
function simple(): Format;
/**
* Combine multiple formats into a single format
* @param formats - Array of formats to combine
* @returns Combined format that applies all formats in sequence
*/
function combine(...formats: Format[]): Format;
/**
* Add timestamp to log messages
* @param options - Timestamp configuration options
* @returns Format that adds timestamp property
*/
function timestamp(options?: TimestampOptions): Format;
/**
* Colorize log levels and messages for console output
* @param options - Colorization configuration
* @returns Format that adds color codes
*/
function colorize(options?: ColorizeOptions): Format;
/**
* Custom template format using printf-style function
* @param templateFunction - Function that returns formatted string
* @returns Format using custom template
*/
function printf(templateFunction: (info: TransformableInfo) => string): Format;
/**
* Enhanced error formatting with stack traces
* @param options - Error formatting options
* @returns Format that processes Error objects
*/
function errors(options?: ErrorsOptions): Format;
/**
* Add label to log messages
* @param options - Label configuration
* @returns Format that adds label property
*/
function label(options?: LabelOptions): Format;
/**
* Logstash-compatible JSON format
* @returns Format for Logstash/ELK stack compatibility
*/
function logstash(): Format;
/**
* Pretty-print objects and nested data
* @param options - Pretty printing options
* @returns Format for readable object output
*/
function prettyPrint(options?: PrettyPrintOptions): Format;
/**
* String interpolation format (util.format style)
* @returns Format that handles string interpolation
*/
function splat(): Format;
/**
* Remove color codes from log messages
* @returns Format that strips ANSI color codes
*/
function uncolorize(): Format;
/**
* Align log messages for better readability
* @returns Format that aligns text output
*/
function align(): Format;
/**
* CLI-specific formatting with colors and levels
* @param options - CLI formatting options
* @returns Format optimized for command-line output
*/
function cli(options?: CliOptions): Format;
/**
* Add millisecond timing information
* @returns Format that adds timing deltas
*/
function ms(): Format;
/**
* Metadata formatting for structured logging
* @param options - Metadata configuration
* @returns Format that handles metadata objects
*/
function metadata(options?: MetadataOptions): Format;Usage Examples:
const winston = require('winston');
// Basic JSON format
const logger = winston.createLogger({
format: winston.format.json(),
transports: [new winston.transports.Console()]
});
// Combined formats
const logger2 = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
transports: [new winston.transports.Console()]
});
// Custom printf format
const logger3 = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ timestamp, level, message, ...meta }) => {
return `${timestamp} [${level.toUpperCase()}]: ${message} ${Object.keys(meta).length ? JSON.stringify(meta) : ''}`;
})
),
transports: [new winston.transports.Console()]
});Configuration interfaces for various format functions.
interface TimestampOptions {
/** Timestamp format string (moment.js style) */
format?: string;
/** Property name for timestamp (default: 'timestamp') */
alias?: string;
}
interface ColorizeOptions {
/** Colorize the level */
level?: boolean;
/** Colorize everything */
all?: boolean;
/** Colorize the message */
message?: boolean;
/** Custom color mapping */
colors?: { [level: string]: string };
}
interface ErrorsOptions {
/** Include stack trace in error formatting */
stack?: boolean;
}
interface LabelOptions {
/** Label string to add */
label?: string;
/** Add label to message instead of separate property */
message?: boolean;
}
interface PrettyPrintOptions {
/** Object inspection depth */
depth?: number;
/** Colorize pretty-printed output */
colorize?: boolean;
}
interface CliOptions {
/** Logging levels configuration */
levels?: { [level: string]: number };
/** Colors configuration */
colors?: { [level: string]: string };
}
interface MetadataOptions {
/** Property name for metadata */
key?: string;
/** Fill properties from metadata */
fillExcept?: string[];
/** Fill only these properties from metadata */
fillWith?: string[];
}Creating custom format transformations for specialized logging needs.
/**
* Create a custom format function
* @param transformFunction - Function that transforms log info
* @returns Custom format instance
*/
function format(transformFunction: (info: TransformableInfo) => TransformableInfo | boolean): Format;Usage Examples:
const winston = require('winston');
// Custom format to add request ID
const addRequestId = winston.format((info, opts) => {
if (opts.requestId) {
info.requestId = opts.requestId;
}
return info;
});
// Custom format to filter sensitive data
const filterSensitive = winston.format((info) => {
if (info.password) {
info.password = '[REDACTED]';
}
if (info.creditCard) {
delete info.creditCard;
}
return info;
});
// Custom format for performance logging
const performanceFormat = winston.format((info) => {
if (info.duration && info.duration > 1000) {
info.performanceFlag = 'SLOW';
}
return info;
});
// Use custom formats
const logger = winston.createLogger({
format: winston.format.combine(
addRequestId({ requestId: 'req-123' }),
filterSensitive(),
performanceFormat(),
winston.format.timestamp(),
winston.format.json()
),
transports: [new winston.transports.Console()]
});Conditional formatting:
const winston = require('winston');
const conditionalFormat = winston.format((info, opts) => {
if (process.env.NODE_ENV === 'production') {
// Remove debug information in production
delete info.debugInfo;
delete info.trace;
}
return info;
});
const logger = winston.createLogger({
format: winston.format.combine(
conditionalFormat(),
winston.format.json()
),
transports: [new winston.transports.Console()]
});Environment-specific formatting:
const winston = require('winston');
const createFormat = () => {
if (process.env.NODE_ENV === 'development') {
return winston.format.combine(
winston.format.colorize(),
winston.format.timestamp({ format: 'HH:mm:ss' }),
winston.format.printf(({ timestamp, level, message }) => {
return `${timestamp} ${level}: ${message}`;
})
);
}
return winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
);
};
const logger = winston.createLogger({
format: createFormat(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'app.log' })
]
});Multi-transport formatting:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
transports: [
// Console with colorized simple format
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
}),
// File with structured JSON format
new winston.transports.File({
filename: 'app.log',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
)
}),
// Error file with detailed formatting
new winston.transports.File({
filename: 'error.log',
level: 'error',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.printf(({ timestamp, level, message, stack }) => {
return `${timestamp} [${level.toUpperCase()}]: ${message}\n${stack || ''}`;
})
)
})
]
});The format system integrates seamlessly with all Winston components:
This provides maximum flexibility for different logging scenarios while maintaining consistent APIs across the entire Winston ecosystem.
Install with Tessl CLI
npx tessl i tessl/npm-winston