logger

package
v0.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2026 License: MIT Imports: 9 Imported by: 0

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug(msg string)

Debug logs a debug level message using the global logger

func DebugEvent

func DebugEvent() *zerolog.Event

DebugEvent returns a debug level event for chaining

func DebugWithFields

func DebugWithFields(msg string, fields map[string]interface{})

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 Error

func Error(msg string)

Error logs an error level message using the global logger

func ErrorEvent

func ErrorEvent() *zerolog.Event

ErrorEvent returns an error level event for chaining

func ErrorWithErr

func ErrorWithErr(msg string, err error)

ErrorWithErr logs an error level message with an error using the global logger

func ErrorWithFields

func ErrorWithFields(msg string, fields map[string]interface{})

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

func GetRequestID(ctx context.Context) (string, bool)

GetRequestID retrieves the request ID from the context

func GetSessionID

func GetSessionID(ctx context.Context) (string, bool)

GetSessionID retrieves the session ID from the context

func GetUserID

func GetUserID(ctx context.Context) (string, bool)

GetUserID retrieves the user ID from the context

func Info

func Info(msg string)

Info logs an info level message using the global logger

func InfoEvent

func InfoEvent() *zerolog.Event

InfoEvent returns an info level event for chaining

func InfoWithFields

func InfoWithFields(msg string, fields map[string]interface{})

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 Init

func Init()

Init initializes the global logger with default configuration

func SetGlobalLogger

func SetGlobalLogger(logger *Logger)

SetGlobalLogger sets the global logger instance

func SetLevel

func SetLevel(level string) error

SetLevel sets the log level for the global logger

func Warn

func Warn(msg string)

Warn logs a warning level message using the global logger

func WarnEvent

func WarnEvent() *zerolog.Event

WarnEvent returns a warn level event for chaining

func WarnWithFields

func WarnWithFields(msg string, fields map[string]interface{})

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

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID adds a request ID to the context

func WithSessionID

func WithSessionID(ctx context.Context, sessionID string) context.Context

WithSessionID adds a session ID to the context

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID adds a user 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 New

func New(config *Config) (*Logger, error)

New creates a new Logger instance with the provided configuration

func WithContext

func WithContext(ctx context.Context) *Logger

WithContext returns a logger with context values extracted and added as fields

func (*Logger) Debug

func (l *Logger) Debug(msg string)

Debug logs a debug level message

func (*Logger) DebugWithFields

func (l *Logger) DebugWithFields(msg string, fields map[string]interface{})

DebugWithFields logs a debug level message with structured fields

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

Debugf logs a formatted debug level message

func (*Logger) Error

func (l *Logger) Error(msg string)

Error logs an error level message

func (*Logger) ErrorWithErr

func (l *Logger) ErrorWithErr(msg string, err error)

ErrorWithErr logs an error level message with an error

func (*Logger) ErrorWithFields

func (l *Logger) ErrorWithFields(msg string, fields map[string]interface{})

ErrorWithFields logs an error level message with structured fields

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{})

Errorf logs a formatted error level message

func (*Logger) Fatal

func (l *Logger) Fatal(msg string)

Fatal logs a fatal level message and exits the program

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, args ...interface{})

Fatalf logs a formatted fatal level message and exits the program

func (*Logger) GetZerologLogger

func (l *Logger) GetZerologLogger() zerolog.Logger

GetZerologLogger returns the underlying zerolog.Logger for advanced usage

func (*Logger) Info

func (l *Logger) Info(msg string)

Info logs an info level message

func (*Logger) InfoWithFields

func (l *Logger) InfoWithFields(msg string, fields map[string]interface{})

InfoWithFields logs an info level message with structured fields

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof logs a formatted info level message

func (*Logger) Warn

func (l *Logger) Warn(msg string)

Warn logs a warning level message

func (*Logger) WarnWithFields

func (l *Logger) WarnWithFields(msg string, fields map[string]interface{})

WarnWithFields logs a warning level message with structured fields

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...interface{})

Warnf logs a formatted warning level message

func (*Logger) With

func (l *Logger) With() zerolog.Context

With returns a new logger with additional fields

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

WithContext returns a logger with context values extracted and added as 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"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL