log

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2026 License: Apache-2.0 Imports: 5 Imported by: 2

README

Log Package

log is a Go package that provides a simplified and opinionated interface for structured logging, built on top of the high-performance zap logger. It offers a globally configured, easy-to-use logger that can be safely used across your entire application.

Core Features

  • Global Singleton Logger: A single logger instance is used throughout the application, initialized once to ensure consistency and performance.
  • Simplified Configuration: Easily configure the logger for different environments (development vs. production) and set log levels with a clean, functional options pattern.
  • Structured and Formatted Logging: Supports both highly performant structured logging (e.g., log.Info("message", log.String("key", "value"))) and convenient formatted logging (e.g., log.Infof("user %s logged in", username)).
  • Convenient Field Constructors: Provides simple wrappers (e.g., log.String, log.Int, log.Err) for zap's structured fields, making logging code more readable.
  • Environment-Aware Output: Automatically provides human-readable, colored output in development mode and structured, efficient JSON output in production.

How to Use

1. Configure the Logger (Optional)

In your application's main or init function, you can configure the logger. This step is optional. If you don't configure it, it will run with sensible defaults (development mode, debug level).

Configuration should only be done once.

package main

import (
	"os"
	"github.com/94peter/vulpes/log"
)

func main() {
    // Example: Configure for a production environment.
    // The environment could be determined by an environment variable.
    if os.Getenv("APP_ENV") == "production" {
        log.SetConfig(
            log.WithDev(false),      // Disable development mode for JSON output.
            log.WithLevel("info"),   // Set the log level to info.
        )
    }

    // ... rest of your application logic
}
2. Log Messages

Once configured (or using defaults), you can call the logging functions from anywhere in your application.

Structured logging is the preferred method, especially in production, as it makes logs machine-readable and easier to query.

import "github.com/94peter/vulpes/log"

func processRequest(requestID string, userID int) error {
    log.Info("Processing request",
        log.String("request_id", requestID),
        log.Int("user_id", userID),
    )

    err := doSomething()
    if err != nil {
        // The Err field is a convenient way to log errors.
        log.Error("Failed to do something",
            log.String("request_id", requestID),
            log.Err(err),
        )
        return err
    }

    log.Debug("Request processed successfully", log.String("request_id", requestID))
    return nil
}
Formatted Logging

For simple messages or during early development, ...f style functions can be more convenient.

import "github.com/94peter/vulpes/log"

func greet(name string) {
    log.Infof("Hello, %s! Welcome to the application.", name)
}

API Reference

Configuration
  • SetConfig(opts ...Option): Configures the global logger. Can only be effectively called once.
  • WithDev(bool): An option to set development mode.
  • WithLevel(string): An option to set the log level (e.g., "debug", "info", "warn", "error").
Logging Methods
  • Debug(msg string, fields ...Field)
  • Info(msg string, fields ...Field)
  • Warn(msg string, fields ...Field)
  • Error(msg string, fields ...Field)
  • Panic(msg string, fields ...Field)
  • Fatal(msg string, fields ...Field)
Formatted Logging Methods
  • Debugf(format string, a ...interface{})
  • Infof(format string, a ...interface{})
  • Warnf(format string, a ...interface{})
  • Errorf(format string, a ...interface{})
  • Fatalf(format string, a ...interface{})
Field Constructors
  • String(key, val string) Field
  • Int(key, val int) Field
  • Int64(key, val int64) Field
  • Bool(key, val bool) Field
  • Time(key, val time.Time) Field
  • Duration(key, val time.Duration) Field
  • Err(err error) Field
  • Any(key, val interface{}) Field
  • ... and many more for other primitive types.

Documentation

Overview

Package log provides a simplified and opinionated interface for structured logging, built on top of the high-performance zap logger. It offers a global logger instance that can be configured once and used throughout the application.

Package log provides a simplified and opinionated interface for structured logging, built on top of the high-performance zap logger.

Package log provides a simplified and opinionated interface for structured logging, built on top of the high-performance zap logger.

Package log provides a simplified and opinionated interface for structured logging, built on top of the high-performance zap logger.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug(msg string, fields ...Field)

