Skip to content

feat(logging): Implement robust Zap logger initialization#7

Merged
nutcas3 merged 3 commits intomainfrom
logger
Jul 29, 2025
Merged

feat(logging): Implement robust Zap logger initialization#7
nutcas3 merged 3 commits intomainfrom
logger

Conversation

@nutcas3
Copy link
Copy Markdown
Owner

@nutcas3 nutcas3 commented Jul 22, 2025

This commit introduces a new logging package designed to provide a centralized and configurable logging solution using go.uber.org/zap. This setup ensures consistent logging practices across the application, with support for different logging levels, development/production configurations, and structured output.

Key features and components:

  • Global Logger Instance:
    • Uses a sync.Once (or in this case, a sync.RWMutex with an initialized flag)
      to ensure the zap.Logger is initialized only once, providing a singleton
      instance accessible throughout the application.
  • Configurable Logging:
    • LogLevel enum: Defines debug, info, warn, and error levels.
    • Config struct: Allows specifying Level, Development mode, and Encoding
      (e.g., "json" or "console").
    • DefaultConfig(): Provides a sensible default configuration (info level,
      production mode, JSON encoding).
  • Initialize(config Config) Function:
    • Sets up the zap.Logger based on the provided Config.
    • Dynamically sets zapcore.Level based on LogLevel.
    • Configures zap.Config for development (human-readable) or production (JSON,
      ISO8601 timestamps) encoder settings.
    • Sets OutputPaths to stdout and ErrorOutputPaths to stderr.
    • Handles potential errors during logger build process.
  • Logger() Function:
    • Provides global access to the initialized *zap.Logger instance.
    • Includes ensureInitialized() to lazily initialize the logger with default
      settings if Initialize hasn't been explicitly called.
  • Convenience Functions:
    • With(fields ...zap.Field): Allows adding contextual fields to the logger.
    • Debug, Info, Warn, Error: Simple wrappers for common logging levels.
  • Sync() Function:
    • Flushes any buffered log entries, important for graceful shutdowns to prevent
      lost logs.

This logging package significantly enhances the observability and debugging capabilities of the application by providing a robust, flexible, and easy-to-use logging utility.

nutcas3 added 3 commits July 22, 2025 15:24
…access

This commit introduces a new `logging` package designed to provide a centralized
and configurable logging solution using `go.uber.org/zap`. This setup ensures
consistent logging practices across the application, with support for different
logging levels, development/production configurations, and structured output.

Key features and components:

-   **Global Logger Instance**:
    -   Uses a `sync.Once` (or in this case, a `sync.RWMutex` with an `initialized` flag)
        to ensure the `zap.Logger` is initialized only once, providing a singleton
        instance accessible throughout the application.
-   **Configurable Logging**:
    -   `LogLevel` enum: Defines `debug`, `info`, `warn`, and `error` levels.
    -   `Config` struct: Allows specifying `Level`, `Development` mode, and `Encoding`
        (e.g., "json" or "console").
    -   `DefaultConfig()`: Provides a sensible default configuration (info level,
        production mode, JSON encoding).
-   **`Initialize(config Config)` Function**:
    -   Sets up the `zap.Logger` based on the provided `Config`.
    -   Dynamically sets `zapcore.Level` based on `LogLevel`.
    -   Configures `zap.Config` for development (human-readable) or production (JSON,
        ISO8601 timestamps) encoder settings.
    -   Sets `OutputPaths` to `stdout` and `ErrorOutputPaths` to `stderr`.
    -   Handles potential errors during logger build process.
-   **`Logger()` Function**:
    -   Provides global access to the initialized `*zap.Logger` instance.
    -   Includes `ensureInitialized()` to lazily initialize the logger with default
        settings if `Initialize` hasn't been explicitly called.
-   **Convenience Functions**:
    -   `With(fields ...zap.Field)`: Allows adding contextual fields to the logger.
    -   `Debug`, `Info`, `Warn`, `Error`: Simple wrappers for common logging levels.
-   **`Sync()` Function**:
    -   Flushes any buffered log entries, important for graceful shutdowns to prevent
        lost logs.

This logging package significantly enhances the observability and debugging capabilities
of the application by providing a robust, flexible, and easy-to-use logging utility.
…events

This commit introduces a dedicated `CircuitBreakerLogger` within the `logging`
package, providing specialized logging capabilities for circuit breaker
operations. This new logger standardizes how circuit breaker events, state
changes, and metrics are captured, making it easier to monitor and debug
resilience patterns in the application.

Key features and methods:

-   **`CircuitBreakerLogger` struct**: Wraps a `*zap.Logger` instance,
    automatically tagging all circuit breaker logs with `component: "circuit_breaker"`.
-   **`NewCircuitBreakerLogger()`**: Constructor to create a new logger instance,
    ensuring consistent component tagging.
-   **`LogStateChange(name string, from, to string)`**: Logs transitions
    between circuit breaker states (e.g., "closed" to "open"), providing
    visibility into the circuit's behavior. Logged at `Info` level.
-   **`LogTrip(name string, err error)`**: Records when a circuit breaker
    "trips" (opens due to failures), including the error that caused the trip.
    Logged at `Warn` level to highlight significant events.
-   **`LogReset(name string)`**: Logs when a circuit breaker "resets" (closes
    after recovering from a tripped state). Logged at `Info` level.
-   **`LogSuccess(name string)`**: Logs successful requests through the circuit
    breaker. Logged at `Debug` level for detailed tracing.
-   **`LogFailure(name string, err error)`**: Logs failed requests through the
    circuit breaker, including the error. Logged at `Debug` level.
-   **`LogRejection(name string)`**: Logs when a request is rejected by an
    open circuit breaker. Logged at `Debug` level.
-   **`LogMetrics(...)`**: Provides comprehensive logging of circuit breaker
    metrics, including current state, request counts, failure counts,
    and time in state. Logged at `Debug` level for performance analysis.

All logging functions automatically include the current timestamp, and relevant
fields (`circuit`, `state`, `error`, etc.) are captured as structured `zap.Field`s,
enhancing log parseability and analysis. This dedicated logger significantly
improves the operational visibility of circuit breaker patterns.
@nutcas3 nutcas3 merged commit 4855c80 into main Jul 29, 2025
3 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant