logger

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2026 License: Apache-2.0 Imports: 2 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
  • Thread-Safe - Safe for concurrent use
  • Production Ready - Default configuration optimized for production

Installation

go get github.com/otmc-sw/logger

Quick Start

package main

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

func main() {
    logger.Init(logger.Config{
        Level:    logger.InfoLevel,
        Console:  true,
        File:     true,
        Filename: "logs/app.log",
        Caller:   true,
    })

	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")
	logger.Crit("❌ Unable to initialize application: %v", err)
}

Console Output

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

2026-07-04 15:49:40.404 +07:00                 Info()       global.go:20    | INFO  | ✅ Application started
2026-07-04 15:49:40.404 +07:00                 Info()       global.go:20    | INFO  | 🌐 Server listening on localhost:8080
2026-07-04 15:49:40.405 +07:00                 Warn()       global.go:25    | WARN  | ⚠️ Memory usage is high 85.5

Configuration

Using Config
logger.Init(logger.Config{
    Level:      logger.DebugLevel,
    Console:    true,
    File:       true,
    Filename:   "logs/app.log",
    JSON:       false,
    Caller:     true,
    MaxSize:    100,    // MB
    MaxBackups: 3,
    MaxAge:     30,     // days
    Compress:   true,
})
Using Functional Options
log := logger.New(
    logger.WithLevel(logger.DebugLevel),
    logger.WithConsole(),
    logger.WithFile("logs/app.log"),
    logger.WithJSON(),
    logger.WithCaller(true),
    logger.WithMaxSize(100),
    logger.WithMaxBackups(3),
    logger.WithMaxAge(30),
    logger.WithCompress(true),
)

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-04 15:49:40.404 +07:00                 Info()       main.go:20    | INFO  | Application started
Text Formatter
log := logger.New(
    logger.WithConsole(),
)
// Use TextFormatter by setting it on the core
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 for convenience:

// Use global functions
logger.Info("Message")
logger.Error("Error: %v", err)

// Configure global logger
logger.Init(logger.Config{
    Level: logger.DebugLevel,
})

// Set log level
logger.SetLevel(logger.WarnLevel)

Custom Logger

Create multiple logger instances with different configurations:

// Console logger
consoleLog := logger.New(
    logger.WithConsole(),
    logger.WithLevel(logger.DebugLevel),
)

// File logger
fileLog := logger.New(
    logger.WithFile("logs/app.log"),
    logger.WithLevel(logger.InfoLevel),
)

// JSON logger for monitoring
jsonLog := logger.New(
    logger.WithFile("logs/metrics.log"),
    logger.WithJSON(),
)

Log Rotation

Automatic log rotation using lumberjack:

logger.Init(logger.Config{
    File:       true,
    Filename:   "logs/app.log",
    MaxSize:    100,    // Max size in MB
    MaxBackups: 3,      // Max number of old log files
    MaxAge:     30,     // Max age in days
    Compress:   true,   // Compress rotated files
})

Color Output

Colors are automatically applied to console output:

  • TRACE - Gray
  • DEBUG - Blue
  • INFO - Green
  • 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)
    ↓
Core Engine
    ↓
├── 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.

*

*

  • @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.

*

*

  • @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 = internal.TraceLevel
	DebugLevel = internal.DebugLevel
	InfoLevel  = internal.InfoLevel
	WarnLevel  = internal.WarnLevel
	ErrorLevel = internal.ErrorLevel
	CritLevel  = internal.CritLevel
)

Variables

This section is empty.

Functions

func Crit added in v0.1.1

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

Crit logs a critical message using the global logger and exits

func Debug

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

Debug logs a debug message using the global logger

func Error

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

Error logs an error message using the global logger

func Info

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

Info logs an info message using the global logger

func Init

func Init(config Config)

Init initializes the global logger

func SetLevel

func SetLevel(level Level)

SetLevel sets the log level of the global logger

func Sync

func Sync() error

Sync flushes the global logger

func Trace

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

Trace logs a trace message using the global logger

func Warn

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

Warn logs a warning message using the global logger

Types

type Config

type Config struct {
	// Level is the minimum log level to output
	Level Level

	// Console enables console output
	Console bool

	// File enables file output
	File bool

	// Filename is the path to the log file
	Filename string

	// JSON enables JSON formatting
	JSON bool

	// Caller enables caller information (function, file, line)
	Caller bool

	// Stacktrace enables stacktrace for errors
	Stacktrace bool

	// MaxSize is the maximum size in megabytes of a log file before it gets rotated
	MaxSize int

	// MaxBackups is the maximum number of old log files to retain
	MaxBackups int

	// MaxAge is the maximum number of days to retain old log files
	MaxAge int

	// Compress determines if the rotated log files should be compressed using gzip
	Compress bool
}

Config represents the logger configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration

type Field

type Field struct {
	Key   string
	Value any
}

Field represents a structured logging field

func Any

func Any(key string, value any) Field

Any creates a field with any type

func Bool

func Bool(key string, value bool) Field

Bool creates a bool field

func Err

func Err(err error) Field

Err creates an error field

func Float64

func Float64(key string, value float64) Field

Float64 creates a float64 field

func Int

func Int(key string, value int) Field

Int creates an int field

func Int64

func Int64(key string, value int64) Field

Int64 creates an int64 field

func String

func String(key, value string) Field

String creates a string field

type Formatter

type Formatter = internal.Formatter

Formatter is the interface for formatting log entries

type Hook

type Hook = internal.Hook

Hook is the interface for log hooks

type Level

type Level = internal.Level

Level is the log level type

func ParseLevel

func ParseLevel(level string) Level

ParseLevel parses a string level and returns the Level constant

type Logger

type Logger interface {
	Trace(format string, args ...any)
	Debug(format string, args ...any)
	Info(format string, args ...any)
	Warn(format string, args ...any)
	Error(format string, args ...any)
	Crit(format string, args ...any)
	Sync() error
}

Logger is the public logging interface

func New

func New(opts ...Option) Logger

New creates a new logger with the given options

type Option

type Option func(*Config)

Option is a function that configures the logger

func WithCaller

func WithCaller(enabled bool) Option

WithCaller enables or disables caller information

func WithCompress

func WithCompress(enabled bool) Option

WithCompress enables or disables compression of rotated log files

func WithConsole

func WithConsole(enabled bool) Option

WithConsole enables or disables console output

func WithFile

func WithFile(filename string) Option

WithFile enables file output with the specified filename

func WithJSON

func WithJSON(enabled bool) Option

WithJSON enables JSON formatting

func WithLevel

func WithLevel(level Level) Option

WithLevel sets the log level

func WithMaxAge

func WithMaxAge(maxAge int) Option

WithMaxAge sets the maximum number of days to retain old log files

func WithMaxBackups

func WithMaxBackups(maxBackups int) Option

WithMaxBackups sets the maximum number of old log files to retain

func WithMaxSize

func WithMaxSize(maxSize int) Option

WithMaxSize sets the maximum size in megabytes before rotation

func WithStacktrace

func WithStacktrace(enabled bool) Option

WithStacktrace enables or disables stacktrace for errors

Directories

Path Synopsis
*
*
*
* * @License Apache License 2.0 * @Copyright (c) 2026 OTMC Softwares.
* * @License Apache License 2.0 * @Copyright (c) 2026 OTMC Softwares.
*
*

Jump to

Keyboard shortcuts

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