Logger - API
A logger for TypeScript projects.
Installation
- npm
- yarn
- pnpm
npm is the default package manager for Node.js, and to where tscommon is published.
Your project is using npm if it has a
Run the following command in your terminal:
Your project is using npm if it has a
package-lock.json
file in its root folder.Run the following command in your terminal:
terminal
npm install @tscommon/logger
Usage
Basic
import { Logger, LogLevel } from '@tscommon/logger';
const logger = new Logger();
// Sets the log level to INFO.
Logger.logLevel = LogLevel.INFO;
logger.info('Hello, world!');
logger.error('Something went wrong.', { error: new Error('An error occurred.') });
logger.debug('This message will not be logged.');
// Output:
// {
// "severity": "INFO",
// "timestamp": {
// "seconds": 1731238664,
// "nanos": 513000000
// },
// "message": "Hello, world!"
// }
// {
// "severity": "ERROR",
// "timestamp": {
// "seconds": 1731238664,
// "nanos": 513000000
// },
// "message": "Something went wrong.",
// "payload": {
// "error": {
// "stack": "Error: An error occurred. [[Stack]]",
// "message": "An error occurred."
// }
// }
// }
Development
import { inspect } from 'util';
import { Logger, LogLevel, LogWriter, type LogEntry, type LogLabels, type LogPayload, type LogTimestamp } from '@tscommon/logger';
class DevLogWriter extends LogWriter {
protected override serialize(entry: LogEntry): string {
let str = '';
str += this.printTimestamp(entry.timestamp);
str += ` [${this.printSeverity(entry.severity)}]`;
if (entry.context) str += ` (${entry.context})`;
if (entry.labels) str += ` ${this.printLabels(entry.labels)}`;
str += ` ${entry.message}`;
if (entry.payload) str += ` ${this.printPayload(entry.payload)}`;
return str;
}
private printTimestamp(timestamp: LogTimestamp): string {
return new Date(timestamp.seconds * 1000 + timestamp.nanos / 1_000_000).toLocaleString();
}
private printLabels(labels: LogLabels): string {
return Object.entries(labels)
.map(([key, value]) => (value ? `${key}: ${value}` : undefined))
.filter(Boolean)
.join(', ');
}
private printSeverity(severity: LogLevel): string {
return LogLevel[severity].toUpperCase();
}
private printPayload(payload: LogPayload): string {
return inspect(payload, {
depth: 5,
colors: true,
compact: true,
breakLength: Infinity,
});
}
}
Logger.writer = new DevLogWriter();
const logger = new Logger('app');
logger.info('Server started.', { port: 3000 });
logger.error('Something went wrong.', { error: new Error('An error occurred.') });
// Output
// 01/01/2024, 09:00:00 [INFO] (app) Server started. { port: 3000 }
// 01/01/2024, 09:00:00 [ERROR] (app) Something went wrong. {
// error: Error: An error occurred.
// ...
// }
Google Cloud
The logger can be used to log errors in a format that is compatible with Google Cloud Logging.
import { Logger, LogWriter, type LogEntry } from '@tscommon/logger';
export class GoogleCloudLogWriter extends LogWriter {
#logs: LogEntry[] = [];
#isScheduled = false;
public override write(entry: LogEntry): void {
this.#logs.push(entry);
if (!this.#isScheduled) {
// Buffer logs and write them at the end of the event loop.
setImmediate(() => {
this.#logs.forEach((log) => super.write(log));
this.#isScheduled = false;
this.#logs = [];
});
this.#isScheduled = true;
}
}
protected override serialize(entry: LogEntry): string {
const log = this.transform(entry);
// Enables error reporting in Google Cloud Logging.
log.stack_trace = entry.payload?.error instanceof Error ? entry.payload.error.stack : undefined;
return JSON.stringify(log);
}
}
// Sets logging writer to the custom one.
Logger.writer = new GoogleCloudLogWriter();
const logger = new Logger();
logger.info('Hello, world!');
logger.error('Something went wrong.', { error: new Error('An error occurred.') });
// Output:
// {
// "severity": "INFO",
// "timestamp": {
// "seconds": 1731239034,
// "nanos": 992000000
// },
// "message": "Hello, world!"
// }
// {
// "severity": "ERROR",
// "timestamp": {
// "seconds": 1731239034,
// "nanos": 992000001
// },
// "message": "Something went wrong.",
// "payload": {
// "error": {
// "stack": "Error: An error occurred. [[stack]]",
// "message": "An error occurred."
// }
// },
// "stack_trace": "Error: An error occurred. [[stack]]"
// }