log

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2025 License: BSD-3-Clause Imports: 10 Imported by: 4

README

Log

A high-performance, structured logging package for Go applications, built on top of zap with additional features and simplified interface.

Features

  • Multiple log levels (Debug, Info, Warn, Error, Panic, Fatal)
  • Structured logging with key-value pairs
  • Printf-style logging with format strings
  • Println-style logging support
  • Flexible output formats (JSON and console)
  • Configurable time layout
  • Log file rotation by date
  • Separate error log files
  • Optional caller information and stack traces
  • Built on top of uber-go/zap for high performance

Installation

go get github.com/kydenul/log

Quick Start

package main

import "github.com/kydenul/log"

func main() {
    // Use default logger
    log.Info("Hello, World!")
    
    // With formatting
    log.Infof("Processing item %d", 123)
}

Requirements

  • Go 1.23.4 or higher
  • Dependencies:
    • go.uber.org/zap
    • gopkg.in/natefinch/lumberjack.v2
    • github.com/stretchr/testify (for testing)

License

This project is licensed under the terms found in the LICENSE file.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Documentation

Overview

Package log provides a structured logging facility for the Ziwi framework.

This package is built on top of the zap logging library (go.uber.org/zap) and provides a simplified interface for common logging patterns. It supports various log levels, structured logging with key-value pairs, and different output formats.

Features:

  • Multiple log levels: Debug, Info, Warn, Error, Panic, Fatal
  • Structured logging with key-value pairs
  • Printf-style logging with format strings
  • Println-style logging
  • JSON and console output formats
  • Configurable time layout
  • Log file rotation by date
  • Separate error log files
  • Optional caller information and stack traces

Basic Usage:

// Initialize with custom options
opts := log.NewOptions()
opts.Level = "debug"
opts.Format = "json"
log.Init(opts)

// Simple logging
log.Debug("Debug message")
log.Info("Info message")
log.Warn("Warning message")
log.Error("Error message")

// Structured logging with key-value pairs
log.Infow("User logged in", "user_id", 123, "ip", "192.168.1.1")
log.Errorw("Database connection failed", "error", err, "retry", true)

// Format string logging
log.Debugf("Processing item %d of %d", i, total)
log.Errorf("Failed to connect to %s: %v", host, err)

Configuration: The logger can be configured through the Options struct:

type Options struct {
    Prefix    string // Log prefix, e.g., "ZIWI"
    Directory string // Log file directory, e.g., "logs"

    Level      string // "debug", "info", "warn", "error", "dpanic", "panic", "fatal"
    TimeLayout string // Time format, default: "2006-01-02 15:04:05.000"
    Format     string // "console" or "json"

    DisableCaller     bool // Disable caller information
    DisableStacktrace bool // Disable stack traces
    DisableSplitError bool // Disable separate error log files
}

Example configuration in ziwi.yaml:

log:
  disable-caller: false
  disable-stacktrace: false
  level: debug
  format: console
  output-paths: [/tmp/ziwi.log, stdout]

Custom Logger: You can create a custom logger instance for specific components:

customOpts := log.NewOptions()
customOpts.Prefix = "MYCOMPONENT"
customLogger := log.NewLogger(customOpts)
customLogger.Info("Component initialized")

Package log is a log package.

Index

Constants

View Source
const (
	DefaultPrefix     = "ZIWI_"
	DefaultLevel      = zapcore.InfoLevel
	DefaultTimeLayout = "2006-01-02 15:04:05.000"
	DefaultFormat     = "console" // console style

	DefaultDisableCaller     = false
	DefaultDisableStacktrace = false
	DefaultDisableSplitError = true

	DefaultMaxSize    = 100   // 100MB
	DefaultMaxBackups = 3     // Keep 3 old log files
	DefaultCompress   = false // Not compress rotated log files
)

Variables

View Source
var DefaultDirectory = func() string {
	home, err := os.UserHomeDir()
	if err != nil {
		panic(fmt.Sprintf("Failed to get user home directory: %v", err))
	}
	return filepath.Join(home, "logs")
}()

DefaultDirectory returns the default log directory, which is typically the user's home directory joined with "logs".

Functions

func Debug

func Debug(args ...any)

func Debugf

func Debugf(template string, args ...any)

Debugf formats the message according to the format specifier and logs it.

func Debugln

func Debugln(args ...any)

func Debugw

func Debugw(msg string, ksAndvs ...any)

Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func Error

