How vuduongtp/go-logadapter works
Project type and purpose
• This is an open-source Go library (“go-logadapter”) that sits between an application and Go’s logging packages to provide:
• Multi-destination logging (console, file)
• Customizable formats (JSON, pretty JSON, text)
• Log filtering by level or custom fields
• Pluggable adapters for Echo (HTTP framework) and Gorm (ORM)
File structure
• Top-level Go source files:
• constant.go: global constants (e.g., default log keys or formats)
• util.go: helper functions (e.g., context extraction, ID generators)
• echo_adapter.go: implements Echo’s Logger interface + middleware
• gorm_adapter.go: implements Gorm’s logger.Interface
• main.go: example/demo of setting up and running an Echo server
• test/test.go: end-to-end usage example
• go.mod / go.sum: dependency management
• README.md: project overview and usage instructions
README for insights
• Core concepts: Config struct, SetLogger/NewWithConfig, SetFormatter
• Two official adapters: EchoLogger & EchoLoggerMiddleware, GormLogger
• FileConfig for rotating file output
Main components & their interactions
A. Core Logging Engine (logadapter package)
– Exposes functions: Debug, InfoWithContext, Error, Warn, SetLogger, SetFormatter
– Holds a singleton “Logger” instance configured with:
• LogLevel, LogFormat, TimestampFormat
• Sinks: console writer and optional rotating file writer (FileConfig)
– Reads custom fields from context
B. Echo Adapter
– Implements echo.Logger interface
– Middleware injects request_id & correlation_id into request context
– Routes all Echo logs and HTTP request logs into the core logger
C. Gorm Adapter
– Implements gorm/logger.Interface
– On each SQL call, captures query, row count, latency
– Routes Gorm logs into the core logger with custom fields (type=”sql”)
D. File Writer (optional sink)
– Uses lumberjack or similar for log rotation: size, backups, age, compression
E. Client application (e.g., main.go or any user code)
– Calls logadapter.SetLogger(NewWithConfig(&Config{…}))
– Imports and uses logadapter.Debug, InfoWithContext, etc.
– For Echo: replaces e.Logger, adds middleware
– For Gorm: sets db.Logger = NewGormLogger()
Key architectural patterns & principles
• Dependency Injection via interfaces (Echo’s Logger, Gorm’s logger.Interface)
• Singleton / Global logger instance but configured at startup
• Strategy pattern for formatters (JSONFormat, PrettyJSONFormat, TextFormat)
• Decorator over standard loggers for multi-sink capability
• Context propagation for custom fields