Class LogWriter

Source
Expand description

A log writer that writes log entries to the console. You can extend this class to implement custom log writers that write to files, databases, or other destinations.

import {
Logger,
LogLevel,
LogWriter,
type LogEntry,
type LogLabels,
type LogPayload,
type LogTimestamp,
} from '../src/index.js';

import { inspect } from 'node:util';

export class DevLogWriter extends LogWriter {
static {
// Set your formatter globally
Logger.writer = new DevLogWriter();
}

protected override serialize(entry: LogEntry): string {
let parts: string[] = [];
parts.push(this._printTimestamp(entry.timestamp));
parts.push(`[${this._printSeverity(entry.severity)}]`);
if (entry.context) parts.push(`(${entry.context})`);
if (entry.labels) parts.push(this._printLabels(entry.labels));
parts.push(entry.message);
if (entry.payload) parts.push(this._printPayload(entry.payload));
return parts.join(' ');
}

protected _printTimestamp(timestamp: LogTimestamp): string {
return new Date(timestamp.seconds * 1000 + timestamp.nanos / 1_000_000).toLocaleString();
}

protected _printLabels(labels: LogLabels): string {
return Object.entries(labels)
.map(([key, value]) => (value ? `${key}: ${value}` : undefined))
.filter(Boolean)
.join(', ');
}

protected _printSeverity(severity: LogLevel): string {
return LogLevel[severity].toUpperCase();
}

private _printPayload(payload: LogPayload): string {
return inspect(payload, {
depth: 5,
colors: true,
compact: true,
breakLength: Infinity,
});
}
}
import { Logger, LogWriter, type LogEntry } from '../src/index.js';

export class GoogleCloudLogWriter extends LogWriter {
static {
// Set Google Cloud formatter globally
Logger.writer = new GoogleCloudLogWriter();
}

private logs: LogEntry[] = [];

public override write(entry: LogEntry): void {
if (this.logs.push(entry) === 1) {
setImmediate(() => {
this.logs.forEach((log) => super.write(log));
this.logs = [];
});
}
}

protected override serialize(entry: LogEntry): string {
const log = this.transform(entry);
if (entry.payload instanceof Error) log.stack_trace = entry.payload.stack;
return JSON.stringify(log);
}
}

Constructors§

Source§

new LogWriter(maxDepth?: number): LogWriter

Initializes a new instance.

Methods§

Source§

collect(data: unknown, depth: number, path: (string | number)[]): unknown

Collects data recursively and truncates it if it exceeds the maximum depth. This method is called by the transform method. It can be overridden in derived classes to customize the data collection. The default implementation returns a JSON-serializable object.

Source§

serialize(entry: LogEntry): string

Serializes a log entry to a string. This method is called by the LogWriter.write method. It can be overridden in derived classes to customize the serialization. The default implementation returns a JSON string. You can override this method to format the log entry differently.

Example:

class MyLogWriter extends LogWriter {
protected override serialize(entry: LogEntry): string {
const log = this.transform(entry);
return `${log.timestamp} [${log.severity}] ${log.message}`;
}
}
Source§

transform(entry: LogEntry): Record<string, unknown>

Transforms a log entry into a plain object. This method is called by the serialize method. It can be overridden in derived classes to customize the transformation. The default implementation returns a plain object with the log entry properties.

Source§

write(entry: LogEntry): void

Writes a log entry to the console. This method is called by the logger. It can be overridden in derived classes to customize the log destination. The default implementation writes the log entry to the console.