log

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 11 Imported by: 2

README

Log

A blazingly fast and easy-to-use Golang logging package built on top of Zap. It provides structured console output with timestamp, line number, method, service name, and message.

Features

  • Blazingly Fast: Built on Zap for high performance with minimal allocations
  • Structured Output: Clean console logging with timestamp, line number, method, service name, and message
  • Easy to Use: One-line logging with package-level functions – just import and log
  • Flexible: Supports any number and type of arguments using printf-style formatting
  • Configurable: Customizable service name, log level, and output destination
  • Advanced: Custom encoder for precise output control, supports all Zap features like caller info

Installation

go get github.com/AbiXnash/log

Quick Start

Basic Console Logging
package main

import (
    "github.com/AbiXnash/log"
)

func main() {
    // Initialize the logger
    log.Init(log.Config{
        ServiceName: "myapp",
        Level:       zapcore.InfoLevel,
    })

    // Use package-level functions for easy logging
    log.LogInfo("Application started")
    log.LogInfo("User %s logged in with ID %d", "john", 123)

    // Error logging
    log.LogError("Failed to connect to database: %v", err)
}
Multi-Output Logging (Console + Daily Rotating Files)
package main

import (
    "os"
    "github.com/AbiXnash/log"
)

func main() {
    // Set environment variables for file logging
    os.Setenv("LOG_PATH", "/var/log/myapp")
    os.Setenv("LOG_PREFIX", "myapp")
    os.Setenv("LOG_FORMAT", "json")

    // Initialize the logger with console and file outputs
    log.Init(log.Config{
        ServiceName: "myapp",
        Level:       zapcore.InfoLevel,
        Format:      "console", // Console format
        // FileFormat defaults to "json" via env
    })

    log.LogInfo("Application started - logs to both console and file")
    log.LogError("This error appears in console and JSON file")
}

Configuration

config := log.Config{
    ServiceName: "myservice",           // Your service name
    Level:       zapcore.DebugLevel,    // Minimum log level
    Output:      os.Stdout,             // Output destination (optional, default stdout)
    Format:      "console",             // "console" or "json" for console output (default "console")
    File:        "app.log",             // Single log file path (optional, uses FileFormat)
    LogPath:     "/var/log/myapp",      // Directory for daily rotating logs (optional)
    LogPrefix:   "myapp",               // Prefix for log files (optional, default "log")
    FileFormat:  "json",                // "console" or "json" for file output (default "json")
}
log.Init(config)
Complete Configuration Example
// Environment variables (optional, override config)
os.Setenv("LOG_PATH", "/var/log/myapp")     // Directory for logs
os.Setenv("LOG_PREFIX", "myapp")           // Log file prefix
os.Setenv("LOG_FORMAT", "json")            // File format: "json" or "console"

// Full configuration
config := log.Config{
    ServiceName: "myapp",                   // Required: Service name in logs
    Level:       zapcore.InfoLevel,         // Required: Minimum log level
    Output:      os.Stdout,                 // Optional: Console output (default: os.Stdout)
    Format:      "console",                 // Optional: Console format "console"/"json" (default: "console")
    File:        "",                        // Optional: Single file path (overrides LogPath if set)
    LogPath:     "/var/log/myapp",          // Optional: Directory for daily rotation
    LogPrefix:   "myapp",                   // Optional: Prefix for log files (default: "log")
    FileFormat:  "json",                    // Optional: File format "console"/"json" (default: "json")
}

log.Init(config)

// Logs will appear on console in console format and in daily rotating JSON files
log.LogInfo("This is logged to console and file")
Environment Variables

You can also configure logging using environment variables:

  • LOG_PATH: Directory path for daily rotating logs
  • LOG_PREFIX: Prefix for log filenames (default "log")
  • LOG_FORMAT: Format for file logs ("console" or "json", default "json")

If set, these override the config fields. Log files are created daily with format <prefix>-YYYY-MM-DD.log.

When LOG_PATH is set, logs are written to both console (in Format) and rotating files (in LOG_FORMAT).

Usage Examples

1. Development (Console Only)
log.Init(log.Config{
    ServiceName: "devapp",
    Level:       zapcore.DebugLevel,
    Format:      "console",
})
2. Production with JSON Files
os.Setenv("LOG_PATH", "/var/log/app")
log.Init(log.Config{
    ServiceName: "prodapp",
    Level:       zapcore.InfoLevel,
    Format:      "console",  // Human-readable console
    FileFormat:  "json",     // Structured file logs
})
3. Legacy Single File
log.Init(log.Config{
    ServiceName: "legacy",
    Level:       zapcore.InfoLevel,
    File:        "/var/log/app.log",  // Single file (uses FileFormat)
})
4. Custom File Format
log.Init(log.Config{
    ServiceName: "custom",
    LogPath:     "/logs",
    LogPrefix:   "app",
    FileFormat:  "console",  // Console format in files
})

Using Logger Instance

For simple usage (panics on error):

logger := log.MustNewLogger(log.Config{
    ServiceName: "myapp",
    Level:       zapcore.InfoLevel,
})

logger.Info("This is an info message")
logger.Error("This is an error: %s", "details")

