Ogma Documentation

website·Indexed 32 days ago

https://ogma.jaymcdoniel.dev/en/introduction/

A logging library and instrumentation tool featuring a NestJS module with specialized parsers for HTTP (Express, Fastify), GraphQL, WebSockets (ws, Socket.IO), and various RPC transports including TCP, Kafka, RabbitMQ, NATS, MQTT, Redis, and gRPC. Includes the OgmaInterceptor for request/response logging, a CLI for rehydrating JSON logs, and a Styler package for string formatting.

Tokens
9K
Snippets
59
Records
85
Agent score
54%

What's inside Ogma

  1. Understand how Ogma parses and maps GraphQL requests

    Ogma implements GraphQL parsing via the underlying HTTP adapter using apollo-server middleware. Because GraphQL typically uses a single endpoint (defaulting to /graphql), Ogma uses the [Controller#method] context to differentiate between executed queries. Since GraphQL does not use standard HTTP status codes, Ogma infers the status based on whether the request was a success or an error. If a Nest Exception is thrown, Ogma maps it to the corresponding HTTP status code; otherwise, it defaults to a 500 error.
    [2021-09-06T18:50:23.326Z] [INFO] [jay-pop] [GraphQL Express] [138646] [1630954223323447] [GqlResolver#getQuery] ::1 - query /graphql HTTP/1.1 200 2ms - 17
  2. Choose a Websocket parser for Ogma

    Ogma provides two different parsers for handling Websockets depending on the underlying library being used: one for the ws library and one for socket.io. To implement the desired behavior, install and use the corresponding platform package.
    # For socket.io support
    npm install @ogma/platform-socket.io
    
    # For ws support
    npm install @ogma/platform-ws
  3. Use Ogma with NestJS built-in RPC transports

    Ogma provides parsers for all built-in transports supported by NestJS microservices. Note that because of how NestJS microservices handle requests, the client IP address is not automatically available; it must be explicitly added to the payload sent by the client to be captured by Ogma.
  4. Configure request logging with OgmaInterceptor

    The OgmaInterceptor acts as an intelligent request logger. It automatically captures:

    • A unique request ID (generated via current time and Math.random(), though the generateRequestId method can be overridden).
    • Caller's IP address and protocol.
    • Route hit and the specific route handler class/method (set as the log context).
    • Request method and HTTP status.
    • Request duration and length of returned content.

    Caveat: Because it is an interceptor, it does not log errors occurring in middleware (e.g., Passport authentication/serialization) or Guards. Use a NestJS ExceptionFilter to handle those cases.

  5. Install Ogma Fastify platform support

    Install the @ogma/platform-fastify package to enable the FastifyInterceptorParser for the OgmaInterceptor. This allows the plugin to correctly parse Fastify request and response objects for logging purposes.
    npm i @ogma/platform-fastify
    # or
    yarn add @ogma/platform-fastify
  6. Automatically log method execution with @Log and @LogAll

    Use @Log() on a method or @LogAll() on a class to automatically log the start, end, and duration of method executions.

    Constraints & Configuration:

    • Compatibility: These decorators do not work on controller methods due to Nest's route handler proxy.
    • Logger Property: By default, they look for a logger property on the class. You can pass a different property name to the decorator if needed.
    • Log Level: Default level is fine. This can be changed via the traceMethod option in the OgmaModule.forRoot() configuration.
  7. Implement the InterceptorService interface

    The InterceptorService interface defines the core requirements for any parser used by the Ogma interceptor. It requires two primary methods to transform execution contexts into loggable objects.
    interface InterceptorService {
      getSuccessContext(
        data: number,
        context: ExecutionContext,
        startTime: number,
        options: OgmaInterceptorServiceOptions
      ): LogObject;
    
      getErrorContext(
        error: Error | HttpException,
        context: ExecutionContext,
        startTime: number,
        options: OgmaInterceptorServiceOptions
      ): LogObject;
    }
  8. Inject OgmaService into a NestJS provider

    To use OgmaService in a provider, register the provider in OgmaModule.forFeature() and use the @OgmaLogger() decorator in the constructor. Since OgmaService implements Nest's LoggerService, you can use the LoggerService type for better flexibility when swapping loggers.
    @Module({
      imports: [OgmaModule.forFeature(FooService)],
      providers: [FooService]
    })
    export class FooModule {}
    
    @Injectable()
    export class FooService {
      constructor(
        @OgmaLogger(FooService) private readonly logger: OgmaService
      ) {}
    }
  9. Install and implement parsers for OgmaInterceptor

    The OgmaInterceptor requires a parser to handle specific request contexts. You must either install a platform-specific package or provide a custom parser.

    • Default HTTP (Express): Use @ogma/platform-express for standard NestJS Express servers.
    • Custom Parsers: Must extend AbstractInterceptorService and use the @Parser(context) decorator. This ensures type safety and allows the DelegatorService to correctly route the context to the parser.
  10. Install Ogma Platform GraphQL Fastify

    Install the @ogma/platform-graphql-fastify package to provide the GraphQLFastifyParser for the OgmaInterceptor. This parser allows Ogma to successfully log GraphQL request and response data.
    npm i @ogma/platform-graphql-fastify
    # or
    yarn add @ogma/platform-graphql-fastify
  11. Install and use @ogma/styler for terminal string formatting

    The @ogma/styler package provides a chainable API to apply ANSI SGR (Select Graphic Rendition) styles to strings. You import the style instance, chain the desired style properties (e.g., colors, backgrounds, text decorations), and call the .apply() method to finalize the styling on a string or primitive.
    import { style } from '@ogma/styler';
    
    // Chain styles and apply to a string
    console.log(style.blue.yellowBg.underline.apply('Hello World!'));