Debug logs a message at the Debug level with structured fields.

func Debugf

func Debugf(format string, a ...any)

Debugf logs a formatted message at the Debug level.

func Error

func Error(msg string, fields ...Field)

Error logs a message at the Error level with structured fields.

func Errorf

func Errorf(format string, a ...any)

Errorf logs a formatted message at the Error level.

func Fatal

func Fatal(msg string, fields ...Field)

Fatal logs a message at the Fatal level and then calls os.Exit(1).

func Fatalf

func Fatalf(format string, a ...any)

Fatalf logs a formatted message at the Fatal level and then calls os.Exit(1).

func Info

func Info(msg string, fields ...Field)

Info logs a message at the Info level with structured fields.

func Infof

func Infof(format string, a ...any)

Infof logs a formatted message at the Info level.

func Panic

func Panic(msg string, fields ...Field)

Panic logs a message at the Panic level and then panics.

func SetConfig

func SetConfig(opts ...Option)

SetConfig applies user-defined options to the default logger configuration. This should be called before the first log message is written to have an effect.

func Warn

func Warn(msg string, fields ...Field)

Warn logs a message at the Warn level with structured fields.

func Warnf

func Warnf(format string, a ...any)

Warnf logs a formatted message at the Warn level.

Types

type Config

type Config struct {
	Level       string
	ServiceName string
	Env         string
	CallerSkip  int
	Development bool
}

Config holds the configuration for the logger.

type Field

type Field = zapcore.Field

Field is a type alias for zapcore.Field, representing a single key-value pair in a structured log. Using a type alias provides a convenient, shorter way to reference this type.

func Any

func Any(key string, val any) Field

Any creates a Field with a value of any type, using reflection for serialization. It is useful for logging complex types like structs, slices, and maps.

func Bool

func Bool(key string, val bool) Field

Bool creates a Field with a boolean value.

func ByteString

func ByteString(key string, val []byte) Field

ByteString creates a Field with a byte slice value.

func Duration

func Duration(key string, val time.Duration) Field

Duration creates a Field with a time.Duration value.

func Err

func Err(err error) Field

Err creates a Field with an error value. It is a shorthand for zap.Error.

func Float64

func Float64(key string, val float64) Field

Float64 creates a Field with a float64 value.

func Int

func Int(key string, val int) Field

Int creates a Field with an integer value.

func Int32

func Int32(key string, val int32) Field

Int32 creates a Field with an int32 value.

func Int64

func Int64(key string, val int64) Field

Int64 creates a Field with an int64 value.

func String

func String(key string, val string) Field

String creates a Field with a string value.

func Stringer

func Stringer(key string, val fmt.Stringer) Field

Stringer creates a Field with a value that implements the fmt.Stringer interface.

func Time

func Time(key string, val time.Time) Field

Time creates a Field with a time.Time value.

func Uint

func Uint(key string, val uint) Field

Uint creates a Field with an unsigned integer value.

func Uint32

func Uint32(key string, val uint32) Field

Uint32 creates a Field with a uint32 value.

func Uint64

func Uint64(key string, val uint64) Field

Uint64 creates a Field with a uint64 value.

func Uintptr

func Uintptr(key string, val uintptr) Field

Uintptr creates a Field with a uintptr value.

type Option

type Option func(*Config)

Option defines a function that configures the logger. This follows the functional options pattern for clean and extensible configuration.

func WithCallerSkip

func WithCallerSkip(skip int) Option

WithCallerSkip sets the number of stack frames to skip when logging caller info.

func WithDev

func WithDev(development bool) Option

WithDev configures the logger to run in development mode. In development mode, logs are more human-readable, with colored levels and custom time formatting.

func WithEnv

func WithEnv(env string) Option

WithEnv sets the environment the service is running in.

func WithLevel

func WithLevel(level string) Option

WithLevel sets the minimum logging level. Only logs at or above this level will be written. Valid levels are "debug", "info", "warn", "error".

func WithServiceName

func WithServiceName(name string) Option

WithServiceName sets the name of the service that is logging.

Jump to

Keyboard shortcuts

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