logger

package module
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

README ΒΆ

πŸ“š OTMC Logger

A simple, high-performance logging library for Go applications, designed for CLI, Desktop, API, and Server applications.

✨ Features

  • Simple API - Similar to fmt.Printf, easy to use
  • Beautiful Console Output - Automatic formatting with colors and alignment
  • File Logging - With automatic rotation support
  • Multiple Formatters - Pretty (default), Text, and JSON
  • Log Levels - TRACE, DEBUG, INFO, WARN, ERROR, CRIT
  • Caller Information - Automatically captures function, file, and line number
  • Runtime Configuration - Change settings at runtime without restart
  • Multiple Logger Instances - Create independent loggers with different configs
  • Thread-Safe - Safe for concurrent use
  • Production Ready - Default configuration optimized for production

πŸ“¦ Installation

go get github.com/otmc-sw/logger@latest

πŸš€ Quick Start

package main

import (
    "github.com/otmc-sw/logger"
)

func main() {
    err := "OTMC Testing Message"

	logger.Trace("πŸš€ Starting application...")
	logger.Debug("πŸ“ Configuration loaded from %s", "config.yaml")
	logger.Info("🌐 Server listening on %s:%d", "localhost", 8080)
	logger.Warn("⚠️ Memory usage is high: %.1f%%", 85.5)
	logger.Error("❌ Failed to connect to database: %s", "postgres")
    // Warning: This will close the application.
	logger.Crit("❌ Unable to initialize application: %v", err)
}

πŸ–₯️ Console Output

The logger automatically formats output with timestamps, caller information, and colors:

2026-07-06 08:57:34.208 +07:00     Initializer()      main.go:104   | INFO  | βœ… Database connection established.
2026-07-06 08:57:34.208 +07:00     Initializer()      main.go:106   | INFO  | 🧩 Loading settings...
2026-07-06 08:57:34.209 +07:00     Initializer()      main.go:112   | INFO  | πŸ€– LLM Provider: groq
2026-07-06 08:57:34.209 +07:00     Initializer()      main.go:119   | INFO  | βœ… LLM client initialized.
2026-07-06 08:57:34.209 +07:00     Initializer()      main.go:149   | INFO  | πŸ“ Run directory: D:\SCM\GitHub\OTMC\Softwares\document-hub\backend
2026-07-06 08:57:34.209 +07:00     Initializer()      main.go:150   | INFO  | πŸ“¦ Frontend dist: D:\SCM\GitHub\OTMC\Softwares\document-hub\frontend\dist
2026-07-06 08:57:34.209 +07:00          Runner()      main.go:154   | INFO  | 🌿 Running application ...
2026-07-06 08:57:34.209 +07:00          Runner()      main.go:157   | INFO  | 🌐 Registering APIs ...
2026-07-06 08:57:34.210 +07:00           Start() scheduler.go:57    | INFO  | βœ… Backup scheduler engine started
2026-07-06 08:57:34.210 +07:00          reload() scheduler.go:142   | INFO  | πŸ”€ Backup scheduled with cron expression: 0 2 * * * (max backups: 10)

βš™οΈ Configuration

πŸ› οΈ Creating a Logger
// With no options β€” uses default config (console, InfoLevel, caller on)
log := logger.New()

// With one or more options
log := logger.New(
    logger.WithLevel(logger.DebugLevel),
    logger.WithConsole(),
    logger.WithFile("logs/app.log"),
    logger.WithJSON(),
    logger.WithCaller(false),
    logger.WithMaxSize(20),
    logger.WithMaxBackups(3),
    logger.WithMaxAge(30),
    logger.WithCompress(true),
    logger.WithTimeFormat(time.RFC3339),
)
πŸ”„ Runtime Configuration

The logger supports runtime configuration changes. Most changes can be done through Configure() or dedicated methods:

Configure (batch update)

Apply one or more options at once. This is the recommended way to change settings that affect the formatter or writer (JSON toggle, file path, etc.).

log.Configure(
    logger.WithJSON(),
    logger.WithFile("logs/app.log"),
    logger.WithCaller(false),
)