func Error(args ...any)

func Errorf

func Errorf(template string, args ...any)

Errorf formats the message according to the format specifier and logs it.

func Errorln

func Errorln(args ...any)

func Errorw

func Errorw(msg string, keysAndValues ...any)

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func Fatal

func Fatal(args ...any)

func Fatalf

func Fatalf(template string, args ...any)

Fatalf formats the message according to the format specifier and calls os.Exit.

func Fatalln

func Fatalln(args ...any)

func Fatalw

func Fatalw(msg string, ksAndvs ...any)

Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With.

func Info

func Info(args ...any)

func Infof

func Infof(template string, args ...any)

Infof formats the message according to the format specifier and logs it.

func Infoln

func Infoln(args ...any)

func Infow

func Infow(msg string, ksAndvs ...any)

Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func Panic

func Panic(args ...any)

func Panicf

func Panicf(template string, args ...any)

Panicf formats the message according to the format specifier and panics.

func Panicln

func Panicln(args ...any)

func Panicw

func Panicw(msg string, keysAndValues ...any)

Panicw logs a message with some additional context, then panics. The variadic key-value pairs are treated as they are in With.

func Sync

func Sync()

Sync flushs any buffered log entries. Applications should take care to call Sync before exiting.

func Warn

func Warn(args ...any)

func Warnf

func Warnf(template string, args ...any)

Warnf formats the message according to the format specifier and logs it.

func Warnln

func Warnln(args ...any)

func Warnw

func Warnw(msg string, keysAndValues ...any)

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

Types

type Logger

type Logger interface {
	Sync()

	Debug(args ...any)
	Debugf(template string, args ...any)
	Debugw(msg string, keysAndValues ...any)
	Debugln(args ...any)

	Info(args ...any)
	Infof(template string, args ...any)
	Infow(msg string, keysAndValues ...any)
	Infoln(args ...any)

	Warn(args ...any)
	Warnf(template string, args ...any)
	Warnw(msg string, keysAndValues ...any)
	Warnln(args ...any)

	Error(args ...any)
	Errorf(template string, args ...any)
	Errorw(msg string, keysAndValues ...any)
	Errorln(args ...any)

	Panic(args ...any)
	Panicf(template string, args ...any)
	Panicw(msg string, keysAndValues ...any)
	Panicln(args ...any)

	Fatal(args ...any)
	Fatalf(template string, args ...any)
	Fatalw(msg string, keysAndValues ...any)
	Fatalln(args ...any)
}

Logger defines the interface, includes the supported logging methods. For each log level, it exposes four methods:

  • methods named after the log level for log.Print-style logging
  • methods ending in "w" for loosely-typed structured logging (read as "info with")
  • methods ending in "f" for log.Printf-style logging
  • methods ending in "ln" for log.Println-style logging

type Options

type Options struct {
	Prefix    string // Log Prefix, e.g ZIWI
	Directory string // Log File Directory, e.g logs

	Level      string // Log Level, "debug", "info", "warn", "error"
	TimeLayout string // Time Layout, e.g "2006-01-02 15:04:05.000"
	Format     string // Log Format, "console", "json"

	DisableCaller     bool // Disable caller information
	DisableStacktrace bool // Disable stack traces
	DisableSplitError bool // Disable separate error log files

	// Log rotation settings
	MaxSize    int  // Maximum size of log files in megabytes before rotation
	MaxBackups int  // Maximum number of old log files to retain
	Compress   bool // Whether to compress rotated log files
}

Options for logger

func NewOptions

func NewOptions() *Options

NewOptions return the default Options.

Default:

Prefix:    "ZIWI_",
Directory: "$HOME/logs",

Level:      "info",
TimeLayout: "2006-01-02 15:04:05.000",
Format:     "console",

DisableCaller:     false,
DisableStacktrace: false,
DisableSplitError: false,

// Default log rotation settings
MaxSize:    100, // 100MB
MaxBackups: 3,   // Keep 3 old log files
Compress:   false,

func (*Options) Validate

func (opt *Options) Validate() error

func (*Options) WithCompress

func (opt *Options) WithCompress(compress bool) *Options

func (*Options) WithDirectory

func (opt *Options) WithDirectory(dir string) *Options

func (*Options) WithDisableCaller

func (opt *Options) WithDisableCaller(disableCaller bool) *Options

func (*Options) WithDisableSplitError