For handling errors:

logger, err := log.NewLogger(log.Config{
    ServiceName: "myapp",
    Level:       zapcore.InfoLevel,
})
if err != nil {
    // handle error
}

logger.Info("This is an info message")
logger.Error("This is an error: %s", "details")

API Reference

Package-Level Functions

These functions use a global logger initialized with Init(). They are convenient for simple applications.

  • LogDebug(msg string, args ...interface{})
  • LogInfo(msg string, args ...interface{})
  • LogWarn(msg string, args ...interface{})
  • LogError(msg string, args ...interface{})
  • LogFatal(msg string, args ...interface{})
Logger Instance Methods

For more control, create a logger instance with NewLogger() or MustNewLogger().

  • logger.Debug(msg string, args ...interface{})
  • logger.Info(msg string, args ...interface{})
  • logger.Warn(msg string, args ...interface{})
  • logger.Error(msg string, args ...interface{})
  • logger.Fatal(msg string, args ...interface{})
Configuration
type Config struct {
    ServiceName string              // Service name in logs
    Level       zapcore.Level       // Minimum log level
    Output      zapcore.WriteSyncer // Output destination (default: os.Stdout)
    Format      string              // "console" or "json" for console output (default: "console")
    File        string              // Single log file path (optional)
    LogPath     string              // Directory for daily rotating logs (optional)
    LogPrefix   string              // Prefix for log files (optional, default "log")
    FileFormat  string              // "console" or "json" for file output (default: "json")
}

Output Format

Console Format (default for console)

The console log output includes:

  • Timestamp (RFC3339)
  • Log level (INFO, ERROR, etc.)
  • Service name in brackets
  • File and line number
  • Message

Example console output:

2026-01-13T23:16:38+05:30 INFO [myapp] main.go:15 Application started
2026-01-13T23:16:38+05:30 ERROR [myapp] main.go:20 Failed to connect to database
JSON Format (default for files)

Set Format: "json" for console or FileFormat: "json" for files (default for files).

Example JSON output:

{"level":"INFO","time":"2026-01-13T23:16:38.423+0530","logger":"myapp","caller":"main.go:15","msg":"Application started"}
{"level":"ERROR","time":"2026-01-13T23:16:38.423+0530","logger":"myapp","caller":"main.go:20","msg":"Failed to connect to database"}
Multi-Output

When file logging is enabled, console uses Format and files use FileFormat, allowing different formats simultaneously.

Production Usage

Best Practices
  1. Initialize once: Call Init() or create logger instances at application startup
  2. Use appropriate levels: Use Debug for development, Info for production monitoring, Warn/Error for issues
  3. Structured file logging: Use JSON format for files (default) for better log aggregation and searching
  4. Multi-output: Use LogPath for daily rotating files with console output for development visibility
  5. Environment configuration: Use LOG_PATH, LOG_PREFIX, LOG_FORMAT for containerized deployments
  6. Caller info: Included by default; shows file and line number for easy debugging
Error Handling
  • Package-level functions silently ignore calls if logger is not initialized
  • File logging panics on file open errors (fail fast principle)
  • Directory creation for LogPath is automatic
  • All other operations are designed to never fail
Thread Safety

All logging operations are thread-safe and can be called concurrently from multiple goroutines.

Performance

This library is built on top of Uber's Zap, which is designed for high-performance logging with minimal allocations. Benchmarks show:

  • Console format: ~1.5µs per log operation
  • JSON format: ~1.1µs per log operation
  • Package-level functions: Same performance as instance methods

The custom encoder for console output adds negligible overhead while providing clean, readable logs. For maximum performance in production, use JSON format with structured logging.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Init

func Init(cfg Config)

Init initializes the global logger

func LogDebug

func LogDebug(msg string, args ...interface{})

LogDebug logs at Debug level using global logger

func LogDebugWithFields

func LogDebugWithFields(msg string, fields ...zap.Field)

LogDebugWithFields logs at Debug level with structured fields using global logger

func LogError

func LogError(msg string, args ...interface{})

LogError logs at Error level using global logger

func LogErrorWithFields

func LogErrorWithFields(msg string, fields ...zap.Field)

LogErrorWithFields logs at Error level with structured fields using global logger

func LogFatal

func LogFatal(msg string, args ...interface{})

LogFatal logs at Fatal level using global logger

func LogFatalWithFields

func LogFatalWithFields(msg string, fields ...zap.Field)

LogFatalWithFields logs at Fatal level with structured fields using global logger

func LogInfo

func LogInfo(msg string, args ...interface{})

LogInfo logs at Info level using global logger

func LogInfoWithFields

func LogInfoWithFields(msg string, fields ...zap.Field)

LogInfoWithFields logs at Info level with structured fields using global logger

func LogWarn

func LogWarn(msg string, args ...interface{})

LogWarn logs at Warn level using global logger

func LogWarnWithFields

func LogWarnWithFields(msg string, fields ...zap.Field)

LogWarnWithFields logs at Warn level with structured fields using global logger

func NewFancyEncoder

func NewFancyEncoder(cfg zapcore.EncoderConfig) zapcore.Encoder

