roarr

repository·main·Indexed 22 days ago

https://github.com/gajus/roarr

A fast, structured JSON logger for Node.js and the browser. It supports printf-style formatting, contextual child loggers, and asynchronous context propagation via the adopt method in Node.js. It provides convenience methods for log levels (trace, debug, info, warn, error, fatal) and integrates with @roarr/cli for filtering and pretty-printing.

Tokens
5.9K
Snippets
26
Records
33
Agent score
77%

What's inside roarr

  1. Understand Context Truncation

    main
    To prevent performance issues and accidental logging of massive objects, Roarr automatically truncates context properties if the context object contains more than 10 properties. When this limit is reached, you will see a "...": "1 item not stringified" entry in the JSON output.
  2. Recommended Context Property Conventions

    main

    Roarr does not have reserved context property names, but following these conventions ensures compatibility with the roarr pretty-print CLI tool and other integrations:

    PropertyUse Case
    applicationName of the application (use package instead for distributed code)
    logLevelNumeric value indicating the log level
    namespaceNamespace within a package (e.g., function name), similar to the debug package
    packageName of the NPM package

    Log Level Mapping

    The roarr pretty-print CLI translates logLevel numeric values as follows:

    logLevelName
    10TRACE
    20DEBUG
    30INFO
    40WARN
    50ERROR
    60FATAL
  3. Enable logging in Node.js

    main

    In Node.js, Roarr logging is disabled by default. To enable it, you must set the ROARR_LOG environment variable to true when starting your program. When enabled, all logs are written to stdout.

    ROARR_LOG=true node ./index.js
  4. Install and use the Roarr CLI

    main

    The Roarr CLI is a separate package used to filter and pretty-print Roarr logs. It is useful for inspecting JSON log streams in a human-readable format.

    Install it globally via npm:

    npm install @roarr/cli -g

    Run roarr --help to see all available commands and options.

  5. Implement log consumption in the Browser

    main

    In a browser environment, you must manually implement the ROARR.write method to capture and process logs. The ROARR.write method accepts a single argument: a message string (which is a JSON-formatted log entry).

    If you need to configure ROARR.write before the roarr package is loaded, you should initialize it on globalThis.ROARR.

    import { ROARR } from "roarr";
    
    // Basic implementation
    ROARR.write = (message) => {
      console.log(JSON.parse(message));
    };
  6. Produce logs with Roarr

    main

    To produce logs in either Node.js or the browser, import the Roarr class and use its API methods. The API is consistent across both environments.

    import { Roarr as log } from "roarr";
    
    log("foo");
  7. Clean up Roarr in Test Environments

    main

    In Node.js, Roarr registers an error listener on the output stream to ignore EPIPE errors. If your test runner creates isolated module environments, you should call ROARR.teardown() during teardown to prevent listener leaks.

    import { ROARR } from "roarr";
    
    afterEach(() => {
      ROARR.teardown?.();
    });
  8. Filter logs in Node.js and Browser

    main

    Node.js

    In Node.js, Roarr prints all or none based on the ROARR_LOG variable. To filter the output, pipe the stdout to the @roarr/cli program using the --filter flag.

    Browser

    In the browser, you filter logs by implementing custom logic inside your globalThis.ROARR.write implementation.

    # Node.js filtering with @roarr/cli
    ROARR_LOG=true node ./index.js | roarr --filter 'context.logLevel:>30'
  9. Implement a Singleton Logger Pattern

    main

    To avoid code duplication and ensure consistent context across your application, create a dedicated logger file (e.g., Logger.js) that exports a child instance of Roarr with predefined context properties.

    /**
     * @file Example contents of a Logger.js file.
     */
    
    import { Roarr } from "roarr";
    
    export const Logger = Roarr.child({
      // .foo property is going to appear only in the logs that are created using
      // the current instance of a Roarr logger.
      foo: "bar",
    });
  10. Integrate Roarr with NestJS

    main

    You can use nestjs-logger-roarr to integrate Roarr into NestJS applications.

    Option 1: Shared Logger Instance Use RoarrLoggerService.sharedInstance() to provide a single logger for the entire application during NestFactory creation.

    Option 2: Module Injection Use RoarrLoggerModule.forRoot() in your AppModule to enable multiple injected loggers with a minimum logLevel configuration.

    // Option 1: Shared Instance
    import { RoarrLoggerService } from 'nestjs-logger-roarr';
    import { AppModule } from "app.module";
    
    const logger = RoarrLoggerService.sharedInstance();
    const app = await NestFactory.create(AppModule, { logger });
    
    // Option 2: Module Syntax
    import { Module } from '@nestjs/common';
    import { ConfigModule } from '@nestjs/config';
    import { RoarrLoggerModule } from 'nestjs-logger-roarr';
    
    @Module({
      imports: [
        RoarrLoggerModule.forRoot({
          logLevel: 'warn', // minimum log level displayed
        }),
      ],
    })
    export class AppModule {}
  11. Configure Roarr via environment variables

    main

    You can control Roarr's behavior using the following environment variables:

    NameTypeFunctionDefault
    ROARR_LOGBooleanEnables/disables loggingfalse
    ROARR_STREAMSTDOUT or STDERRThe stream where logs are writtenSTDOUT

    Tip: If you set ROARR_STREAM=STDERR, you may need to use shell redirection to pipe the output correctly, for example: `3>&1 1>&2 2>&3 3&-".

  12. Understand the Message and MessageContext structures

    main

    Roarr uses structured data for its logs.

    MessageContext A MessageContext is a JsonObject (a valid JSON object) that can be extended with custom properties. It represents the metadata attached to a log entry.

    Message A Message<T> represents the complete log entry structure. It contains:

    • context: The MessageContext (type T).
    • message: The actual log string.
    • sequence: A unique sequence identifier.
    • time: A timestamp (number).
    • version: The version of the log format.