func (opt *Options) WithDisableSplitError(disableSplitError bool) *Options

func (*Options) WithDisableStacktrace

func (opt *Options) WithDisableStacktrace(disableStacktrace bool) *Options

func (*Options) WithFormat

func (opt *Options) WithFormat(format string) *Options

func (*Options) WithLevel

func (opt *Options) WithLevel(level string) *Options

func (*Options) WithMaxBackups

func (opt *Options) WithMaxBackups(maxBackups int) *Options

func (*Options) WithMaxSize

func (opt *Options) WithMaxSize(maxSize int) *Options

func (*Options) WithPrefix

func (opt *Options) WithPrefix(prefix string) *Options

func (*Options) WithTimeLayout

func (opt *Options) WithTimeLayout(timeLayout string) *Options

type ZiwiLog

type ZiwiLog struct {
	zapcore.Encoder
	// contains filtered or unexported fields
}

ZiwiLog is the implement of Logger interface. It wraps zap.Logger.

func NewLogger

func NewLogger(opts *Options) *ZiwiLog

NewLogger creates a new logger instance. It will initialize the global logger instance with the specified options.

Returns:

  • *ZiwiLog: The new logger instance.

func (*ZiwiLog) Debug

func (l *ZiwiLog) Debug(args ...any)

func (*ZiwiLog) Debugf

func (l *ZiwiLog) Debugf(template string, args ...any)

Debugf formats the message according to the format specifier and logs it.

func (*ZiwiLog) Debugln

func (l *ZiwiLog) Debugln(args ...any)

func (*ZiwiLog) Debugw

func (l *ZiwiLog) Debugw(msg string, ksAndvs ...any)

Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*ZiwiLog) EncodeEntry

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

EncodeEntry encodes the entry and fields into a buffer.

func (*ZiwiLog) Error

func (l *ZiwiLog) Error(args ...any)

func (*ZiwiLog) Errorf

func (l *ZiwiLog) Errorf(template string, args ...any)

Errorf formats the message according to the format specifier and logs it.

func (*ZiwiLog) Errorln

func (l *ZiwiLog) Errorln(args ...any)

func (*ZiwiLog) Errorw

func (l *ZiwiLog) Errorw(msg string, ksAndVs ...any)

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*ZiwiLog) Fatal

func (l *ZiwiLog) Fatal(args ...any)

func (*ZiwiLog) Fatalf

func (l *ZiwiLog) Fatalf(template string, args ...any)

Fatalf formats the message according to the format specifier and calls os.Exit.

func (*ZiwiLog) Fatalln

func (l *ZiwiLog) Fatalln(args ...any)

func (*ZiwiLog) Fatalw

func (l *ZiwiLog) Fatalw(msg string, ksAndvs ...any)

Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With.

func (*ZiwiLog) Info

func (l *ZiwiLog) Info(args ...any)

func (*ZiwiLog) Infof

func (l *ZiwiLog) Infof(template string, args ...any)

Infof formats the message according to the format specifier and logs it.

func (*ZiwiLog) Infoln

func (l *ZiwiLog) Infoln(args ...any)

func (*ZiwiLog) Infow

func (l *ZiwiLog) Infow(msg string, keysAndValues ...any)

Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*ZiwiLog) Panic

func (l *ZiwiLog) Panic(args ...any)

func (*ZiwiLog) Panicf

func (l *ZiwiLog) Panicf(template string, args ...any)

Panicf formats the message according to the format specifier and panics.

func (*ZiwiLog) Panicln

func (l *ZiwiLog) Panicln(args ...any)

func (*ZiwiLog) Panicw

func (l *ZiwiLog) Panicw(msg string, ksAndvs ...any)

Panicw logs a message with some additional context, then panics. The variadic key-value pairs are treated as they are in With.

func (*ZiwiLog) Sync

func (l *ZiwiLog) Sync()

Sync flushs any buffered log entries. Applications should take care to call Sync before exiting.

func (*ZiwiLog) Warn

func (l *ZiwiLog) Warn(args ...any)

func (*ZiwiLog) Warnf

func (l *ZiwiLog) Warnf(template string, args ...any)

Warnf formats the message according to the format specifier and logs it.

func (*ZiwiLog) Warnln

func (l *ZiwiLog) Warnln(args ...any)

func (*ZiwiLog) Warnw

func (l *ZiwiLog) Warnw(msg string, keysAndValues ...any)

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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