Customizable output formatting system with built-in reporters for different environments and extensible reporter interface for custom log formatting implementations.
Base interface for creating custom log output formatters and processors.
/**
* Interface for custom log reporters
*/
interface ConsolaReporter {
/**
* Process and output a log message
* @param logObj - Complete log object with all metadata
* @param ctx - Context including configuration options
*/
log(logObj: LogObject, ctx: { options: ConsolaOptions }): void;
}Usage Examples:
import { createConsola } from "consola";
// Custom JSON reporter
class JsonReporter implements ConsolaReporter {
log(logObj, ctx) {
const output = JSON.stringify({
timestamp: logObj.date.toISOString(),
level: logObj.level,
type: logObj.type,
tag: logObj.tag,
message: logObj.args.join(" ")
});
console.log(output);
}
}
// Custom file reporter
class FileReporter implements ConsolaReporter {
constructor(private filename: string) {}
log(logObj, ctx) {
const line = `[${logObj.date.toISOString()}] ${logObj.type.toUpperCase()}: ${logObj.args.join(" ")}\n`;
require("fs").appendFileSync(this.filename, line);
}
}
const logger = createConsola({
reporters: [new JsonReporter(), new FileReporter("app.log")]
});Add, remove, and replace reporters on existing Consola instances.
interface ConsolaInstance {
/**
* Add a reporter to the instance
* @param reporter - Reporter to add to the output chain
* @returns The current instance for chaining
*/
addReporter(reporter: ConsolaReporter): ConsolaInstance;
/**
* Remove a specific reporter or all reporters
* @param reporter - Specific reporter to remove, or undefined to remove all
* @returns The current instance for chaining
*/
removeReporter(reporter?: ConsolaReporter): ConsolaInstance;
/**
* Replace all reporters with new set
* @param reporters - Array of reporters to use for output
* @returns The current instance for chaining
*/
setReporters(reporters: ConsolaReporter[]): ConsolaInstance;
}Usage Examples:
import { consola } from "consola";
import { BasicReporter, FancyReporter } from "consola/reporters";
// Add additional reporter
const fileReporter = new FileReporter("debug.log");
consola.addReporter(fileReporter);
// Remove specific reporter
consola.removeReporter(fileReporter);
// Replace all reporters
consola.setReporters([
new BasicReporter(),
new CustomMetricsReporter()
]);
// Chain reporter operations
consola
.addReporter(new JsonReporter())
.addReporter(new EmailReporter())
.setLevel(1); // Only warnings and errorsSimple text-based reporter providing clean, unformatted output suitable for production environments and log parsing.
/**
* Basic text reporter for simple, clean output formatting
*/
class BasicReporter implements ConsolaReporter {
/**
* Format error objects with stack traces and cause chains
*/
formatError(err: any, opts: FormatOptions): string;
/**
* Format function arguments for display
*/
formatArgs(args: any[], opts: FormatOptions): string;
/**
* Format timestamp information
*/
formatDate(date: Date, opts: FormatOptions): string;
/**
* Format complete log object for output
*/
formatLogObj(logObj: LogObject, opts: FormatOptions): string;
/**
* Output formatted log message to appropriate stream
*/
log(logObj: LogObject, ctx: { options: ConsolaOptions }): void;
}Usage Examples:
import { createConsola } from "consola";
import { BasicReporter } from "consola/reporters";
const basicLogger = createConsola({
reporters: [new BasicReporter()]
});
basicLogger.info("User login", { userId: 123 });
// Output: [info] User login { userId: 123 }
basicLogger.error("Database connection failed", new Error("Timeout"));
// Output: [error] Database connection failed Error: Timeout
// at DatabaseConnection.connect (db.js:45:12)
// ...stack traceEnhanced reporter with colors, icons, and sophisticated formatting for development environments.
/**
* Fancy reporter with colors, icons, and enhanced formatting
*/
class FancyReporter extends BasicReporter {
/**
* Format log type with colors and Unicode icons
*/
formatType(logObj: LogObject, isBadge: boolean, opts: FormatOptions): string;
/**
* Enhanced log object formatting with colors and layout
*/
formatLogObj(logObj: LogObject, opts: FormatOptions): string;
}
// Color and icon mappings
const TYPE_COLOR_MAP: { [k in LogType]?: string } = {
info: "cyan",
fail: "red",
success: "green",
ready: "green",
start: "magenta"
};
const LEVEL_COLOR_MAP: { [k in LogLevel]?: string } = {
0: "red", // fatal/error
1: "yellow" // warn
};Usage Examples:
import { createConsola } from "consola";
import { FancyReporter } from "consola/reporters";
const fancyLogger = createConsola({
reporters: [new FancyReporter()],
formatOptions: {
colors: true,
columns: 120
}
});
fancyLogger.success("Build completed successfully");
// Output: ✔ Build completed successfully (with green color)
fancyLogger.warn("Memory usage high", { usage: "85%" });
// Output: ⚠ Memory usage high { usage: '85%' } (with yellow color)
fancyLogger.box("Important Notice", "System maintenance scheduled");
// Output: Formatted box with borders and colorsBrowser-optimized reporter using browser console API with styled output and proper console method mapping.
/**
* Browser-specific reporter using native console styling
*/
class BrowserReporter implements ConsolaReporter {
constructor(options?: any);
/** Default color for unstyledoutput */
defaultColor: string;
/** Color mapping for different log levels */
levelColorMap: Record<number, string>;
/** Color mapping for specific log types */
typeColorMap: Record<string, string>;
/**
* Get appropriate browser console method for log level
*/
private _getLogFn(level: number): Function;
/**
* Output to browser console with styling
*/
log(logObj: LogObject): void;
}Usage Examples:
import { createConsola } from "consola/browser";
import { BrowserReporter } from "consola/reporters";
// Browser logger automatically uses BrowserReporter
const browserLogger = createConsola();
// Custom browser reporter
const customBrowserLogger = createConsola({
reporters: [new BrowserReporter({
levelColorMap: {
0: "#ff0000", // Red for errors
1: "#ff9900", // Orange for warnings
3: "#0099ff" // Blue for info
}
})]
});
browserLogger.info("Page loaded", { url: window.location.href });
// Browser console output with styled badge and formattingConfigure multiple reporters for comprehensive logging coverage.
Usage Examples:
import { createConsola } from "consola";
import { BasicReporter, FancyReporter } from "consola/reporters";
// Development setup with multiple outputs
const devLogger = createConsola({
reporters: [
new FancyReporter(), // Console with colors
new FileReporter("debug.log"), // File logging
new JsonReporter() // Structured output
]
});
// Production setup with monitoring
const prodLogger = createConsola({
reporters: [
new BasicReporter(), // Clean console output
new MetricsReporter(), // Send to monitoring system
new AlertReporter() // Critical error alerts
],
level: 1 // Warnings and errors only
});
// Conditional reporters based on environment
const reporters = [new BasicReporter()];
if (process.env.NODE_ENV === "development") {
reporters.push(new FancyReporter());
}
if (process.env.LOG_FILE) {
reporters.push(new FileReporter(process.env.LOG_FILE));
}
const logger = createConsola({ reporters });Backward compatibility support for older method names.
interface ConsolaInstance {
// Legacy aliases (deprecated but supported)
add(reporter: ConsolaReporter): ConsolaInstance; // → addReporter
remove(reporter?: ConsolaReporter): ConsolaInstance; // → removeReporter
clear(reporter?: ConsolaReporter): ConsolaInstance; // → removeReporter
}interface LogObject extends InputLogObject {
level: LogLevel;
type: LogType;
tag: string;
args: any[];
date: Date;
[key: string]: unknown;
}
interface FormatOptions {
columns?: number;
date?: boolean;
colors?: boolean;
compact?: boolean | number;
errorLevel?: number;
[key: string]: unknown;
}