@flare-city/logger
Overview
The @flare-city/logger is a TypeScript class designed for logging in a Node.js / Cloudflare Workers / JS Edge Runtime environment. It provides flexible and customizable logging functionalities with support for different log levels and output formats. This documentation will guide you through understanding how the code works, how to use it, and provide examples.
Installation
To use the Logger class in your project, you can include the provided TypeScript file. If you are using a package manager like npm or yarn, you can install it as follows:
npm install @flare-city/loggerUsage
import { Logger, LogLevel, LoggingType } from "@flare-city/logger";
// Create a new instance of Logger
const logger = new Logger({
name: "MyLogger",
level: "info",
loggingType: "json",
});
// Log messages at different levels
logger.debug("This is a debug message", { additionalData: "some data" });
logger.info("This is an info message", { moreInfo: "additional info" });
logger.warn("This is a warning message", { warningDetails: "some details" });
logger.error("This is an error message", { errorDetails: "some details" });
// Change log level dynamically
logger.setLogLevel("debug");Constructor Options
When creating a new instance of Logger, you can provide the following options:
name(optional): A string representing the name of the logger. Default is "Logger".level(optional): The initial log level. It can be "debug", "info", "warn", or "error". Default is "info".loggingType(optional): The output format for logs. It can be "simple" or "json". Default is "json".
Methods
setName
setName(name: string): voidSets the name of the logger dynamically.
setLoggingType
setLoggingType(loggingType: LoggingType): voidSets the logging type dynamically. The logging type can be "simple" or "json".
log
log(level: LogLevel, message: string, data: Record<string, any>): voidLogs a message with the specified log level. The data parameter is an optional object for additional information.
debug
debug(message: string, data: Record<string, any>): voidLogs a debug message.
info
info(message: string, data: Record<string, any>): voidLogs an info message.
warn
warn(message: string, data: Record<string, any>): voidLogs a warning message.
error
error(message: string, data: Record<string, any>): voidLogs an error message.
setLogLevel
setLogLevel(level: LogLevel): voidSets the log level dynamically. Valid log levels are "debug", "info", "warn", and "error". If an invalid level is provided, a warning will be logged.
Examples
Example 1: Basic Usage
const logger = new Logger();
logger.info("Hello, Logger!");Example 2: Custom Name and Logging Type
const logger = new Logger({
name: "CustomLogger",
loggingType: "simple",
});
logger.debug("This is a debug message.");Example 3: Dynamic Log Level
const logger = new Logger();
logger.info("This will be logged.");
logger.setLogLevel("debug");
logger.debug("This will also be logged.");