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
main.ts
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
main.ts
import { inspect } from 'node:util';
import { Logger, LogLevel, LogWriter, type LogEntry, type LogLabels, type LogPayload, type LogTimestamp } from '@tscommon/logger';
if (process.env.NODE_ENV === 'development') {
class DevLogWriter extends LogWriter {
// Override the serialize method to customize the log format.
protected override serialize(entry: LogEntry): string {
let str: string = '';
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 | undefined {
return Object.entries(labels)
.filter(([, value]) => typeof value === 'string')
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
}
private printSeverity(severity: LogLevel): string {
return LogLevel[severity].toUpperCase();
}
private printPayload(payload: LogPayload): string | undefined {
return inspect(payload, { depth: 3, colors: true });
}
}
// Sets custom log writer.
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.
main.ts
import { Logger, LogWriter, type LogEntry } from '@tscommon/logger';
class GoogleCloudLogWriter extends LogWriter {
private captureStackTrace(entry: LogEntry): string | undefined {
return entry.payload?.['error'] instanceof Error ? entry.payload['error'].stack : undefined;
}
protected override serialize(entry: LogEntry): string {
const log = this.transform(entry);
// Include `stack_trace` in the log entry.
log['stack_trace'] = this.captureStackTrace(entry);
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]]"
// }