// Global
logger.Configure(
    logger.WithLevel(logger.DebugLevel),
    logger.WithJSON(),
)
SetLevel (single update β€” no rebuild)

Changing the log level is the most frequent operation and does not require recreating the logger internals.

log.SetLevel(logger.DebugLevel)

// Global
logger.SetLevel(logger.WarnLevel)
Config / Update (round-trip)

Get a copy of the current config, modify it, and apply it back.

cfg := log.Config()
cfg.Level = logger.DebugLevel
cfg.JSON = true
cfg.Filename = "logs/app.log"
log.Update(cfg)

// Global
cfg := logger.GetConfig()
cfg.Console = true
logger.Update(cfg)
Available Options
Option Default Description
WithLevel(level) InfoLevel Minimum log level
WithConsole(enabled) true Enable/disable console output
WithFile(filename) "" Enable file output with rotation
WithJSON(enabled) false JSON format instead of pretty
WithCaller(enabled) true Include caller info (file:line)
WithStacktrace(enabled) false Include stack trace on errors
WithMaxSize(mb) 10 Max file size before rotation (MB)
WithMaxBackups(n) 3 Max rotated files to keep
WithMaxAge(days) 90 Max age of rotated files (days)
WithCompress(enabled) true Compress rotated files
WithTimeFormat(format) "2006-01-02 15:04:05.000 -07:00" Time format string

πŸ“Š Log Levels

logger.Trace("Detailed trace information")
logger.Debug("Debug information")
logger.Info("General informational messages")
logger.Warn("Warning messages")
logger.Error("Error messages")
logger.Crit("Critical errors β€” exits after logging")

🎨 Formatters

🎯 Pretty Formatter (Default)
log := logger.New(
    logger.WithConsole(),
)

Output:

2026-07-06 08:57:34.208 +07:00     Initializer()      main.go:106   | INFO  | 🧩 Loading settings...
2026-07-06 08:57:34.209 +07:00          Runner()      main.go:154   | INFO  | 🌿 Running application ...
πŸ“‹ JSON Formatter
log := logger.New(
    logger.WithJSON(),
    logger.WithConsole(),
)

Output:

{
  "time": "2026-07-04T08:49:40.404+07:00",
  "level": "INFO",
  "message": "Application started",
  "function": "main",
  "file": "main.go",
  "line": 20
}

🌍 Global Logger

The library provides a global logger instance that mirrors the instance API:

// Logging
logger.Trace("...")
logger.Debug("...")
logger.Info("...")
logger.Warn("...")
logger.Error("...")
logger.Crit("...")

// Request logging
logger.Request("GET", "/api/users", 200, 150*time.Millisecond, "10.0.0.1")

// Configuration
logger.SetLevel(logger.DebugLevel)
logger.Configure(logger.WithJSON(), logger.WithFile("app.log"))
logger.Update(cfg)
cfg := logger.GetConfig()

πŸ”§ Custom Logger Instances

Create independent logger instances with different configurations:

// Console logger β€” debug level, pretty format
consoleLog := logger.New(
    logger.WithConsole(),
    logger.WithLevel(logger.DebugLevel),
)
consoleLog.Info("This is a console log")
consoleLog.SetLevel(logger.TraceLevel)

// File logger β€” info level, rotated files
fileLog := logger.New(
    logger.WithFile("logs/app.log"),
    logger.WithLevel(logger.InfoLevel),
    logger.WithMaxSize(20),
)
fileLog.Info("This is a file log")

// JSON logger β€” for structured monitoring
jsonLog := logger.New(
    logger.WithFile("logs/metrics.json"),
    logger.WithJSON(),
    logger.WithCaller(false),
)
jsonLog.Info("This is a JSON log for metrics")

// Change settings at runtime
jsonLog.Configure(logger.WithCaller(true))

♻️ Log Rotation

Automatic log rotation using the built-in rotator package:

log := logger.New(
    logger.WithFile("logs/app.log"),
    logger.WithMaxSize(20),    // 20 MB per file
    logger.WithMaxBackups(3),  // keep 3 rotated files
    logger.WithMaxAge(30),     // keep for 30 days
    logger.WithCompress(true), // compress rotated files
)

