logger

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2026 License: AGPL-3.0 Imports: 4 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Logger Package

Structured logging infrastructure for legible using uber-go/zap.

Features

  • Multiple Log Levels: debug, info, warn, error
  • Flexible Output: Console (human-readable) or JSON (machine-parseable)
  • File Output: Optional file logging for daemon mode
  • Structured Logging: Context-aware fields (document_id, operation, duration, error)
  • High Performance: Built on zap for zero-allocation logging in hot paths
  • Global Logger: Package-level convenience functions

Basic Usage

Initialize Logger
import "github.com/platinummonkey/legible/internal/logger"

// Initialize with config
cfg := &logger.Config{
    Level:  "info",
    Format: "console",
}
if err := logger.Init(cfg); err != nil {
    log.Fatal(err)
}
defer logger.Sync()
Simple Logging
import "github.com/platinummonkey/legible/internal/logger"

// Package-level functions use the global logger
logger.Info("Starting sync operation")
logger.Infof("Processing %d documents", count)
logger.Warn("No documents found")
logger.Error("Failed to connect")
Structured Logging
// Add contextual fields
logger.WithFields(
    "document_id", "abc-123",
    "operation", "sync",
    "duration_ms", 250,
).Info("Document synced successfully")

// Convenience methods
logger.WithDocumentID("abc-123").Info("Processing document")
logger.WithOperation("ocr").Info("Starting OCR")
logger.WithError(err).Error("Operation failed")
Instance Logger
// Create a custom logger instance
cfg := &logger.Config{
    Level:      "debug",
    Format:     "json",
    OutputPath: "/var/log/legible.log",
}
log, err := logger.New(cfg)
if err != nil {
    return err
}
defer log.Sync()

log.Debug("Debug information")
log.Info("Information message")

Configuration

type Config struct {
    // Level is the minimum log level (debug, info, warn, error)
    Level string

    // Format is "console" (human-readable) or "json" (machine-parseable)
    Format string

    // OutputPath is the file path for log output (empty = stdout only)
    OutputPath string

    // EnableCaller adds caller information to log entries
    EnableCaller bool

    // EnableStacktrace adds stack traces to error-level logs
    EnableStacktrace bool
}

Examples

Development Mode (Console)
cfg := &logger.Config{
    Level:  "debug",
    Format: "console",
}
logger.Init(cfg)

logger.Debug("Detailed debug information")
// Output: 2025-12-30T09:59:17.940-0600  DEBUG  Detailed debug information
Production Mode (JSON)
cfg := &logger.Config{
    Level:  "info",
    Format: "json",
    OutputPath: "/var/log/app.log",
}
logger.Init(cfg)

logger.WithFields("user_id", 123).Info("User logged in")
// Output: {"level":"info","ts":1767110357.929,"msg":"User logged in","user_id":123}
Context-Aware Logging
// Create a logger with document context
docLogger := logger.WithDocumentID("doc-abc-123")

// All subsequent logs include the document_id
docLogger.Info("Starting download")
docLogger.WithOperation("convert").Info("Converting to PDF")
docLogger.WithFields("size_bytes", 1024).Info("Download complete")

// Output (JSON format):
// {"level":"info","ts":...,"msg":"Starting download","document_id":"doc-abc-123"}
// {"level":"info","ts":...,"msg":"Converting to PDF","document_id":"doc-abc-123","operation":"convert"}
// {"level":"info","ts":...,"msg":"Download complete","document_id":"doc-abc-123","size_bytes":1024}
Error Logging
if err := processDocument(doc); err != nil {
    logger.WithError(err).
        WithDocumentID(doc.ID).
        Error("Failed to process document")
}

// Output (JSON):
// {"level":"error","ts":...,"msg":"Failed to process document","document_id":"doc-123","error":"connection timeout"}

Integration with Config Package

import (
    "github.com/platinummonkey/legible/internal/config"
    "github.com/platinummonkey/legible/internal/logger"
)

// Load application config
cfg, err := config.Load("")
if err != nil {
    log.Fatal(err)
}

// Initialize logger from config
logCfg := &logger.Config{
    Level:  cfg.LogLevel,
    Format: "console",
}
if cfg.DaemonMode {
    logCfg.Format = "json"
    logCfg.OutputPath = "/var/log/legible.log"
}

if err := logger.Init(logCfg); err != nil {
    log.Fatal(err)
}
defer logger.Sync()

Testing

Run tests:

make test

The logger package has 92.4% test coverage with comprehensive tests for:

  • Log level filtering
  • Console and JSON output formats
  • File output
  • Structured fields
  • Global and instance loggers
  • Error handling

Documentation

Overview

Package logger provides structured logging functionality using zap.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug(args ...interface{})

Debug logs a debug message

func Debugf

func Debugf(template string, args ...interface{})

Debugf logs a formatted debug message

func Error

func Error(args ...interface{})

Error logs an error message

func Errorf

func Errorf(template string, args ...interface{})

Errorf logs a formatted error message

func Fatal

func Fatal(args ...interface{})

Fatal logs a fatal message and exits

func Fatalf

func Fatalf(template string, args ...interface{})

Fatalf logs a formatted fatal message and exits

func Info

func Info(args ...interface{})

Info logs an info message

func Infof

func Infof(template string, args ...interface{})

Infof logs a formatted info message

func Init

func Init(cfg *Config) error

Init initializes the global logger instance

func Sync

func Sync() error

Sync flushes any buffered log entries

func Warn

func Warn(args ...interface{})

Warn logs a warning message

func Warnf

func Warnf(template string, args ...interface{})

Warnf logs a formatted warning message

Types

type Config

type Config struct {
	// Level is the minimum log level to output (debug, info, warn, error)
	Level string

	// Format determines output format: "console" (human-readable) or "json" (machine-parseable)
	Format string

	// OutputPath is the file path for log output (empty = stdout only)
	OutputPath string

	// EnableCaller adds caller information to log entries
	EnableCaller bool

	// EnableStacktrace adds stack traces to error-level logs
	EnableStacktrace bool
}

Config holds logger configuration options

type Logger

type Logger struct {
	*zap.SugaredLogger
	// contains filtered or unexported fields
}

Logger wraps zap.SugaredLogger to provide structured logging throughout the application

func Get

func Get() *Logger

Get returns the global logger instance

func New

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

New creates a new logger instance with the provided configuration

func WithDocumentID

func WithDocumentID(docID string) *Logger

WithDocumentID returns a logger with document_id field attached

func WithError

func WithError(err error) *Logger

WithError returns a logger with error field attached

func WithFields

func WithFields(fields ...interface{}) *Logger

WithFields returns a logger with the specified fields attached

func WithOperation

func WithOperation(operation string) *Logger

WithOperation returns a logger with operation field attached

func (*Logger) Sync

func (l *Logger) Sync() error

Sync flushes any buffered log entries

func (*Logger) WithDocumentID

func (l *Logger) WithDocumentID(docID string) *Logger

WithDocumentID returns a logger with document_id field attached

func (*Logger) WithError

func (l *Logger) WithError(err error) *Logger

WithError returns a logger with error field attached

func (*Logger) WithFields

func (l *Logger) WithFields(fields ...interface{}) *Logger

WithFields returns a logger with the specified fields attached for structured logging

func (*Logger) WithOperation

func (l *Logger) WithOperation(operation string) *Logger

WithOperation returns a logger with operation field attached

Jump to

Keyboard shortcuts

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