log.go
Overview
The `log.go` file provides a simple, structured logging utility built on top of the popular Go logging library **logrus**. It offers a centralized logger instance configured for JSON output with timestamp and caller information included automatically. This file exposes a convenient interface for adding contextual fields to log entries, supporting enhanced traceability and debugging.
Key features:
Wraps
logrusto provide a consistent logging interface.Enables structured logging with annotated fields.
Automatically includes caller information (file and line number).
Configured to output JSON-formatted logs with timestamps.
Provides global logger with debug-level verbosity.
This file typically serves as the foundational logging component across the application, enabling other modules to log events, errors, and debugging information with contextual metadata in a uniform and structured manner.
Detailed Explanation
Types
type Fields = logrus.Fields
Description:
An alias forlogrus.Fields, which is a map type used to associate string keys with arbitrary values (map[string]interface{}) for structured logging.Usage:
Fields are used to add extra context to logs, such as user IDs, request IDs, or any relevant metadata.
Interfaces
type Logger interface
Description:
A wrapper interface that embedslogrus.FieldLogger, encompassing all standard logging methods includingDebug(),Info(),Warn(),Error(),WithFields(), etc.Purpose:
Abstracts the underlying logging implementation, allowing the rest of the application to depend on this interface for logging without direct dependency onlogrus.
Variables
var logger Logger
Description:
A package-level singleton logger instance initialized at startup.
Initialization
func init()
Description:
Initializes the package-levelloggervariable withlogrus's standard logger.Configuration details:
Log level is set to
DebugLevel, enabling verbose output.Caller reporting is enabled (
SetReportCaller(true)), which adds the origin of each log call (file and line number).Uses
logrus.JSONFormatterwith:Timestamp format:
"2006-01-02 15:04:05"Pretty print disabled (compact JSON output).
Effect:
This setup ensures that all logs emitted through this package will be detailed and structured, facilitating easy machine parsing and human readability.
Functions
func WithFields(fields Fields) Logger
Description:
Returns a logger instance that includes the provided fields as annotations on every log entry.Parameters:
fields Fields: Key-value pairs to attach to logs.
Returns:
ALoggerinstance with the specified fields embedded.Usage Example:
log.WithFields(log.Fields{
"user_id": 42,
"order": "12345",
}).Info("Order processed successfully")
This will produce a JSON log entry containing the `user_id` and `order` fields alongside the log message.
func WithoutFields() Logger
Description:
Returns the base logger instance without any additional field annotations.Returns:
The defaultLoggerinstance.Usage Example:
log.WithoutFields().Debug("Starting background job")
Implementation Details
Relies entirely on logrus as the underlying logging framework.
Uses logrus's standard logger singleton for simplicity and global access.
Caller reporting is enabled, so each log entry automatically includes the source file and line number, which is crucial for debugging.
JSON formatter is applied with precise timestamp formatting to standardize log output for log aggregation tools or external monitoring systems.
The package exports only two utility functions (
WithFieldsandWithoutFields) to simplify usage and encourage structured logging patterns.
Interaction with Other System Components
This logging package is designed to be imported and used by all other components within the application.
It provides a consistent interface for logging regardless of the module, ensuring uniform log format and verbosity.
Downstream systems like monitoring, alerting, or log aggregation services consume the JSON logs produced by this utility.
Since caller information is included, developers and support engineers can quickly trace log entries back to the source code.
Visual Diagram
flowchart TD
A[log.go Package] --> B[logger (logrus.StandardLogger)]
B --> C[Configured with JSONFormatter]
B --> D[DebugLevel Logging]
B --> E[Caller Reporting Enabled]
A --> F[WithFields(fields Fields) Logger]
A --> G[WithoutFields() Logger]
F --> B
G --> B
**Diagram Explanation:**
The
loggervariable wraps the standardlogruslogger configured with JSON output, debug level, and caller reporting.WithFieldsreturns a new logger instance chaining the provided fields.WithoutFieldsreturns the base logger directly.All logging calls flow through this central logger instance.
Summary
The `log.go` file is a minimal yet powerful abstraction over `logrus`, providing structured, JSON-formatted logging with caller context for the entire application. It simplifies adding metadata to logs and ensures consistent log formatting and detail level. This foundational logging utility enhances observability and debugging capabilities across the system.