The rotator package is lightweight, dependency-free, and supports:

  • Configurable naming strategies (index, date, timestamp, or custom)
  • Gzip compression
  • Automatic cleanup by count and age
  • Thread-safe concurrent writes

For advanced usage, see the rotator package documentation.

🎨 Color Output

Colors are automatically applied to console output:

  • TRACE - Gray
  • DEBUG - Cyan
  • INFO - Blue
  • WARN - Yellow
  • ERROR - Red
  • CRIT - Bright Red

Colors are automatically stripped when writing to files.

πŸ—οΈ Architecture

Application
    ↓
Logger API (Trace, Debug, Info, Warn, Error, Crit, Request)
    ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Logger struct                       β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚   β”‚ Config  β”‚  β”‚ Core             β”‚ β”‚
β”‚   β”‚ Level   β”‚  β”‚   β†’ Formatter    β”‚ β”‚
β”‚   β”‚ JSON    β”‚  β”‚   β†’ Writer       β”‚ β”‚
β”‚   β”‚ Console β”‚  β”‚   β†’ Hooks        β”‚ β”‚
β”‚   β”‚ File    β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚   β”‚ Caller  β”‚                       β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                       β”‚
β”‚                                     β”‚
β”‚   Configure()  SetLevel()           β”‚
β”‚   Config()     Update()             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
    ↓
β”œβ”€β”€ Formatter (Pretty, Text, JSON)
β”œβ”€β”€ Writer (Console, File, Multi)
└── Hooks (Webhook, Discord, Slack, etc.)

πŸ“„ License

  • Apache License 2.0
  • Copyright (c) 2026 OTMC Softwares.

✨ Contributors

  • 🌿 Nguyen Van Trung
  • 🌿 Nguyen Thi Hoai
  • 🌿 OTMC Contributors

Documentation ΒΆ

Overview ΒΆ

*

  • @License Apache License 2.0
  • @Copyright (c) 2026 OTMC Softwares. OTMC Golang Logger.
  • @Contributors Nguyen Van Trung, Nguyen Thi Hoai, OTMC Contributors.

*

*

  • @License Apache License 2.0
  • @Copyright (c) 2026 OTMC Softwares. OTMC Golang Logger.
  • @Contributors Nguyen Van Trung, Nguyen Thi Hoai, OTMC Contributors. *

*

  • @License Apache License 2.0
  • @Copyright (c) 2026 OTMC Softwares. OTMC Golang Logger.
  • @Contributors Nguyen Van Trung, Nguyen Thi Hoai, OTMC Contributors.

*

Index ΒΆ

Constants ΒΆ

View Source
const (
	TraceLevel = core.TraceLevel
	DebugLevel = core.DebugLevel
	InfoLevel  = core.InfoLevel
	WarnLevel  = core.WarnLevel
	ErrorLevel = core.ErrorLevel
	CritLevel  = core.CritLevel
)

Variables ΒΆ

This section is empty.

Functions ΒΆ

func AddListener ΒΆ added in v0.1.8

func AddListener() chan LogEntry

func Close ΒΆ added in v0.1.7

func Close() error

func Configure ΒΆ added in v0.1.4

func Configure(opts ...Option)

func Crit ΒΆ added in v0.1.1

func Crit(format string, args ...any)

func Debug ΒΆ

func Debug(format string, args ...any)

func Error ΒΆ

func Error(format string, args ...any)

func Info ΒΆ

func Info(format string, args ...any)

func Metadata ΒΆ added in v0.1.11

func Metadata(metadata interface{}, level Level, format string, args ...any)

func RemoveListener ΒΆ added in v0.1.8

func RemoveListener(ch chan LogEntry)

func Request ΒΆ added in v0.1.3

func Request(method, path string, statusCode int, latency time.Duration, clientIP string)

func SetLevel ΒΆ

func SetLevel(level Level)

func Sync ΒΆ

func Sync() error

func Trace ΒΆ

func Trace(format string, args ...any)

func Update ΒΆ added in v0.1.4

func Update(cfg Config)

func Warn ΒΆ

func Warn(format string, args ...any)

Types ΒΆ

type Config ΒΆ

