docs(log): document ConsoleHandler (#6071)

This commit is contained in:
Asher Gomez 2024-10-02 17:46:14 +10:00 committed by GitHub
parent ea8548602e
commit a9a427a709
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 62 additions and 2 deletions

View File

@ -76,6 +76,7 @@ const ENTRY_POINTS = [
"../log/debug.ts",
"../log/error.ts",
"../log/info.ts",
"../log/console_handler.ts",
"../log/formatters.ts",
"../media_types/mod.ts",
"../msgpack/mod.ts",

View File

@ -5,7 +5,13 @@ import type { LogRecord } from "./logger.ts";
import { blue, bold, red, yellow } from "@std/fmt/colors";
import { BaseHandler, type BaseHandlerOptions } from "./base_handler.ts";
/** Options for {@linkcode ConsoleHandler}. */
export interface ConsoleHandlerOptions extends BaseHandlerOptions {
/**
* Whether to use colors in the output.
*
* @default {true}
*/
useColors?: boolean;
}
@ -31,17 +37,57 @@ function applyColors(msg: string, level: number): string {
}
/**
* This is the default logger. It will output color coded log messages to the
* console via `console.log()`.
* Default logger that outputs log messages to the console via
* {@linkcode console.log}.
*
* @example Usage
* ```ts no-assert
* import { ConsoleHandler } from "@std/log/console-handler";
*
* const handler = new ConsoleHandler("INFO");
* handler.log("Hello, world!"); // Prints "Hello, world!"
* ```
*/
export class ConsoleHandler extends BaseHandler {
#useColors?: boolean;
/**
* Constructs a new instance.
*
* @param levelName The level name to log messages at.
* @param options Options for the handler.
*/
constructor(levelName: LevelName, options: ConsoleHandlerOptions = {}) {
super(levelName, options);
this.#useColors = options.useColors ?? true;
}
/**
* Formats a log record into a string.
*
* @example Usage
* ```ts
* import { ConsoleHandler } from "@std/log/console-handler";
* import { LogRecord } from "@std/log/logger";
* import { LogLevels } from "@std/log/levels";
* import { assertEquals } from "@std/assert/equals";
* import { blue } from "@std/fmt/colors";
*
* const handler = new ConsoleHandler("INFO");
* const logRecord = new LogRecord({
* msg: "Hello, world!",
* args: ["foo", "bar"],
* level: LogLevels.INFO,
* loggerName: "my-logger",
* });
* const result = handler.format(logRecord);
*
* assertEquals(result, blue("INFO Hello, world!"));
* ```
*
* @param logRecord The log record to format.
* @returns The formatted log record.
*/
override format(logRecord: LogRecord): string {
let msg = super.format(logRecord);
@ -52,6 +98,19 @@ export class ConsoleHandler extends BaseHandler {
return msg;
}
/**
* Logs a message to the console.
*
* @example Usage
* ```ts no-assert
* import { ConsoleHandler } from "@std/log/console-handler";
*
* const handler = new ConsoleHandler("INFO");
* handler.log("Hello, world!"); // Prints "Hello, world!"
* ```
*
* @param msg The message to log.
*/
log(msg: string) {
// deno-lint-ignore no-console
console.log(msg);