Conversation
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This commit introduces a new
loggingpackage designed to provide a centralized and configurable logging solution usinggo.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:
sync.Once(or in this case, async.RWMutexwith aninitializedflag)to ensure the
zap.Loggeris initialized only once, providing a singletoninstance accessible throughout the application.
LogLevelenum: Definesdebug,info,warn, anderrorlevels.Configstruct: Allows specifyingLevel,Developmentmode, andEncoding(e.g., "json" or "console").
DefaultConfig(): Provides a sensible default configuration (info level,production mode, JSON encoding).
Initialize(config Config)Function:zap.Loggerbased on the providedConfig.zapcore.Levelbased onLogLevel.zap.Configfor development (human-readable) or production (JSON,ISO8601 timestamps) encoder settings.
OutputPathstostdoutandErrorOutputPathstostderr.Logger()Function:*zap.Loggerinstance.ensureInitialized()to lazily initialize the logger with defaultsettings if
Initializehasn't been explicitly called.With(fields ...zap.Field): Allows adding contextual fields to the logger.Debug,Info,Warn,Error: Simple wrappers for common logging levels.Sync()Function: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.