type Config struct {
	Level         Level
	Console       bool
	File          bool
	Filename      string
	JSON          bool
	Caller        bool
	Stacktrace    bool
	MaxSize       float64
	MaxBackups    int
	MaxAge        int
	Compress      bool
	TimeFormat    string
	MaxLogEntries int
}

func DefaultConfig ΒΆ

func DefaultConfig() Config

func GetConfig ΒΆ added in v0.1.4

func GetConfig() Config

type Formatter ΒΆ

type Formatter = core.Formatter

type Hook ΒΆ

type Hook = core.Hook

type Level ΒΆ

type Level = core.Level

func ParseLevel ΒΆ

func ParseLevel(level string) Level

type LogEntry ΒΆ added in v0.1.8

type LogEntry = core.Entry

func GetRecentLogs ΒΆ added in v0.1.8

func GetRecentLogs(limit int) []LogEntry

type Logger ΒΆ

type Logger struct {
	// contains filtered or unexported fields
}

func New ΒΆ

func New(opts ...Option) *Logger

func (*Logger) AddListener ΒΆ added in v0.1.8

func (l *Logger) AddListener() chan LogEntry

func (*Logger) Close ΒΆ added in v0.1.7

func (l *Logger) Close() error

func (*Logger) Config ΒΆ added in v0.1.4

func (l *Logger) Config() Config

func (*Logger) Configure ΒΆ added in v0.1.4

func (l *Logger) Configure(opts ...Option)

func (*Logger) Crit ΒΆ added in v0.1.1

func (l *Logger) Crit(format string, args ...any)

func (*Logger) Debug ΒΆ

func (l *Logger) Debug(format string, args ...any)

func (*Logger) Error ΒΆ

func (l *Logger) Error(format string, args ...any)

func (*Logger) GetRecentLogs ΒΆ added in v0.1.8

func (l *Logger) GetRecentLogs(limit int) []LogEntry

func (*Logger) Info ΒΆ

func (l *Logger) Info(format string, args ...any)

func (*Logger) Metadata ΒΆ added in v0.1.11

func (l *Logger) Metadata(metadata interface{}, level Level, format string, args ...any)

func (*Logger) RemoveListener ΒΆ added in v0.1.8

func (l *Logger) RemoveListener(ch chan LogEntry)

func (*Logger) Request ΒΆ added in v0.1.3

func (l *Logger) Request(method, path string, statusCode int, latency time.Duration, clientIP string)

func (*Logger) SetLevel ΒΆ added in v0.1.4

func (l *Logger) SetLevel(level Level)

func (*Logger) Sync ΒΆ

func (l *Logger) Sync() error

func (*Logger) Trace ΒΆ

func (l *Logger) Trace(format string, args ...any)

func (*Logger) Update ΒΆ added in v0.1.4

func (l *Logger) Update(cfg Config)

func (*Logger) Warn ΒΆ

func (l *Logger) Warn(format string, args ...any)

type Option ΒΆ

type Option func(*Config)

func WithCaller ΒΆ

func WithCaller(enabled bool) Option

func WithCompress ΒΆ

func WithCompress(enabled bool) Option

func WithConsole ΒΆ

func WithConsole(enabled bool) Option

func WithFile ΒΆ

func WithFile(filename string) Option

func WithJSON ΒΆ

func WithJSON(enabled bool) Option

func WithLevel ΒΆ

func WithLevel(level Level) Option

func WithMaxAge ΒΆ

func WithMaxAge(maxAge int) Option

func WithMaxBackups ΒΆ

func WithMaxBackups(maxBackups int) Option

func WithMaxLogEntries ΒΆ added in v0.1.8

func WithMaxLogEntries(maxEntries int) Option

func WithMaxSize ΒΆ

func WithMaxSize(maxSize float64) Option

func WithStacktrace ΒΆ

func WithStacktrace(enabled bool) Option

func WithTimeFormat ΒΆ added in v0.1.4

func WithTimeFormat(format string) Option

Directories ΒΆ

Path Synopsis
*
*
*
*
*
tests
printer command
*
*
rotator command
*
*
*
*

Jump to

Keyboard shortcuts

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