titanlog

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2025 License: MIT Imports: 6 Imported by: 0

README

TitanLog

TitanLog is a high-performance, thread-safe, structured logging library for Go. It provides a simple and idiomatic API for leveled logging with support for context-aware fields and pluggable output formatters (JSON, Text).

TitanLog is designed to be minimal, dependency-free, and safe for concurrent use in modern Go applications and pipelines.


Features

  • Leveled Logging Granular control with Debug, Info, Warn, Error, and Fatal levels.

  • Structured Data Attach key-value pairs (Fields) to logs for machine-readable context.

  • Thread-Safe Built-in concurrency safety using mutexes, making it safe across multiple goroutines.

  • Immutable Context WithFields creates a shallow copy of the logger, ensuring parent loggers remain unchanged.

  • Pluggable Formatters Switch between human-readable text and JSON format at runtime.

  • Zero Dependencies Built entirely using the Go standard library.


Installation

go get github.com/abir-anhad/titanlog

Usage

Basic Logging

Initialize the logger with a threshold level and an output destination.

package main

import (
    "os"
    "github.com/abir-anhad/titanlog"
)

func main() {
    // Only logs at InfoLevel or higher will be printed
    log := titanlog.New(titanlog.InfoLevel, os.Stdout)

    log.Info("Service started")
    log.Warn("Config file missing, using defaults")

    // Ignored because the threshold is Info
    log.Debug("Debugging connection...")
}

Structured Logging (Context)

Use WithFields to attach structured context to logs. This is especially useful for tracing requests in production.

func processRequest(reqID string) {
    log := titanlog.New(titanlog.InfoLevel, os.Stdout)

    // Create a context-specific logger
    reqLog := log.WithFields(titanlog.Fields{
        "request_id": reqID,
        "ip":         "192.168.1.50",
    })

    reqLog.Info("Processing payment")
    reqLog.Error("Payment gateway timeout")
}

Example Output (Text Formatter):

2025-12-15T10:00:00Z INFO  request_id=123 ip=192.168.1.50 message="Processing payment"
2025-12-15T10:00:05Z ERROR request_id=123 ip=192.168.1.50 message="Payment gateway timeout"

JSON Formatting

For production environments such as AWS CloudWatch, Datadog, or ELK Stack, use JSON formatting.

func main() {
    log := titanlog.New(titanlog.InfoLevel, os.Stdout)

    // Switch to JSON formatter
    log.SetFormatter(&titanlog.JSONFormatter{})

    log.WithFields(titanlog.Fields{
        "user": "admin",
        "id":   55,
    }).Info("User logged in")
}

Output:

{
  "level": "INFO",
  "msg": "User logged in",
  "time": "2025-12-15T10:00:00Z",
  "user": "admin",
  "id": 55
}

Concurrency Safety

TitanLog is safe for concurrent use. A single logger instance can be shared across multiple goroutines.

func main() {
    log := titanlog.New(titanlog.InfoLevel, os.Stdout)

    for i := 0; i < 10; i++ {
        go func(id int) {
            log.WithFields(titanlog.Fields{
                "worker_id": id,
            }).Info("Worker started")
        }(i)
    }
}

Design Philosophy

  • Simple, explicit API
  • No hidden global state
  • Immutable logger context
  • Safe defaults for production
  • Idiomatic Go patterns

Contributing

Contributions are welcome.

  • Fork the repository
  • Create a feature branch
  • Open a pull request

For major changes, please open an issue first to discuss your proposal.


License

MIT License


Documentation

Overview

Package titanlog provides a simple, leveled structured logging system. It supports log levels, custom outputs, and structured fields.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Fields

type Fields map[string]interface{}

Fields is a type alias for a map of key-value pairs used in structured logging. Keys should be strings, and values can be of any type.

type Formatter added in v0.1.2

type Formatter interface {
	Format(level Level, msg string, fields Fields) ([]byte, error)
}

Formatter defines the interface that all log formatters must implement.

type JSONFormatter added in v0.1.2

type JSONFormatter struct{}

JSONFormatter formats logs as a JSON object.

func (*JSONFormatter) Format added in v0.1.2

func (f *JSONFormatter) Format(level Level, msg string, fields Fields) ([]byte, error)

type Level

type Level int

Level represents the severity of a log message. Higher values indicate more severe events.

const (
	// DebugLevel is for verbose output, useful for developers.
	DebugLevel Level = iota
	// InfoLevel is for standard operational messages.
	InfoLevel
	// WarnLevel is for non-critical issues that should be looked at.
	WarnLevel
	// ErrorLevel is for runtime errors that require attention.
	ErrorLevel
	// FatalLevel is for severe errors that may cause the application to crash.
	FatalLevel
)

func (Level) String

func (l Level) String() string

String returns the string representation of the Level (e.g., "INFO").

type Logger

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

Logger is the main struct that holds the configuration for logging. It is safe for concurrent use.

func New

func New(threshold Level, output io.Writer) *Logger

New creates a new Logger instance. The threshold determines the minimum log level to output (e.g., if set to InfoLevel, DebugLevel logs are ignored). The output parameter specifies where logs should be written (e.g., os.Stdout or a file).

func (*Logger) Debug

func (l *Logger) Debug(message string)

Debug logs a message at DebugLevel. These are typically used for verbose output during development.

func (*Logger) Error

func (l *Logger) Error(message string)

Error logs a message at ErrorLevel. These indicate runtime errors that require attention.

func (*Logger) Fatal

func (l *Logger) Fatal(message string)

Fatal logs a message at FatalLevel. These indicate severe errors that may cause the application to crash or become unusable.

func (*Logger) Info

func (l *Logger) Info(message string)

Info logs a message at InfoLevel. These are used for standard operational events.

func (*Logger) SetFormatter added in v0.1.2

func (l *Logger) SetFormatter(f Formatter)

SetFormatter allows changing the logging format (e.g., JSON or Text) at runtime.

func (*Logger) Warn

func (l *Logger) Warn(message string)

Warn logs a message at WarnLevel. These indicate non-critical issues that should be reviewed.

func (*Logger) WithFields

func (l *Logger) WithFields(f Fields) *Logger

WithFields creates a new Logger instance with the provided fields added to the existing context.

This method returns a copy of the logger; the original logger is not modified. This allows for creating context-specific loggers (e.g., per-request or per-user) without affecting the global logger.

type TextFormatter added in v0.1.2

type TextFormatter struct{}

TextFormatter formats logs as "TIME LEVEL key=value msg"

func (*TextFormatter) Format added in v0.1.2

func (f *TextFormatter) Format(level Level, msg string, fields Fields) ([]byte, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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