### Basic tslog Initialization and Logging Source: https://github.com/fullstack-build/tslog/blob/master/docs/README.md Demonstrates the basic setup of a tslog Logger instance and how to log messages at different levels. Ensure 'tslog' is installed. ```typescript import { Logger, ILogObj } from "tslog"; const log: Logger = new Logger(); log.silly("I am a silly log."); ``` -------------------------------- ### Install rotating-file-stream Source: https://github.com/fullstack-build/tslog/blob/master/README.md Install the 'rotating-file-stream' library using npm to enable file rotation for logs. ```bash npm i rotating-file-stream ``` -------------------------------- ### Bun Example for tslog Source: https://github.com/fullstack-build/tslog/blob/master/README.md Import and use the tslog Logger in a Bun environment. The example shows basic info logging. You can also add a 'dev' script to your package.json for easier execution. ```typescript // main.ts import { Logger } from "tslog"; const logger = new Logger(); logger.info("Hello from Bun"); ``` -------------------------------- ### Deno Example for tslog Source: https://github.com/fullstack-build/tslog/blob/master/README.md Import and use the tslog Logger in a Deno environment. The example demonstrates basic info logging. Optional metadata access can be granted using `--allow-env`. ```typescript // main.ts import { Logger } from "npm:tslog"; const logger = new Logger(); logger.info("Hello from Deno"); ``` -------------------------------- ### Install tslog via npm Source: https://github.com/fullstack-build/tslog/blob/master/README.md Install the tslog package using npm. This is the first step for using tslog in Node.js projects. ```bash npm install tslog ``` -------------------------------- ### Browser Example for tslog Source: https://github.com/fullstack-build/tslog/blob/master/README.md Integrate tslog into an HTML file for browser-based logging. This example includes a script tag to load tslog.js and then initializes and uses the Logger. ```html tslog example

Example

