type LogStream = typeof Deno.stderr | typeof Deno.stdout;
function consoleDrain(
_logger: Logger,
level: string,
...data: unknown[]
): Promise {
switch (level) {
case "trace":
case "debug":
case "info":
case "wait":
case "event":
return writeLog(Deno.stdout, ...data);
case "warn":
case "error":
return writeLog(Deno.stderr, ...data);
default:
return writeLog(Deno.stdout, ...data);
}
}
protected _log(
prefix: string | null,
level: string,
...data: unknown[]
): void {
// Delegate to parent if forked
if (this._parent) {
return this._parent._log(this._prefix!, level, ...data);
}
// Only log if the level is enabled
if (!this._enabled) {
return;
}
// If using the default drain, perform the level check
if (
this._drain === consoleDrain &&
this._levelValues[this._level] > this._levelValues[level]
) {
return;
}
// Format the message all pretty and stuff
if (level !== "other") {
const label = this._customLevels
? this._customLevels[level]?.label
: colorizedLogLevels[level];
let levelLabel = (label ?? level.padEnd(5)) + " -";
// Add the prefix if specified
if (prefix) {
levelLabel = color.bold(colorMap[level](prefix + ":")) + levelLabel;
}
data.unshift(levelLabel);
}
// Persist the log entry in debug mode
if (DEBUG_MODE) {
this._logBuffer[this._currentIndex] = new LogEntry(level, data);
this._currentIndex = (this._currentIndex + 1) % this._logBuffer.length;
}
// Drain the log entry
const promise = this._drain(this, level, ...data);
pendingDrains.add(promise);
promise.finally(() => {
pendingDrains.delete(promise);
});
}
/**
Waits for all pending log writes to complete.
*/
public async flush(): Promise {
// Delegate to parent if forked
if (this._parent) {
return this._parent.flush();
}
await Promise.allSettled([...pendingDrains]);
}
/**
Creates a new logger instance with the specified prefix.
This is useful for creating a logger for a specific plugin, big features, or modules.
All writes and cached logs will be delegated to the parent logger, so debugging will still work.
@param prefix The prefix to add to the logger (e.g. 'my-plugin')
@returns A new logger instance with the specified prefix
*/
public fork(prefix: string): Logger {
return new Logger({
customLevels: this._customLevels,
enabled: this._enabled,
level: this._level,
parent: this,
prefix: this._prefix ? this._prefix + prefix : prefix,
});
}
public getLevel(): LogLevel | string {
// Delegate to parent if forked
if (this._parent) {
return this._parent.getLevel();
}
return this._level;
}
public getLevelValues(): Record<string, number> {
// Delegate to parent if forked
if (this._parent) {
return this._parent.getLevelValues();
}
return this._levelValues;
}
public getRecentLogs(count = 50): LogEntry[] {
// Delegate to parent if forked
if (this._parent) {
return this._parent.getRecentLogs(count);
}
// Return an empty array if the log buffer is empty
if (count <= 0) {
return [];
}
// Ensure the count doesn't exceed the number of logs in the buffer
count = Math.min(count, this._logBuffer.length);
const startIndex =
(this._currentIndex - count + this._logBuffer.length) %
this._logBuffer.length;
let recentLogs: LogEntry[];
if (startIndex < this._currentIndex) {
recentLogs = this._logBuffer.slice(startIndex, this._currentIndex);
} else {
recentLogs = this._logBuffer
.slice(startIndex)
.concat(this._logBuffer.slice(0, this._currentIndex));
}
return recentLogs.reverse();
}
public setDrain(drain: LogDrain) {
this._drain = drain;
}
public trace(...data: unknown[]) {
this._log(null, "trace", ...data);
}
public debug(...data: unknown[]) {
this._log(null, "debug", ...data);
}
public info(...data: unknown[]) {
this._log(null, "info", ...data);
}
public wait(...data: unknown[]) {
this._log(null, "wait", ...data);
}
public log(...data: unknown[]) {
this._log(null, "other", ...data);
}
public event(...data: unknown[]) {
this._log(null, "event", ...data);
}
public ready(...data: unknown[]) {
this._log(null, "ready", ...data);
}
public warn(...data: unknown[]) {
this._log(null, "warn", ...data);
}
public error(...data: unknown[]) {
this._log(null, "error", ...data);
}
public custom(level: string, ...data: unknown[]): void {
if (this._customLevels?.[level]) {
this._log(null, level, ...data);
}
}
}
PROMPT: You are an expert code reviewer. Your task is to analyze the provided code files and provide a comprehensive code review. For each file, consider:
Code Quality: Assess readability, maintainability, and adherence to best practices
Potential Issues: Identify bugs, security vulnerabilities, or performance concerns
Suggestions: Provide specific recommendations for improvements
Format your review as follows:
Start with a brief overview of all files
For each file, provide:
A summary of the file's purpose
Key findings (both positive and negative)
Specific recommendations
End with any overall suggestions for the codebase
Your review should be detailed but concise, focusing on the most important aspects of the code.
Files to review:
File: ./src/lib/logger.ts
Content:
import { color } from "./color.ts";
import { env } from "./env.ts";
type LogStream = typeof Deno.stderr | typeof Deno.stdout;
function consoleDrain(
_logger: Logger,
level: string,
...data: unknown[]
): Promise {
switch (level) {
case "trace":
case "debug":
case "info":
case "wait":
case "event":
return writeLog(Deno.stdout, ...data);
case "warn":
case "error":
return writeLog(Deno.stderr, ...data);
default:
return writeLog(Deno.stdout, ...data);
}
}
protected _log(
prefix: string | null,
level: string,
...data: unknown[]
): void {
// Delegate to parent if forked
if (this._parent) {
return this._parent._log(this._prefix!, level, ...data);
}
// Only log if the level is enabled
if (!this._enabled) {
return;
}
// If using the default drain, perform the level check
if (
this._drain === consoleDrain &&
this._levelValues[this._level] > this._levelValues[level]
) {
return;
}
// Format the message all pretty and stuff
if (level !== "other") {
const label = this._customLevels
? this._customLevels[level]?.label
: colorizedLogLevels[level];
let levelLabel = (label ?? level.padEnd(5)) + " -";
// Add the prefix if specified
if (prefix) {
levelLabel = color.bold(colorMap[level](prefix + ":")) + levelLabel;
}
data.unshift(levelLabel);
}
// Persist the log entry in debug mode
if (DEBUG_MODE) {
this._logBuffer[this._currentIndex] = new LogEntry(level, data);
this._currentIndex = (this._currentIndex + 1) % this._logBuffer.length;
}
// Drain the log entry
const promise = this._drain(this, level, ...data);
pendingDrains.add(promise);
promise.finally(() => {
pendingDrains.delete(promise);
});
}
/**
Waits for all pending log writes to complete.
*/
public async flush(): Promise {
// Delegate to parent if forked
if (this._parent) {
return this._parent.flush();
}
await Promise.allSettled([...pendingDrains]);
}
/**
Creates a new logger instance with the specified prefix.
This is useful for creating a logger for a specific plugin, big features, or modules.
All writes and cached logs will be delegated to the parent logger, so debugging will still work.
@param prefix The prefix to add to the logger (e.g. 'my-plugin')
@returns A new logger instance with the specified prefix
*/
public fork(prefix: string): Logger {
return new Logger({
customLevels: this._customLevels,
enabled: this._enabled,
level: this._level,
parent: this,
prefix: this._prefix ? this._prefix + prefix : prefix,
});
}
public getLevel(): LogLevel | string {
// Delegate to parent if forked
if (this._parent) {
return this._parent.getLevel();
}
return this._level;
}
public getLevelValues(): Record<string, number> {
// Delegate to parent if forked
if (this._parent) {
return this._parent.getLevelValues();
}
return this._levelValues;
}
public getRecentLogs(count = 50): LogEntry[] {
// Delegate to parent if forked
if (this._parent) {
return this._parent.getRecentLogs(count);
}
// Return an empty array if the log buffer is empty
if (count <= 0) {
return [];
}
// Ensure the count doesn't exceed the number of logs in the buffer
count = Math.min(count, this._logBuffer.length);
const startIndex =
(this._currentIndex - count + this._logBuffer.length) %
this._logBuffer.length;
let recentLogs: LogEntry[];
if (startIndex < this._currentIndex) {
recentLogs = this._logBuffer.slice(startIndex, this._currentIndex);
} else {
recentLogs = this._logBuffer
.slice(startIndex)
.concat(this._logBuffer.slice(0, this._currentIndex));
}
return recentLogs.reverse();
}
public setDrain(drain: LogDrain) {
this._drain = drain;
}
public trace(...data: unknown[]) {
this._log(null, "trace", ...data);
}
public debug(...data: unknown[]) {
this._log(null, "debug", ...data);
}
public info(...data: unknown[]) {
this._log(null, "info", ...data);
}
public wait(...data: unknown[]) {
this._log(null, "wait", ...data);
}
public log(...data: unknown[]) {
this._log(null, "other", ...data);
}
public event(...data: unknown[]) {
this._log(null, "event", ...data);
}
public ready(...data: unknown[]) {
this._log(null, "ready", ...data);
}
public warn(...data: unknown[]) {
this._log(null, "warn", ...data);
}
public error(...data: unknown[]) {
this._log(null, "error", ...data);
}
public custom(level: string, ...data: unknown[]): void {
if (this._customLevels?.[level]) {
this._log(null, level, ...data);
}
}
}
The provided code constitutes a sophisticated logging library designed to handle varied log levels and structures. Through constructs like custom log levels, log persistence in debug mode, and chainable logger instances via the fork method, this library offers comprehensive logging features tailored to dynamic applications.
File Review: ./src/lib/logger.ts
Summary
The file defines a logging utility. It introduces a Logger class with capabilities to log messages at varied severity levels, supports custom log levels, and facilitates message persistence in non-production environments. The code is emboldened through features like asynchronous logging and a method to retrieve recent logs, enhancing its utility in both development and production settings.
Key Findings
Positive Aspects:
Comprehensive Logging:
The logging system supports multiple levels and custom-defined levels, providing flexibility.
Configurable:
The Logger class can be tailored to specific needs using options, allowing dynamic adjustment of logging behavior.
Chainable Loggers:
The fork function promotes modularity and scoped logging for components or modules, preserving the cohesion of the logging system.
Asynchronous Drains:
The use of promises in log draining keeps the application responsive and enhances throughput during logging.
Debug Mode Optimizations:
Logs are persisted only in debug mode, reducing memory overhead in production environments.
Error Handling:
There's graceful handling of serialization errors which avoids application crashes.
Negative Aspects:
Global Logger Instance:
The use of a singleton pattern for the logger could lead to shared state issues in a concurrent environment.
Lack of Error Notification:
Errors in promises for write operations are silently caught. Explicit error handling or logging would be beneficial.
Potential Memory Overheads:
Logs are stored in memory in debug mode. For long-running applications, this could amplify memory usage, especially with high verbosity levels.
Verbose Type Declarations:
Type declarations for log levels and color mappings are quite verbose, reducing readability.
Inconsistent API:
The custom function requires the log level as a string, which is different from other methods using predefined log levels.
Specific Recommendations
Singleton Pattern Concerns:
Consider refactoring the global logger instance to avoid state sharing issues. Possibly, use dependency injection or factory patterns for loggers.
Error Management:
Enhance error handling in writeLog promises. Consider a dedicated error handling mechanism for unexpected write failures.
Memory Management:
Provide configurations for log persistence limits or leverage circular buffers explicitly to manage memory use in a more predictably bounded manner.
Type Enums:
Use TypeScript enums instead of union types for LogLevel for improved readability and type safety.
API Uniformity:
Align the custom logging method with standard methods for consistent API behavior. Perhaps by allowing predefined levels to be passed as strings where applicable.
Overall Suggestions for Codebase
Documentation and Comments:
The code can benefit from more detailed comments, especially around critical functions, to promote clearer maintainability and onboarding.
Testing:
Ensure comprehensive tests cover all features, especially around custom log levels and asynchronous behavior. This can help ensure robustness against edge cases.
Security:
Evaluate security implications, particularly if any external inputs can be logged directly. Consider applying encoding or logging policies to sensitive data.
By implementing these suggestions, the library's maintainability, performance, and reliability can be further enhanced while keeping flexibility and usability intact.