goLogger

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2025 License: MIT Imports: 11 Imported by: 3

README

[!Note] This content is translated by LLM. Original text can be found here

Go Logger

A Golang logging package with automatic rotation, multi-level log classification, file management capabilities, and comprehensive error handling mechanisms.
Primarily designed for use in pardnchiu/go-* packages

lang license version card
readme readme

Three Core Features

Support for slog Standardization and Tree Structure Output

JSON uses Go's standard log/slog package for structured logging Text adopts tree structure to enhance readability

Complete Multi-Level Log Classification

Supports 8 levels (DEBUG, TRACE, INFO, NOTICE, WARNING, ERROR, FATAL, CRITICAL)

Automatic File Rotation and Cleanup

Automatically rotates and creates backups when files reach size limits, intelligently cleans expired files to maintain configured backup count

Usage

Installation
go get github.com/pardnchiu/go-logger
Initialization
package main

import (
  "fmt"
  "errors"
  
  "github.com/pardnchiu/go-logger"
)

func main() {
  config := &goLogger.Log{
    Path:      "./logs",              // Log directory
    Stdout:    true,                  // Also output to terminal
    MaxSize:   16 * 1024 * 1024,      // 16MB file size limit
    MaxBackup: 5,                     // Keep 5 backup files
    Type:      "json",                // "json" for slog standard, "text" for tree format
  }
  
  // Initialize
  logger, err := goLogger.New(config)
  if err != nil {
    panic(err)
  }
  defer logger.Close()
  
  // Log messages at different levels
  logger.Debug("This is debug message", "detailed debug info")
  logger.Trace("Trace program execution flow")
  logger.Info("General information message")
  logger.Notice("Message that needs attention")
  logger.Warn("Warning message")
  
  // Error handling
  err = errors.New("an error occurred")
  logger.WarnError(err, "Warning message for handling error")
  logger.Error(err, "Additional message for handling error")
  logger.Fatal(err, "Critical error")
  logger.Critical(err, "System critical error")
  
  // Flush cache
  logger.Flush()
}

Configuration

type Log struct {
  Path      string // Log file directory path (default: ./logs)
  Stdout    bool   // Whether to output to stdout (default: false)
  MaxSize   int64  // Maximum log file size in bytes (default: 16MB)
  MaxBackup int    // Maximum number of backup files (default: 5)
  Type      string // Output format: "json" for slog standard, "text" for tree format (default: "text")
}

Output Formats

slog Standard

When Type: "json", logs are output in log/slog structured format:

{"timestamp":"2024/01/15 14:30:25.123456","level":"INFO","message":"Application started","data":null}
{"timestamp":"2024/01/15 14:30:25.123457","level":"ERROR","message":"Database connection failed","data":["Connection timeout","Retry in 5 seconds"]}
  • Directly uses Go's standard log/slog package
  • Easy integration with log aggregation tools
  • Consistent JSON schema across all log levels
Tree Structure

When Type: "text", logs are displayed in tree format:

2024/01/15 14:30:25.123457 [ERROR] Database connection failed
2024/01/15 14:30:25.123457 ├── Connection timeout
2024/01/15 14:30:25.123457 └── Retry in 5 seconds
  • Clear hierarchical message structure
  • Enhanced readability during debugging

Log Levels

Debug and Trace

Logged to debug.log

logger.Debug("Variable values", "x = 10", "y = 20")
logger.Trace("Function call", "Started processing user request")
Info, Notice, Warning

Logged to output.log

logger.Info("Application started")                    // No prefix
logger.Notice("Configuration file reloaded")          // [NOTICE] prefix
logger.Warn("Memory usage is high")                   // [WARNING] prefix
logger.WarnError(err, "Non-system-affecting error")   // [WARNING] prefix
Error, Fatal, Critical

Logged to error.log

logger.Error(err, "Retry attempt 3")         // [ERROR] prefix
logger.Fatal(err, "Unable to start service") // [FATAL] prefix
logger.Critical(err, "System crash")         // [CRITICAL] prefix

Available Functions

  • New - Create a new logger instance

    logger, err := goLogger.New(config)
    
    • Initialize log directory, ensure path exists
    • Initialize three log files: debug.log, output.log, error.log
    • Set up log handlers for each level
  • Close - Properly close the logger

    err := logger.Close()
    
    • Mark logger as closed
    • Ensure no resource leaks
  • Flush - Force write to files

    err := logger.Flush()
    
    • Write all cached log content to disk
    • Ensure logs are not lost
File Rotation Mechanism
Automatic Rotation
  • Check file size before each log write
  • Automatically rotate when exceeding MaxSize limit
  • Backup file naming format: filename.YYYYMMDD_HHMMSS
Backup Management
  • Keep the latest MaxBackup backup files
  • Automatically delete expired old backups
  • Sort by modification time, keep the newest files

License

This project is licensed under the MIT License.

Author

邱敬幃 Pardn Chiu


©️ 2025 邱敬幃 Pardn Chiu

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Log

type Log struct {
	Path      string `json:"path,omitempty"`        // 日誌檔案路徑,預設 `./logs`
	Stdout    bool   `json:"stdout,omitempty"`      // 是否輸出到標準輸出,預設 false
	MaxSize   int64  `json:"max_size,omitempty"`    // 日誌檔案最大大小(位元組),預設 16 * 1024 * 1024
	MaxBackup int    `json:"max_backups,omitempty"` // 新增:最大備份檔案數量,預設 5
	Type      string `json:"type,omitempty"`        // 日誌類型,預設 "text",可選 "json" 或 "text"
}

type Logger

type Logger struct {
	Config        *Log
	DebugHandler  *log.Logger
	OutputHandler *log.Logger
	ErrorHandler  *log.Logger
	File          map[string]*os.File
	Mutex         sync.RWMutex
	IsClose       bool
	// contains filtered or unexported fields
}

func New

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

func (*Logger) Cleanup

func (l *Logger) Cleanup(path string) error

func (*Logger) Close

func (l *Logger) Close() error

func (*Logger) Critical

func (l *Logger) Critical(err error, messages ...any) error

func (*Logger) Debug

func (l *Logger) Debug(messages ...any)

func (*Logger) Error

func (l *Logger) Error(err error, messages ...any) error

func (*Logger) Fatal

func (l *Logger) Fatal(err error, messages ...any) error

func (*Logger) Flush

func (l *Logger) Flush() error

func (*Logger) Info

func (l *Logger) Info(messages ...any)

func (*Logger) Notice

func (l *Logger) Notice(messages ...any)

func (*Logger) Trace

func (l *Logger) Trace(messages ...any)

func (*Logger) Warn

func (l *Logger) Warn(messages ...any)

func (*Logger) WarnError added in v0.2.0

func (l *Logger) WarnError(err error, messages ...any) error

Jump to

Keyboard shortcuts

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