``` -------------------------------- ### Basic Logging with tslog Source: https://github.com/fullstack-build/tslog/blob/master/README.md Demonstrates the basic usage of the Logger class from tslog, showing how to log messages at different levels including errors and objects. Ensure the 'tslog' package is installed. ```typescript import { Logger } from "tslog"; const log = new Logger(); log.silly("I am a silly log."); log.trace("I am a trace log."); log.debug("I am a debug log."); log.info("I am an info log."); log.warn("I am a warn log with a json object:", { foo: "bar" }); log.error("I am an error log."); log.fatal(new Error("I am a pretty Error with a stacktrace.")); ``` -------------------------------- ### Sub-Logger Name Inheritance Example Source: https://github.com/fullstack-build/tslog/blob/master/docs/README.md This example demonstrates how names are inherited and displayed in 'pretty' mode for nested sub-loggers, showing a hierarchical structure. ```typescript const mainLogger = new Logger({ type: "pretty", name: "MainLogger" }); mainLogger.silly("foo bar"); const firstSubLogger = mainLogger.getSubLogger({ name: "FirstSubLogger" }); firstSubLogger.silly("foo bar 1"); const secondSubLogger = firstSubLogger.getSubLogger({ name: "SecondSubLogger" }); secondSubLogger.silly("foo bar 2"); ``` ```bash 2022-11-17 10:45:47.705 SILLY [/examples/server/index2.ts:51 MainLogger] foo bar 2022-11-17 10:45:47.706 SILLY [/examples/server/index2.ts:54 MainLogger:FirstSubLogger ] foo bar 1 2022-11-17 10:45:47.706 SILLY [/examples/server/index2.ts:57 MainLogger:FirstSubLogger:SecondSubLogger] foo bar 2 ``` -------------------------------- ### Change minLevel Setting at Runtime Source: https://github.com/fullstack-build/tslog/blob/master/README.md The settings object is public and can be modified at runtime. This example demonstrates changing the minLevel. ```typescript const logger = new Logger({ minLevel: 1 }); // visible logger.log(1, "level_one", "LOG1"); // visible logger.log(2, "level_two", "LOG2"); // change minLevel to 2 logger.settings.minLevel = 2; // hidden logger.log(1, "level_one", "LOG3"); // visible logger.log(2, "level_two", "LOG4"); ``` -------------------------------- ### External Store for HMR State Preservation (Svelte) Source: https://github.com/fullstack-build/tslog/blob/master/examples/sveltekit_vite/vite-example/README.md Use an external store to preserve component state during Hot Module Replacement (HMR). This example shows a simple writable store. ```typescript // store.ts // An extremely simple external store import { writable } from 'svelte/store' export default writable(0) ``` -------------------------------- ### Configure tslog with Rotating File Stream Source: https://github.com/fullstack-build/tslog/blob/master/README.md Attach a rotating file stream to tslog to manage log file size, rotation interval, and compression. This setup is useful for limiting disk space usage. ```typescript import { Logger } from "tslog"; import { createStream } from "rotating-file-stream"; const stream = createStream("tslog.log", { size: "10M", // rotate every 10 MegaBytes written interval: "1d", // rotate daily compress: "gzip", // compress rotated files }); const logger = new Logger(); logger.attachTransport((logObj) => { stream.write(JSON.stringify(logObj) + "\n"); }); logger.debug("I am a debug log."); logger.info("I am an info log."); logger.warn("I am a warn log with a json object:", { foo: "bar" }); ``` -------------------------------- ### Deno Usage Source: https://context7.com/fullstack-build/tslog/llms.txt Illustrates how to use tslog within a Deno environment, leveraging its zero-dependency nature and runtime detection. ```APIDOC ## Deno Usage ### Description This example shows how to import and use the tslog Logger in a Deno runtime. tslog automatically detects the Deno environment and enriches metadata. ### Method Import and instantiate `Logger` ### Endpoint N/A (Deno Script) ### Parameters #### Constructor Parameters - **`name`** (string) - Optional - The name of the logger instance. - **`type`** ('json' | 'pretty' | 'hidden') - Optional - The output format for logs. ### Request Example ```typescript // Deno (main.ts) import { Logger } from "npm:tslog"; const log = new Logger({ name: "DenoApp", type: "json" }); log.info("Running on Deno"); // _meta.runtime === "deno", _meta.runtimeVersion === "deno/1.40.0" // Run: deno run --allow-env main.ts ``` ### Response Logs are output to the console, with `_meta` object containing Deno-specific runtime information. ``` -------------------------------- ### Bun Usage Source: https://context7.com/fullstack-build/tslog/llms.txt Demonstrates the integration of tslog within a Bun runtime environment, highlighting its compatibility and features. ```APIDOC ## Bun Usage ### Description This example shows how to import and use the tslog Logger in a Bun runtime. tslog automatically detects the Bun environment and enriches metadata. ### Method Import and instantiate `Logger` ### Endpoint N/A (Bun Script) ### Parameters #### Constructor Parameters - **`name`** (string) - Optional - The name of the logger instance. - **`type`** ('json' | 'pretty' | 'hidden') - Optional - The output format for logs. ### Request Example ```typescript // Bun (main.ts) import { Logger } from "tslog"; const log = new Logger({ name: "BunApp", type: "pretty" }); log.info("Running on Bun"); // _meta.runtime === "bun", _meta.runtimeVersion === "bun/1.0.0" // Run: bun run main.ts ``` ### Response Logs are output to the console, with `_meta` object containing Bun-specific runtime information. ``` -------------------------------- ### Bun Runtime Usage Source: https://context7.com/fullstack-build/tslog/llms.txt Import 'tslog' directly for Bun. The '_meta' object will include Bun-specific runtime information. ```typescript // Bun (main.ts) import { Logger } from "tslog"; const log = new Logger({ name: "BunApp", type: "pretty" }); log.info("Running on Bun"); // _meta.runtime === "bun", _meta.runtimeVersion === "bun/1.0.0" // Run: bun run main.ts ``` -------------------------------- ### Browser Usage with UMD Bundle Source: https://context7.com/fullstack-build/tslog/llms.txt Include the tslog.js script and initialize the Logger for styled console output in browsers. ```html ``` -------------------------------- ### Deno Runtime Usage Source: https://context7.com/fullstack-build/tslog/llms.txt Use 'npm:tslog' for Deno imports. The '_meta' object will include Deno-specific runtime information. ```typescript // Deno (main.ts) import { Logger } from "npm:tslog"; const log = new Logger({ name: "DenoApp", type: "json" }); log.info("Running on Deno"); // _meta.runtime === "deno", _meta.runtimeVersion === "deno/1.40.0" // Run: deno run --allow-env main.ts ``` -------------------------------- ### Basic tslog Usage Source: https://github.com/fullstack-build/tslog/blob/master/examples/browser/index.html Create a tslog Logger instance with default settings and log messages at different levels. Demonstrates logging simple strings and objects. ```typescript const log = new tslog.Logger({}); log.silly("I am a silly log."); // log.trace("I am a trace log with a stack trace."); log.debug("I am a debug log."); log.info("I am an info log."); log.warn("I am a warn log with a json object:", { foo: "bar" }); log.error("I am an error log."); log.fatal(new Error("I am a pretty Error with a stacktrace.")); ``` -------------------------------- ### Browser Usage (UMD Bundle) Source: https://context7.com/fullstack-build/tslog/llms.txt Demonstrates how to use the tslog Logger with a UMD bundle script in a browser environment. ```APIDOC ## Browser Usage (UMD) ### Description This example shows how to include the tslog UMD bundle via a script tag and instantiate a Logger for browser console output. ### Method Instantiate `tslog.Logger` ### Endpoint N/A (Browser Script) ### Parameters #### Constructor Parameters - **`name`** (string) - Optional - The name of the logger instance. - **`type`** ('json' | 'pretty' | 'hidden') - Optional - The output format for logs. Defaults to 'pretty' in browsers. ### Request Example ```html ``` ### Response Logs are output to the browser's developer console. ``` -------------------------------- ### Customize Pretty Log Format with Templates and Styles Source: https://context7.com/fullstack-build/tslog/llms.txt Configure `prettyLogTemplate` for the log prefix line and `prettyLogStyles` for per-token color and style. This allows full control over the appearance of pretty-printed logs. ```typescript import { Logger } from "tslog"; const log = new Logger({ type: "pretty", prettyLogTemplate: "{{yyyy}}-{{mm}}-{{dd}} {{hh}}:{{MM}}:{{ss}} {{logLevelName}}\t[{{fileNameWithLine}}] ", prettyLogTimeZone: "local", stylePrettyLogs: true, prettyLogStyles: { logLevelName: { "*": ["bold", "black", "bgWhiteBright", "dim"], SILLY: ["bold", "white"], TRACE: ["bold", "whiteBright"], DEBUG: ["bold", "green"], INFO: ["bold", "blue"], WARN: ["bold", "yellow"], ERROR: ["bold", "red"], FATAL: ["bold", "redBright"], }, dateIsoStr: "white", fileNameWithLine: "yellow", name: ["white", "bold"], }, prettyErrorTemplate: "\n{{errorName}} {{errorMessage}}\nstack:\n{{errorStack}}", prettyErrorStackTemplate: " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}", }); log.debug("Server config loaded", { port: 3000, env: "production" }); log.fatal(new Error("Unhandled exception in worker thread")); ``` -------------------------------- ### Settings: `type` Source: https://context7.com/fullstack-build/tslog/llms.txt Configures the output format for log messages. Options include 'pretty' for human-readable colored text, 'json' for single-line machine-parseable output, and 'hidden' to suppress all output. ```APIDOC ## Settings: `type` — Output Format Controls whether logs are printed as colorized human-readable text (`"pretty"`), single-line `"json"`, or suppressed entirely (`"hidden"`). ```typescript import { Logger } from "tslog"; // Pretty (default): colorized, multi-line, human-readable const prettyLogger = new Logger({ type: "pretty" }); prettyLogger.info("User registered", { email: "alice@example.com" }); // 2024.01.15 12:34:56:789 INFO src/users.ts:12 User registered { email: 'alice@example.com' } // JSON: single-line, machine-parseable const jsonLogger = new Logger({ type: "json" }); jsonLogger.info("User registered", { email: "alice@example.com" }); // {"email":"alice@example.com",_meta:{"runtime":"node","logLevelId":3,"logLevelName":"INFO","date":"2024-01-15T12:34:56.789Z","path":{"filePath":"src/users.ts","fileLine":"12",...}}} // Hidden: no output (useful with attachTransport for custom-only routing) const hiddenLogger = new Logger({ type: "hidden" }); hiddenLogger.attachTransport((logObj) => myCustomHandler(logObj)); ``` ``` -------------------------------- ### ISettingsParam Interface Source: https://context7.com/fullstack-build/tslog/llms.txt Defines the structure for configuration parameters when initializing a tslog Logger instance. ```APIDOC ### `ISettingsParam` Interface #### Description This interface defines all available options for configuring a `Logger` instance. It allows customization of log output format, levels, styling, and more. #### Properties - **`type`** ('json' | 'pretty' | 'hidden') - Optional - Specifies the output format for logs. - **`name`** (string) - Optional - Assigns a name to the logger instance. - **`minLevel`** (number) - Optional - Sets the minimum log level to display (0=silly to 6=fatal). - **`argumentsArrayName`** (string) - Optional - Wraps log arguments in a named array. - **`hideLogPositionForProduction`** (boolean) - Optional - Skips stack trace generation in production for performance. - **`prettyLogTemplate`** (string) - Optional - Custom template string for the prefix of pretty logs. - **`prettyErrorTemplate`** (string) - Optional - Custom format for error messages in pretty logs. - **`prettyErrorStackTemplate`** (string) - Optional - Custom format for stack trace lines in pretty logs. - **`stylePrettyLogs`** (boolean) - Optional - Enables ANSI/CSS colors for pretty log output. - **`prettyLogTimeZone`** ('UTC' | 'local') - Optional - Sets the timezone for timestamps in pretty logs. - **`prettyLogStyles`** (IPrettyLogStyles) - Optional - Defines custom color styles for different log tokens. - **`prettyInspectOptions`** (InspectOptions) - Optional - Options for customizing the inspection of objects in logs (similar to `util.inspect`). - **`metaProperty`** (string) - Optional - The key name for the metadata object in logs (defaults to `_meta`). - **`maskPlaceholder`** (string) - Optional - The placeholder string used for masked values (defaults to `[***]`). - **`maskValuesOfKeys`** (string[]) - Optional - An array of keys whose values should be masked. - **`maskValuesOfKeysCaseInsensitive`** (boolean) - Optional - Enables case-insensitive matching for keys to be masked. - **`maskValuesRegEx`** (RegExp[]) - Optional - An array of regular expressions to identify values that should be masked. - **`prefix`** (unknown[]) - Optional - An array of items to prepend to every log message. - **`attachedTransports`** ((log: LogObj & ILogObjMeta) => void)[] - Optional - An array of functions to handle log output to custom transports. - **`overwrite`** ({...}) - Optional - An object containing functions to override internal tslog methods for advanced customization. ``` -------------------------------- ### Pretty Logging with tslog Source: https://github.com/fullstack-build/tslog/blob/master/examples/browser/index.html Instantiate a tslog Logger with 'pretty' type for formatted console output. Use various logging methods like silly, debug, info, warn, error, and fatal. ```typescript class MyClass { _logger = new tslog.Logger({ type: "pretty", }); constructor() { this._logger.silly("I am a silly log."); } myMethod() { const jsonObj = { name: "John Doe", age: 30, cars: { car1: "Audi", car2: "BMW", car3: "Tesla", }, obj: undefined, }; jsonObj.obj = jsonObj; this._logger.debug("I am a debug log."); this._logger.info("I am an info log."); this._logger.warn("I am a warn log with a json object:", jsonObj); this._logger.error("I am an error log."); try { /* @ts-ignore */ null.foo(); } catch (err) { this._logger.fatal(err); } } } const myClass = new MyClass(); myClass.myMethod(); ``` -------------------------------- ### Advanced tslog Usage with Custom Name and Log Levels Source: https://github.com/fullstack-build/tslog/blob/master/docs/README.md Demonstrates initializing a tslog Logger with a custom name and logging messages across various levels, including an error object and a JSON object. This showcases tslog's flexibility in handling different log types and data. ```typescript import { Logger } from "tslog"; const logger = new Logger({ name: "myLogger" }); logger.silly("I am a silly log."); logger.trace("I am a trace log."); logger.debug("I am a debug log."); logger.info("I am an info log."); logger.warn("I am a warn log with a json object:", { foo: "bar" }); logger.error("I am an error log."); logger.fatal(new Error("I am a pretty Error with a stacktrace.")); ``` -------------------------------- ### Running Node.js Application with Source Maps Source: https://github.com/fullstack-build/tslog/blob/master/docs/README.md Execute your Node.js application with source maps enabled for accurate stack traces. This command is typically used after building your project. ```bash npm start ``` -------------------------------- ### Basic tslog Initialization and Logging Source: https://github.com/fullstack-build/tslog/blob/master/README.md Initialize a logger instance and perform basic logging operations like silly, trace, debug, info, warn, error, and fatal. Supports custom logger names and interpolation of JSON objects and errors with stack traces. ```typescript import { Logger, ILogObj } from "tslog"; const log: Logger = new Logger(); log.silly("I am a silly log."); ``` ```typescript import { Logger } from "tslog"; const logger = new Logger({ name: "myLogger" }); logger.silly("I am a silly log."); logger.trace("I am a trace log."); logger.debug("I am a debug log."); logger.info("I am an info log."); logger.warn("I am a warn log with a json object:", { foo: "bar" }); logger.error("I am an error log."); logger.fatal(new Error("I am a pretty Error with a stacktrace.")); ``` -------------------------------- ### Logger Constructor Source: https://context7.com/fullstack-build/tslog/llms.txt Creates a new logger instance. You can configure settings like name, type (pretty/json/hidden), and minimum log level. It also accepts a default log object to merge into every log entry. ```APIDOC ## Logger Constructor Creates a new logger instance. Accepts an optional settings object and an optional default log object whose properties (including function-valued ones) are merged into every log entry. ```typescript import { Logger, ILogObj } from "tslog"; // Basic pretty logger (default) const logger = new Logger(); // Named JSON logger with custom default log object interface IMyLogObj { requestId?: string | (() => string | undefined); service: string; } const appLogger = new Logger( { name: "AppLogger", type: "json", minLevel: 2 }, { service: "my-api", requestId: undefined } ); // Hidden logger (no output, useful with attached transports) const silentLogger = new Logger({ type: "hidden" }); ``` ``` -------------------------------- ### Standard Log Methods Source: https://context7.com/fullstack-build/tslog/llms.txt Provides seven built-in methods for different log severity levels: silly, trace, debug, info, warn, error, and fatal. Each method accepts multiple arguments and returns the resolved log object if not filtered by minLevel. ```APIDOC ## Standard Log Methods: `silly`, `trace`, `debug`, `info`, `warn`, `error`, `fatal` Seven built-in methods covering the default severity scale (0–6). Each method accepts any number of arguments (strings, objects, errors) and returns the fully-resolved log object with metadata attached, or `undefined` if the message was filtered by `minLevel`. ```typescript import { Logger } from "tslog"; const log = new Logger({ name: "myLogger" }); log.silly("Verbose internal state message"); log.trace("Entering function calculateTotal()"); log.debug("Fetched user:", { id: 42, name: "Alice" }); log.info("Server started on port 3000"); log.warn("Deprecated API called", { endpoint: "/v1/users" }); log.error("Database query failed", { query: "SELECT * FROM users" }); // Errors get pretty-printed with full stack trace try { null.foo(); // intentional runtime error } catch (err) { log.fatal(err); } // Return value: typed log object with _meta const logMsg = log.info("Startup complete"); // logMsg._meta = { logLevelId: 3, logLevelName: "INFO", date: Date, path: {...}, runtime: "node", ... } ``` ``` -------------------------------- ### Configure Pretty Log Templates and Styles Source: https://github.com/fullstack-build/tslog/blob/master/README.md Customize the appearance of logs and errors with various templates and style options. This configuration sets up detailed log formatting and error reporting. ```typescript const logger = new Logger({ prettyLogTemplate: "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t[{{filePathWithLine}}{{name}}]\t", prettyErrorTemplate: "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}", prettyErrorStackTemplate: " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}", prettyErrorParentNamesSeparator: ":", prettyErrorLoggerNameDelimiter: "\t", stylePrettyLogs: true, prettyLogTimeZone: "UTC", prettyLogStyles: { logLevelName: { "*": ["bold", "black", "bgWhiteBright", "dim"], SILLY: ["bold", "white"], TRACE: ["bold", "whiteBright"], DEBUG: ["bold", "green"], INFO: ["bold", "blue"], WARN: ["bold", "yellow"], ERROR: ["bold", "red"], FATAL: ["bold", "redBright"], }, dateIsoStr: "white", filePathWithLine: "white", name: ["white", "bold"], nameWithDelimiterPrefix: ["white", "bold"], nameWithDelimiterSuffix: ["white", "bold"], errorName: ["bold", "bgRedBright", "whiteBright"], fileName: ["yellow"], fileNameWithLine: "white", }, }); ``` -------------------------------- ### Browser Usage (ES Module) Source: https://context7.com/fullstack-build/tslog/llms.txt Shows how to import and use the tslog Logger with ES modules in modern browser environments like Vite or webpack. ```APIDOC ## Browser Usage (ES Module) ### Description This example demonstrates using tslog with ES modules, suitable for modern build tools like Vite or webpack, enabling features like styled logs. ### Method Import and instantiate `Logger` ### Endpoint N/A (ES Module) ### Parameters #### Constructor Parameters - **`type`** ('json' | 'pretty' | 'hidden') - Optional - The output format for logs. Defaults to 'pretty'. - **`stylePrettyLogs`** (boolean) - Optional - Enables ANSI/CSS colors for pretty logs. Defaults to `true` in browsers. - **`prettyLogTemplate`** (string) - Optional - A template string for customizing the prefix of pretty logs. ### Request Example ```typescript import { Logger } from "tslog"; const log = new Logger({ type: "pretty", stylePrettyLogs: true, // true by default in browser prettyLogTemplate: "{{logLevelName}} [{{fileNameWithLine}}] ", }); log.info("Page loaded"); log.warn("Feature flag disabled:", { flag: "new-checkout" }); ``` ### Response Logs are output to the browser's developer console with customizable formatting and styling. ``` -------------------------------- ### Initialize Logger with Settings Object Source: https://github.com/fullstack-build/tslog/blob/master/docs/README.md The first parameter to the Logger constructor is a settings object, allowing extensive customization of logger behavior. This object can also be modified at runtime. ```typescript const logger = new Logger({ /* SETTINGS */ }, defaultLogObject); ``` -------------------------------- ### Create tslog Logger Instances Source: https://context7.com/fullstack-build/tslog/llms.txt Instantiate a logger with default settings, custom options like name and type (JSON), or as a hidden logger. Custom default log objects can be provided to merge properties into every log entry. ```typescript import { Logger, ILogObj } from "tslog"; // Basic pretty logger (default) const logger = new Logger(); // Named JSON logger with custom default log object interface IMyLogObj { requestId?: string | (() => string | undefined); service: string; } const appLogger = new Logger( { name: "AppLogger", type: "json", minLevel: 2 }, { service: "my-api", requestId: undefined } ); // Hidden logger (no output, useful with attached transports) const silentLogger = new Logger({ type: "hidden" }); ``` -------------------------------- ### tslog ISettingsParam Interface Source: https://context7.com/fullstack-build/tslog/llms.txt Defines the configuration options available for initializing a tslog Logger. Covers output formats, logging levels, styling, and advanced customization. ```typescript interface ISettingsParam { type?: "json" | "pretty" | "hidden"; // output format name?: string; // logger name minLevel?: number; // 0=silly … 6=fatal argumentsArrayName?: string; // wrap args in named array hideLogPositionForProduction?: boolean; // skip stack trace for perf prettyLogTemplate?: string; // custom prefix template prettyErrorTemplate?: string; // custom error format prettyErrorStackTemplate?: string; // custom stack line format stylePrettyLogs?: boolean; // enable ANSI/CSS colors prettyLogTimeZone?: "UTC" | "local"; // timezone for timestamps prettyLogStyles?: IPrettyLogStyles; // per-token color styles prettyInspectOptions?: InspectOptions; // util.inspect options metaProperty?: string; // key for meta (default "_meta") maskPlaceholder?: string; // replacement string (default "[***]") maskValuesOfKeys?: string[]; // keys to mask maskValuesOfKeysCaseInsensitive?: boolean; // case-insensitive key matching maskValuesRegEx?: RegExp[]; // regex-based value masking prefix?: unknown[]; // prepended to every log attachedTransports?: ((log: LogObj & ILogObjMeta) => void)[]; overwrite?: { addPlaceholders?: (meta: IMeta, placeholders: Record) => void; mask?: (args: unknown[]) => unknown[]; toLogObj?: (args: unknown[], clonedLogObj?: LogObj) => LogObj; addMeta?: (logObj: LogObj, levelId: number, levelName: string) => LogObj & ILogObjMeta; formatMeta?: (meta?: IMeta) => string; formatLogObj?: (args: unknown[], settings: ISettings) => { args: unknown[]; errors: string[] }; transportFormatted?: (markup: string, args: unknown[], errors: string[], meta?: IMeta, settings?: ISettings) => void; transportJSON?: (json: unknown) => void; }; } ``` -------------------------------- ### logger.getSubLogger(settings?, logObj?) Source: https://context7.com/fullstack-build/tslog/llms.txt Creates a child logger that inherits settings from the parent, allowing for selective overrides. Sub-loggers maintain the parent's name chain and attached transports. ```APIDOC ## `logger.getSubLogger(settings?, logObj?)` — Sub-Logger with Inheritance Creates a child logger that inherits all settings from the parent. Sub-loggers inherit the parent name chain, all attached transports, and merged prefix arrays. Settings can be selectively overridden. ```typescript import { Logger } from "tslog"; const mainLogger = new Logger({ type: "pretty", name: "Main", minLevel: 0 }); mainLogger.info("Application started"); // Output: ... INFO [src/index.ts:4 Main] Application started const dbLogger = mainLogger.getSubLogger({ name: "Database" }); dbLogger.debug("Connected to PostgreSQL"); // Output: ... DEBUG [src/db.ts:12 Main:Database] Connected to PostgreSQL const queryLogger = dbLogger.getSubLogger({ name: "Query" }); queryLogger.silly("Executing:", "SELECT * FROM users WHERE id = $1"); // Output: ... SILLY [src/db.ts:20 Main:Database:Query] Executing: SELECT * FROM ... // Override logObj for sub-logger interface ILogObj { service?: string; module?: string; } const parent = new Logger({}, { service: "api" }); const child = parent.getSubLogger({ name: "Auth" }, { service: "api", module: "auth" }); child.info("JWT verified"); // log entry will contain: { service: "api", module: "auth", _meta:{...} } ``` ``` -------------------------------- ### Define and Access Log Object with TsLog Source: https://github.com/fullstack-build/tslog/blob/master/README.md Demonstrates how to define a default log object with custom properties and use it with the TsLog constructor. The default log object is cloned and merged into each log message, making it highly configurable. ```typescript interface ILogObj { foo: string; } const defaultLogObject: ILogObj = { foo: "bar", }; const logger = new Logger({ type: "json" }, defaultLogObject); const logMsg = logger.info("Test"); // logMsg: { // '0': 'Test', // foo: 'bar', // _meta: { // runtime: 'node', // hostname: 'Eugenes-MBP.local', // date: 2022-10-23T10:51:08.857Z, // logLevelId: 3, // logLevelName: 'INFO', // path: { // fullFilePath: 'file:///[...]/tslog/examples/server/index.ts:113:23', // fileName: 'index.ts', // fileColumn: '23', // fileLine: '113', // filePath: '/examples/server/index.ts', // filePathWithLine: '/examples/server/index.ts:113' // } // } //} ``` -------------------------------- ### Create Sub-loggers Source: https://github.com/fullstack-build/tslog/blob/master/README.md Create sub-loggers using getSubLogger() to inherit settings. The LogObj can be overwritten when creating a child logger. ```typescript const mainLogger = new Logger({ type: "pretty", name: "MainLogger" }); mainLogger.silly("foo bar"); const firstSubLogger = mainLogger.getSubLogger({ name: "FirstSubLogger" }); firstSubLogger.silly("foo bar 1"); ``` ```typescript const mainLogObj = { main: true, sub: false }; const mainLogger = new Logger({ type: "pretty", name: "MainLogger" }, mainLogObj); mainLogger.silly("foo bar"); const subLogObj = { main: false, sub: true }; const firstSubLogger = mainLogger.getSubLogger({ name: "FirstSubLogger" }, subLogObj); firstSubLogger.silly("foo bar 1"); ``` -------------------------------- ### Node.js Project Configuration for ESM and Source Maps Source: https://github.com/fullstack-build/tslog/blob/master/README.md Configure your Node.js project for native ESM by setting `"type": "module"` in `package.json` and enable source maps for accurate stack traces by using the `--enable-source-maps` flag when running Node. ```json { "name": "NAME", "version": "1.0.0", "type": "module", "scripts": { "build": "tsc -p .", "start": "node --enable-source-maps dist/index.js" }, "dependencies": { "tslog": "^4" } } ``` -------------------------------- ### Running CommonJS Bundle in Node.js Source: https://github.com/fullstack-build/tslog/blob/master/docs/README.md Execute the CommonJS version of your application bundle in Node.js, ensuring source maps are enabled for debugging. ```bash node --enable-source-maps dist/index.cjs ``` -------------------------------- ### Create Sub-Logger with Inherited Settings Source: https://github.com/fullstack-build/tslog/blob/master/docs/README.md Use getSubLogger() to create child loggers that inherit settings from the parent. This is useful for modular applications and simplifies configuration. ```typescript const mainLogger = new Logger({ type: "pretty", name: "MainLogger" }); mainLogger.silly("foo bar"); const firstSubLogger = mainLogger.getSubLogger({ name: "FirstSubLogger" }); firstSubLogger.silly("foo bar 1"); ``` -------------------------------- ### Settings: `minLevel` Source: https://context7.com/fullstack-build/tslog/llms.txt Filters log messages based on a numeric level threshold. Only messages with a level equal to or higher than `minLevel` will be outputted. The default levels range from 0 (silly) to 6 (fatal). ```APIDOC ## Settings: `minLevel` — Log Level Filtering Suppresses all log messages below the specified numeric threshold. Default log levels: `0=silly`, `1=trace`, `2=debug`, `3=info`, `4=warn`, `5=error`, `6=fatal`. Can be changed at runtime via `logger.settings.minLevel`. ```typescript import { Logger } from "tslog"; const log = new Logger({ minLevel: 3 }); // only INFO and above log.silly("Ignored"); // suppressed log.debug("Ignored"); // suppressed log.info("Visible"); // printed log.warn("Visible"); // printed log.error("Visible"); // printed // Change at runtime log.settings.minLevel = 5; // now only ERROR and FATAL log.info("Also ignored now"); log.error("Still visible"); ``` ``` -------------------------------- ### Customize Meta Key with `metaProperty` Source: https://context7.com/fullstack-build/tslog/llms.txt Use the `metaProperty` setting to rename the default `_meta` key for metadata, preventing collisions with existing log object structures and allowing custom naming. ```typescript import { Logger } from "tslog"; interface IMyLog { userId?: string; action?: string; } const log = new Logger( { type: "json", metaProperty: "__log" }, { userId: "system" } ); const entry = log.info({ action: "startup" }); // entry.__log.logLevelName === "INFO" // entry.__log.date instanceof Date // entry.__log.path.filePathWithLine === "src/index.ts:10" // Access meta at runtime if (entry) { const meta = entry["__log"] as { logLevelName: string; date: Date }; console.log(`Logged at level ${meta.logLevelName} on ${meta.date.toISOString()}`); } ``` -------------------------------- ### Configure Log Output Format (Type) Source: https://context7.com/fullstack-build/tslog/llms.txt Set the `type` option to control log output: `pretty` for human-readable console logs, `json` for machine-parseable single-line output, or `hidden` to suppress console output when using custom transports. ```typescript import { Logger } from "tslog"; // Pretty (default): colorized, multi-line, human-readable const prettyLogger = new Logger({ type: "pretty" }); prettyLogger.info("User registered", { email: "alice@example.com" }); // 2024.01.15 12:34:56:789 INFO src/users.ts:12 User registered { email: 'alice@example.com' } // JSON: single-line, machine-parseable const jsonLogger = new Logger({ type: "json" }); jsonLogger.info("User registered", { email: "alice@example.com" }); // {"email":"alice@example.com",_meta:{"runtime":"node","logLevelId":3,"logLevelName":"INFO","date":"2024-01-15T12:34:56.789Z","path":{"filePath":"src/users.ts","fileLine":"12",...}}} // Hidden: no output (useful with attachTransport for custom-only routing) const hiddenLogger = new Logger({ type: "hidden" }); hiddenLogger.attachTransport((logObj) => myCustomHandler(logObj)); ``` -------------------------------- ### Create Sub-Logger with Inheritance Source: https://context7.com/fullstack-build/tslog/llms.txt Use `getSubLogger` to create child loggers that inherit settings from their parent. Settings like `name` can be overridden, and additional `logObj` properties can be merged. ```typescript import { Logger } from "tslog"; const mainLogger = new Logger({ type: "pretty", name: "Main", minLevel: 0 }); mainLogger.info("Application started"); // Output: ... INFO [src/index.ts:4 Main] Application started const dbLogger = mainLogger.getSubLogger({ name: "Database" }); dbLogger.debug("Connected to PostgreSQL"); // Output: ... DEBUG [src/db.ts:12 Main:Database] Connected to PostgreSQL const queryLogger = dbLogger.getSubLogger({ name: "Query" }); queryLogger.silly("Executing:", "SELECT * FROM users WHERE id = $1"); // Output: ... SILLY [src/db.ts:20 Main:Database:Query] Executing: SELECT * FROM ... // Override logObj for sub-logger interface ILogObj { service?: string; module?: string; } const parent = new Logger({}, { service: "api" }); const child = parent.getSubLogger({ name: "Auth" }, { service: "api", module: "auth" }); child.info("JWT verified"); // log entry will contain: { service: "api", module: "auth", _meta:{...} } ``` -------------------------------- ### Use Standard tslog Log Methods Source: https://context7.com/fullstack-build/tslog/llms.txt Utilize the seven built-in log methods (silly, trace, debug, info, warn, error, fatal) to log messages at different severity levels. Errors are automatically pretty-printed with stack traces. The return value is the resolved log object with metadata. ```typescript import { Logger } from "tslog"; const log = new Logger({ name: "myLogger" }); log.silly("Verbose internal state message"); log.trace("Entering function calculateTotal()"); log.debug("Fetched user:", { id: 42, name: "Alice" }); log.info("Server started on port 3000"); log.warn("Deprecated API called", { endpoint: "/v1/users" }); log.error("Database query failed", { query: "SELECT * FROM users" }); // Errors get pretty-printed with full stack trace try { null.foo(); // intentional runtime error } catch (err) { log.fatal(err); } // Return value: typed log object with _meta const logMsg = log.info("Startup complete"); // logMsg._meta = { logLevelId: 3, logLevelName: "INFO", date: Date, path: {...}, runtime: "node", ... } ``` -------------------------------- ### Implement Full Lifecycle Customization with `overwrite` Source: https://context7.com/fullstack-build/tslog/llms.txt The `overwrite` setting allows replacing any part of the log message lifecycle, including masking, transformation, metadata injection, formatting, and transport. This is useful for deep integration with external systems. ```typescript import { Logger, IMeta, ISettings } from "tslog"; const log = new Logger({ type: "pretty", overwrite: { // Custom masking logic mask: (args: unknown[]) => args.map(arg => typeof arg === "string" ? arg.replace(/\d{4}-\d{4}-\d{4}-\d{4}/g, "[CARD]") : arg ), // Add custom placeholder token to pretty template addPlaceholders: (logObjMeta: IMeta, placeholders: Record) => { placeholders["requestId"] = (globalThis as any).__currentRequestId ?? "none"; }, // Route to appropriate console method by level transportFormatted: (logMetaMarkup, logArgs, logErrors, logMeta) => { const level = logMeta?.logLevelName ?? ""; const output = logMetaMarkup; switch (level) { case "WARN": console.warn(output, ...logArgs, ...logErrors); break; case "ERROR": case "FATAL": console.error(output, ...logArgs, ...logErrors); break; default: console.log(output, ...logArgs, ...logErrors); break; } }, // Custom JSON transport (e.g., send to log aggregator) transportJSON: (logObj) => { fetch("https://logs.example.com/ingest", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(logObj), }).catch(console.error); }, }, }); log.info("Payment processed", { amount: 99.99, card: "4111-1111-1111-1111" }); // card number → "[CARD]" ``` -------------------------------- ### Attach File System Transport Source: https://github.com/fullstack-build/tslog/blob/master/README.md Configure a transport to append all log messages to a specified file. Requires importing the 'fs' module for file system operations. ```typescript import { Logger } from "tslog"; import { appendFileSync } from "fs"; const logger = new Logger(); logger.attachTransport((logObj) => { appendFileSync("logs.txt", JSON.stringify(logObj) + "\n"); }); logger.debug("I am a debug log."); logger.info("I am an info log."); logger.warn("I am a warn log with a json object:", { foo: "bar" }); ``` -------------------------------- ### Browser Usage with ES Modules Source: https://context7.com/fullstack-build/tslog/llms.txt Import the Logger from 'tslog' for use in modern browser build tools like Vite or webpack. 'stylePrettyLogs' is true by default in the browser. ```typescript // ES module in browser / Vite / webpack import { Logger } from "tslog"; const log = new Logger({ type: "pretty", stylePrettyLogs: true, // true by default in browser prettyLogTemplate: "{{logLevelName}} [{{fileNameWithLine}}] ", }); log.info("Page loaded"); log.warn("Feature flag disabled:", { flag: "new-checkout" }); ``` -------------------------------- ### Custom Log Level Method: `log(logLevelId, logLevelName, ...args)` Source: https://context7.com/fullstack-build/tslog/llms.txt Allows emitting logs at a custom numeric level and name. This can be used directly on the Logger instance or by extending `BaseLogger` to define custom named methods. ```APIDOC ## `logger.log(logLevelId, logLevelName, ...args)` — Custom Log Level Emits a log at a fully custom numeric level and name. Use this directly on `Logger` or extend `BaseLogger` to define named methods for custom levels. ```typescript import { Logger, BaseLogger, ILogObjMeta, ISettingsParam, ILogObj } from "tslog"; // Direct custom level on Logger const log = new Logger(); log.log(7, "AUDIT", "User login", { userId: "u-123", ip: "10.0.0.1" }); // Extending BaseLogger to add a typed custom level class AppLogger extends BaseLogger { constructor(settings?: ISettingsParam, logObj?: LogObj) { super(settings, logObj, 5); } public audit(...args: unknown[]): (LogObj & ILogObjMeta) | undefined { return super.log(7, "AUDIT", ...args); } public verbose(...args: unknown[]): (LogObj & ILogObjMeta) | undefined { return super.log(8, "VERBOSE", ...args); } } const appLog = new AppLogger({ type: "pretty", name: "App" }); appLog.audit("Password changed", { userId: "u-456" }); appLog.verbose("Cache hit for key:", "user:42"); ``` ``` -------------------------------- ### Set Log Message Prefixes with Sub-Loggers Source: https://context7.com/fullstack-build/tslog/llms.txt Use the `prefix` setting to prepend fixed strings to log messages. Prefixes are inherited by sub-loggers, allowing for hierarchical tagging of log streams. ```typescript import { Logger } from "tslog"; const logger = new Logger({ prefix: ["[APP]"] }); logger.info("Started"); // Output: ... INFO ... [APP] Started const requestLogger = logger.getSubLogger({ prefix: ["[req-abc123]"] }); requestLogger.info("Processing"); // Output: ... INFO ... [APP] [req-abc123] Processing const dbLogger = requestLogger.getSubLogger({ prefix: ["[db]"] }); dbLogger.debug("Query executed"); // Output: ... DEBUG ... [APP] [req-abc123] [db] Query executed ```