Types

type Config

type Config struct {
	ServiceName string
	Level       zapcore.Level
	Output      zapcore.WriteSyncer // default os.Stdout
	Format      string              // "console" or "json", default "console"
	File        string              // log file path, if set, writes to file instead of Output
	LogPath     string              // directory for daily rotating logs
	LogPrefix   string              // prefix for log files (default "log")
	FileFormat  string              // "console" or "json" for file output, default "json"
}

type FancyEncoder

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

func (*FancyEncoder) AddArray

func (e *FancyEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error

func (*FancyEncoder) AddBinary

func (e *FancyEncoder) AddBinary(key string, value []byte)

func (*FancyEncoder) AddBool

func (e *FancyEncoder) AddBool(key string, value bool)

func (*FancyEncoder) AddByteString

func (e *FancyEncoder) AddByteString(key string, value []byte)

func (*FancyEncoder) AddComplex64

func (e *FancyEncoder) AddComplex64(key string, value complex64)

func (*FancyEncoder) AddComplex128

func (e *FancyEncoder) AddComplex128(key string, value complex128)

func (*FancyEncoder) AddDuration

func (e *FancyEncoder) AddDuration(key string, value time.Duration)

func (*FancyEncoder) AddFloat32

func (e *FancyEncoder) AddFloat32(key string, value float32)

func (*FancyEncoder) AddFloat64

func (e *FancyEncoder) AddFloat64(key string, value float64)

func (*FancyEncoder) AddInt

func (e *FancyEncoder) AddInt(key string, value int)

func (*FancyEncoder) AddInt8

func (e *FancyEncoder) AddInt8(key string, value int8)

func (*FancyEncoder) AddInt16

func (e *FancyEncoder) AddInt16(key string, value int16)

func (*FancyEncoder) AddInt32

func (e *FancyEncoder) AddInt32(key string, value int32)

func (*FancyEncoder) AddInt64

func (e *FancyEncoder) AddInt64(key string, value int64)

func (*FancyEncoder) AddObject

func (e *FancyEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error

func (*FancyEncoder) AddReflected

func (e *FancyEncoder) AddReflected(key string, value interface{}) error

func (*FancyEncoder) AddString

func (e *FancyEncoder) AddString(key string, value string)

func (*FancyEncoder) AddTime

func (e *FancyEncoder) AddTime(key string, value time.Time)

func (*FancyEncoder) AddUint

func (e *FancyEncoder) AddUint(key string, value uint)

func (*FancyEncoder) AddUint8

func (e *FancyEncoder) AddUint8(key string, value uint8)

func (*FancyEncoder) AddUint16

func (e *FancyEncoder) AddUint16(key string, value uint16)

func (*FancyEncoder) AddUint32

func (e *FancyEncoder) AddUint32(key string, value uint32)

func (*FancyEncoder) AddUint64

func (e *FancyEncoder) AddUint64(key string, value uint64)

func (*FancyEncoder) AddUintptr

func (e *FancyEncoder) AddUintptr(key string, value uintptr)

func (*FancyEncoder) Clone

func (e *FancyEncoder) Clone() zapcore.Encoder

func (*FancyEncoder) EncodeEntry

func (e *FancyEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error)

EncodeEntry encodes a log entry into a buffer with a custom console format. Format: timestamp LEVEL [logger] caller message fields_json

func (*FancyEncoder) OpenNamespace

func (e *FancyEncoder) OpenNamespace(key string)

type Logger

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

func MustNewLogger

func MustNewLogger(cfg Config) *Logger

MustNewLogger creates a new logger instance and panics on error

func NewLogger

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

NewLogger creates a new logger instance

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...interface{})

Debug logs at Debug level

func (*Logger) DebugWithFields

func (l *Logger) DebugWithFields(msg string, fields ...zap.Field)

DebugWithFields logs at Debug level with structured fields

func (*Logger) Error

func (l *Logger) Error(msg string, args ...interface{})

Error logs at Error level

func (*Logger) ErrorWithFields

func (l *Logger) ErrorWithFields(msg string, fields ...zap.Field)

ErrorWithFields logs at Error level with structured fields

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, args ...interface{})

Fatal logs at Fatal level

func (*Logger) FatalWithFields

func (l *Logger) FatalWithFields(msg string, fields ...zap.Field)

FatalWithFields logs at Fatal level with structured fields

func (*Logger) Info

func (l *Logger) Info(msg string, args ...interface{})

Info logs at Info level

func (*Logger) InfoWithFields

func (l *Logger) InfoWithFields(msg string, fields ...zap.Field)

InfoWithFields logs at Info level with structured fields

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...interface{})

Warn logs at Warn level

func (*Logger) WarnWithFields

func (l *Logger) WarnWithFields(msg string, fields ...zap.Field)

WarnWithFields logs at Warn level with structured fields

type RotatingFile

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

func NewRotatingFile

func NewRotatingFile(dir, prefix string) *RotatingFile

func (*RotatingFile) Sync

func (r *RotatingFile) Sync() error

func (*RotatingFile) Write

func (r *RotatingFile) Write(p []byte) (n int, err error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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