Documentation
¶
Overview ¶
Package logger provides a structured logging system with configurable log levels, output formats, rotation, and context-aware logging capabilities.
Example (BasicUsage) ¶
Example_basicUsage demonstrates basic logging
package main
import (
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
// Create a logger with text format for readable output
config := &logger.Config{
Level: logger.InfoLevel,
Format: logger.TextFormat,
Output: "stdout",
}
log, err := logger.New(config)
if err != nil {
panic(err)
}
log.Info("Application started")
log.Infof("Server listening on port %d", 8080)
log.Warn("This is a warning")
}
Example (ContextAwareLogging) ¶
Example_contextAwareLogging demonstrates context-aware logging
package main
import (
"context"
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
config := &logger.Config{
Level: logger.InfoLevel,
Format: logger.JSONFormat,
Output: "stdout",
}
log, err := logger.New(config)
if err != nil {
panic(err)
}
// Create context with IDs
ctx := context.Background()
ctx = logger.WithRequestID(ctx, "req-abc123")
ctx = logger.WithSessionID(ctx, "sess-xyz789")
// Create context-aware logger
ctxLog := log.WithContext(ctx)
// All logs will include request_id and session_id
ctxLog.Info("Processing request")
ctxLog.Info("Request completed")
}
Example (DifferentLevels) ¶
Example_differentLevels demonstrates all log levels
package main
import (
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
config := &logger.Config{
Level: logger.DebugLevel,
Format: logger.TextFormat,
Output: "stdout",
}
log, err := logger.New(config)
if err != nil {
panic(err)
}
log.Debug("This is a debug message")
log.Info("This is an info message")
log.Warn("This is a warning message")
log.Error("This is an error message")
}
Example (EnvironmentBasedConfig) ¶
Example_environmentBasedConfig demonstrates configuring logger based on environment
package main
import (
"os"
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
env := os.Getenv("ENVIRONMENT")
if env == "" {
env = "development"
}
var config *logger.Config
switch env {
case "production":
config = &logger.Config{
Level: logger.InfoLevel,
Format: logger.JSONFormat,
Output: "/var/log/ainative-code/app.log",
EnableRotation: true,
MaxSize: 100,
MaxBackups: 10,
MaxAge: 30,
Compress: true,
}
case "development":
config = &logger.Config{
Level: logger.DebugLevel,
Format: logger.TextFormat,
Output: "stdout",
EnableCaller: true,
}
default:
config = logger.DefaultConfig()
}
log, err := logger.New(config)
if err != nil {
panic(err)
}
log.InfoWithFields("Logger configured", map[string]interface{}{
"environment": env,
})
}
Example (ErrorLogging) ¶
Example_errorLogging demonstrates error logging
package main
import (
"fmt"
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
config := &logger.Config{
Level: logger.ErrorLevel,
Format: logger.JSONFormat,
Output: "stdout",
EnableStackTrace: true,
}
log, err := logger.New(config)
if err != nil {
panic(err)
}
// Log error with message
log.Error("Something went wrong")
// Log error with formatted message
log.Errorf("Failed to process item %d", 42)
// Log error with error object
someError := fmt.Errorf("database connection failed")
log.ErrorWithErr("Database error", someError)
// Log error with structured fields
log.ErrorWithFields("Processing failed", map[string]interface{}{
"item_id": 123,
"reason": "timeout",
})
}
Example (FileLogging) ¶
Example_fileLogging demonstrates logging to a file
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
tmpDir := os.TempDir()
logFile := filepath.Join(tmpDir, "app.log")
config := &logger.Config{
Level: logger.DebugLevel,
Format: logger.JSONFormat,
Output: logFile,
}
log, err := logger.New(config)
if err != nil {
panic(err)
}
log.Debug("Debug message")
log.Info("Info message")
log.Warn("Warning message")
fmt.Printf("Logs written to: %s\n", logFile)
}
Example (GlobalLogger) ¶
Example_globalLogger demonstrates using the global logger
package main
import (
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
// The global logger is automatically initialized with default config
logger.Info("Using global logger")
logger.Infof("Formatted message: %s", "example")
// You can also set a custom global logger
config := &logger.Config{
Level: logger.DebugLevel,
Format: logger.TextFormat,
Output: "stdout",
}
customLog, err := logger.New(config)
if err != nil {
panic(err)
}
logger.SetGlobalLogger(customLog)
logger.Debug("This debug message will now be logged")
}
Example (HttpServerLogging) ¶
Example_httpServerLogging demonstrates logging in an HTTP server context
package main
import (
"context"
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
config := &logger.Config{
Level: logger.InfoLevel,
Format: logger.JSONFormat,
Output: "stdout",
}
log, err := logger.New(config)
if err != nil {
panic(err)
}
// Simulate HTTP request handling
requestID := "req-123456"
userID := "user-789"
ctx := context.Background()
ctx = logger.WithRequestID(ctx, requestID)
ctx = logger.WithUserID(ctx, userID)
reqLog := log.WithContext(ctx)
reqLog.InfoWithFields("HTTP request started", map[string]interface{}{
"method": "GET",
"path": "/api/users",
})
reqLog.InfoWithFields("HTTP request completed", map[string]interface{}{
"status": 200,
"duration_ms": 45,
})
}
Example (LogRotation) ¶
Example_logRotation demonstrates log rotation configuration
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
tmpDir := os.TempDir()
logFile := filepath.Join(tmpDir, "rotating.log")
config := &logger.Config{
Level: logger.InfoLevel,
Format: logger.JSONFormat,
Output: logFile,
EnableRotation: true,
MaxSize: 100, // 100 MB
MaxBackups: 5, // Keep 5 old files
MaxAge: 30, // 30 days
Compress: true,
}
log, err := logger.New(config)
if err != nil {
panic(err)
}
log.Info("This log will be rotated based on the configuration")
fmt.Println("Log rotation configured successfully")
}
Output: Log rotation configured successfully
Example (StructuredLogging) ¶
Example_structuredLogging demonstrates structured logging with fields
package main
import (
"github.com/AINative-studio/ainative-code/internal/logger"
)
func main() {
config := &logger.Config{
Level: logger.InfoLevel,
Format: logger.JSONFormat,
Output: "stdout",
}
log, err := logger.New(config)
if err != nil {
panic(err)
}
log.InfoWithFields("User action", map[string]interface{}{
"user_id": "user123",
"action": "login",
"ip": "192.168.1.1",
})
}
Index ¶
- func Debug(msg string)
- func DebugEvent() *zerolog.Event
- func DebugWithFields(msg string, fields map[string]interface{})
- func Debugf(format string, args ...interface{})
- func Error(msg string)
- func ErrorEvent() *zerolog.Event
- func ErrorWithErr(msg string, err error)
- func ErrorWithFields(msg string, fields map[string]interface{})
- func Errorf(format string, args ...interface{})
- func Fatal(msg string)
- func Fatalf(format string, args ...interface{})
- func GetRequestID(ctx context.Context) (string, bool)
- func GetSessionID(ctx context.Context) (string, bool)
- func GetUserID(ctx context.Context) (string, bool)
- func Info(msg string)
- func InfoEvent() *zerolog.Event
- func InfoWithFields(msg string, fields map[string]interface{})
- func Infof(format string, args ...interface{})
- func Init()
- func SetGlobalLogger(logger *Logger)
- func SetLevel(level string) error
- func Warn(msg string)
- func WarnEvent() *zerolog.Event
- func WarnWithFields(msg string, fields map[string]interface{})
- func Warnf(format string, args ...interface{})
- func WithRequestID(ctx context.Context, requestID string) context.Context
- func WithSessionID(ctx context.Context, sessionID string) context.Context
- func WithUserID(ctx context.Context, userID string) context.Context
- type Config
- type LogLevel
- type Logger
- func (l *Logger) Debug(msg string)
- func (l *Logger) DebugWithFields(msg string, fields map[string]interface{})
- func (l *Logger) Debugf(format string, args ...interface{})
- func (l *Logger) Error(msg string)
- func (l *Logger) ErrorWithErr(msg string, err error)
- func (l *Logger) ErrorWithFields(msg string, fields map[string]interface{})
- func (l *Logger) Errorf(format string, args ...interface{})
- func (l *Logger) Fatal(msg string)
- func (l *Logger) Fatalf(format string, args ...interface{})
- func (l *Logger) GetZerologLogger() zerolog.Logger
- func (l *Logger) Info(msg string)
- func (l *Logger) InfoWithFields(msg string, fields map[string]interface{})
- func (l *Logger) Infof(format string, args ...interface{})
- func (l *Logger) Warn(msg string)
- func (l *Logger) WarnWithFields(msg string, fields map[string]interface{})
- func (l *Logger) Warnf(format string, args ...interface{})
- func (l *Logger) With() zerolog.Context
- func (l *Logger) WithContext(ctx context.Context) *Logger
- type LoggerInterface
- type OutputFormat
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DebugEvent ¶
DebugEvent returns a debug level event for chaining
func DebugWithFields ¶
DebugWithFields logs a debug level message with structured fields using the global logger
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf logs a formatted debug level message using the global logger
func ErrorEvent ¶
ErrorEvent returns an error level event for chaining
func ErrorWithErr ¶
ErrorWithErr logs an error level message with an error using the global logger
func ErrorWithFields ¶
ErrorWithFields logs an error level message with structured fields using the global logger
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf logs a formatted error level message using the global logger
func Fatal ¶
func Fatal(msg string)
Fatal logs a fatal level message and exits the program using the global logger
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf logs a formatted fatal level message and exits the program using the global logger
func GetRequestID ¶
GetRequestID retrieves the request ID from the context
func GetSessionID ¶
GetSessionID retrieves the session ID from the context
func InfoWithFields ¶
InfoWithFields logs an info level message with structured fields using the global logger
func Infof ¶
func Infof(format string, args ...interface{})
Infof logs a formatted info level message using the global logger
func SetGlobalLogger ¶
func SetGlobalLogger(logger *Logger)
SetGlobalLogger sets the global logger instance
func WarnWithFields ¶
WarnWithFields logs a warning level message with structured fields using the global logger
func Warnf ¶
func Warnf(format string, args ...interface{})
Warnf logs a formatted warning level message using the global logger
func WithRequestID ¶
WithRequestID adds a request ID to the context
func WithSessionID ¶
WithSessionID adds a session ID to the context
Types ¶
type Config ¶
type Config struct {
// Level sets the minimum log level that will be output
Level LogLevel
// Format specifies the output format (json or text)
Format OutputFormat
// Output specifies where logs should be written (file path or "stdout"/"stderr")
Output string
// EnableRotation enables log file rotation
EnableRotation bool
// MaxSize is the maximum size in megabytes of the log file before it gets rotated
// Only applies when EnableRotation is true
MaxSize int
// MaxBackups is the maximum number of old log files to retain
// Only applies when EnableRotation is true
MaxBackups int
// MaxAge is the maximum number of days to retain old log files
// Only applies when EnableRotation is true
MaxAge int
// Compress determines if the rotated log files should be compressed using gzip
// Only applies when EnableRotation is true
Compress bool
// EnableCaller adds the file and line number where the log was called
EnableCaller bool
// EnableStackTrace adds stack traces for error level logs
EnableStackTrace bool
}
Config holds the configuration for the logger
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a default logger configuration
type LogLevel ¶
type LogLevel string
LogLevel represents the severity level of a log entry
const ( // DebugLevel logs are typically voluminous and are usually disabled in production DebugLevel LogLevel = "debug" // InfoLevel is the default logging priority InfoLevel LogLevel = "info" // WarnLevel logs are more important than Info, but don't need individual human review WarnLevel LogLevel = "warn" // ErrorLevel logs are high-priority. If an application is running smoothly, // it shouldn't generate any error-level logs ErrorLevel LogLevel = "error" )
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger wraps zerolog.Logger with additional context
func GetGlobalLogger ¶
func GetGlobalLogger() *Logger
GetGlobalLogger returns the global logger instance
func WithContext ¶
WithContext returns a logger with context values extracted and added as fields
func (*Logger) DebugWithFields ¶
DebugWithFields logs a debug level message with structured fields
func (*Logger) ErrorWithErr ¶
ErrorWithErr logs an error level message with an error
func (*Logger) ErrorWithFields ¶
ErrorWithFields logs an error level message with structured fields
func (*Logger) GetZerologLogger ¶
GetZerologLogger returns the underlying zerolog.Logger for advanced usage
func (*Logger) InfoWithFields ¶
InfoWithFields logs an info level message with structured fields
func (*Logger) WarnWithFields ¶
WarnWithFields logs a warning level message with structured fields
type LoggerInterface ¶
type LoggerInterface interface {
Debug(msg string)
Info(msg string)
Warn(msg string)
Error(msg string)
}
LoggerInterface defines the interface for logging operations This allows for test mocks and alternative logger implementations
type OutputFormat ¶
type OutputFormat string
OutputFormat specifies the format for log output
const ( // JSONFormat outputs logs in JSON format JSONFormat OutputFormat = "json" // TextFormat outputs logs in human-readable console format TextFormat OutputFormat = "text" )