MimeLogger

website·Indexed 31 days ago

https://docs.mimedev.fr/

A simple, opinionated Node.js logger featuring colored output, file logging, and child logger support. It supports ESM, CJS, and TypeScript, providing built-in format presets and configurable log levels with zero configuration to get started.

Tokens
3.5K
Snippets
28
Records
31
Agent score
49%

What's inside MimeLogger

  1. Overview of Mime4X libraries and tools

    Mime4X provides a suite of open-source tools and libraries, primarily focused on Node.js, CLI utilities, Minecraft plugins, and Discord bots. All projects are hosted on GitHub and are released under the MIT license.
  2. mime-logger core features overview

    mime-logger is an opinionated Node.js logger providing the following capabilities:

    • Log Levels: info, warn, and error with color-coded output via ansis.
    • Logger Hierarchy: Support for named loggers and child loggers created via logger.child(name) for parent/child relationships.
    • Formatting: Built-in presets (pretty, minimal, detailed, json) and support for custom format strings or FormatFn callbacks.
    • Output: Simultaneous output to the console and rotating log files using time-based path tokens.
  3. Initialize and use the MimeLogger class

    The MimeLogger class is the primary entry point for logging. It can be imported as a named export or a default export. The constructor accepts an optional logger name (which appears in the output) and a LoggerOptions object for configuring formats and output targets.
    import { MimeLogger } from "mime-logger";
    
    // Initialize with a name and options
    const logger = new MimeLogger("app", { 
      format: "pretty", 
      output: "console" 
    });
    
    logger.info("Hello world");
    logger.warn("Warning message");
    logger.error("Error message");
  4. Create a custom log format function

    For complete control over log formatting, provide a FormatFn to the format option. This function receives a FormatObject containing the log data and a ColorHelpers instance for adding ANSI colors. Color functions automatically strip ANSI codes when writing to non-TTY outputs (e.g., files).
    import Logger, { type FormatFn } from "mime-logger";
    
    const myFormat: FormatFn = (obj, c) => {
      const ts = c.dim(obj.timestamp.toISOString());
      const level = obj.level.toUpperCase().padEnd(5);
      const name = obj.name ? ` ${c.cyan(obj.name)}` : "";
      return `${ts} ${level}${name} ${obj.message}`;
    };
    
    const logger = new Logger("app", { format: myFormat });
  5. Interpolate values in log messages

    Use the %s placeholder to interpolate values into log messages. Multiple placeholders are replaced sequentially from left to right.
    logger.info("User %s connected from %s", "alice", "192.168.1.1");
    logger.warn("Retrying in %s ms (attempt %s of %s)", 500, 2, 3);
  6. Import and initialize mime-logger

    mime-logger supports ESM, CommonJS, and TypeScript. To start logging, import the Logger class and create a new instance.
    import Logger from "mime-logger";
    const logger = new Logger();
  7. Implement a custom output function

    You can redirect log lines to a remote sink, queue, or buffer by providing a custom function to the output configuration. The function receives two arguments: the fully formatted log string (message) and the raw structured data (obj of type FormatObject).
    const logs: string[] = [];
    const logger = new Logger("app", {
      output: (message: string, obj: FormatObject) => {
        logs.push(message);
      },
    });
  8. Create scoped child loggers with hierarchical naming

    Child loggers allow you to create sub-loggers that share the parent's configuration (such as format and output targets) but have their own specific name segment. Names are joined using a forward slash (/), creating a breadcrumb trail (e.g., server -> server/http -> server/http/middleware). This hierarchy is useful for filtering logs by prefix in log aggregators.
    const app = new Logger("app");
    const db = app.child("database"); // Name: "app/database"
    const query = db.child("query");   // Name: "app/database/query"
    
    app.info("Starting");
    db.info("Connected");
    query.info("SELECT users");
  9. Install mime-logger

    Install the mime-logger package using your preferred package manager. The library supports both ESM and CJS and includes TypeScript types.
    npm install mime-logger
  10. Log messages using convenience methods

    mime-logger provides three convenience methods for logging based on severity. Each method renders a specific label color and message color:

    • info(): Informational messages. Label is green, message is cyan.
    • warn(): Non-fatal warnings. Label is yellow, message is yellow.
    • error(): Errors and failures. Label is red, message is red.
    const logger = new Logger("app");
    logger.info("Server ready");
    logger.warn("High memory usage");
    logger.error("Disk write failed");
  11. Use built-in log format presets

    mime-logger provides four built-in presets via the Formats object that can be passed to the format option in the Logger constructor.

    • Formats.pretty (Default): Dimmed timestamp, colored level badge, yellow name in parentheses, and colored message.
    • Formats.minimal: Level padded to 5 characters, dimmed name, and plain message. Ideal for compact single-process output.
    • Formats.detailed: Prepends the caller file and line number with an ISO timestamp. Best for debugging stack locations.
    • Formats.json: Outputs structured JSON containing timestamp, level, name, and message. Ideal for log aggregators.
    import Logger, { Formats } from "mime-logger";
    
    // Example using the 'pretty' preset
    const logger = new Logger("app", { format: Formats.pretty });
  12. Route logs to multiple output targets

    To write logs to multiple destinations simultaneously (e.g., both the console and a file), pass an array of output configurations to the output option. Every target in the array will receive the same formatted message.
    import Logger, { Formats } from "mime-logger";
    
    const logger = new Logger("app", {
      format: Formats.json,
      output: [
        "console",
        { type: "file", path: "./logs/{year}-{month}-{day}.log" },
      ],
    });