log

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 13 Imported by: 0

README

log

The log package provides a structured logger built on top of zerolog. It is intended for services that need colored console output during development, JSON output for production log aggregators, HTTP request logging, and structured field attachment without importing a heavier logging framework.

Import

import "github.com/raykavin/gobox/log"

What it provides

  • Zerolog for structured logging with colored console or JSON output
  • Logger wrapping Zerolog with Print, Debug, Info, Warn, Error, Fatal, and Panic families
  • WithField, WithFields, and WithError for attaching context to log entries
  • API for logging HTTP request details at the appropriate level based on status code
  • Benchmark for recording named duration measurements
  • Success and Failure as semantic aliases for info and error
  • WithContext for attaching a map of arbitrary key-value pairs to a logger instance

Main types

  • Config: log level, timestamp format, color toggle, JSON toggle, and emoji toggle
  • Zerolog: the core logger; safe for concurrent use
  • Logger: embeds Zerolog and satisfies common logging interfaces

Example

package main

import (
    "time"
    "github.com/raykavin/gobox/log"
)

func main() {
    zl, err := log.New(&log.Config{
        Level:          "debug",
        DateTimeLayout: time.RFC3339,
        Colored:        true,
        JSONFormat:     false,
    })
    if err != nil {
        panic(err)
    }

    logger := &log.Logger{Zerolog: zl}

    logger.Info("application started")
    logger.WithField("port", 8080).Info("listening")
    logger.WithError(err).Error("startup failed")
}

API request logging example

start := time.Now()
// ... handle request ...
zl.API(r.Method, r.URL.Path, r.RemoteAddr, w.Status(), time.Since(start))

The log level is chosen automatically: info for 2xx and 3xx, warn for 4xx, and error for 5xx.

Config reference

Field Default Description
Level "info" Minimum log level (trace, debug, info, warn, error, fatal, panic)
DateTimeLayout time.RFC3339 Timestamp format for console output
Colored true Enable ANSI colors in console mode
JSONFormat false Emit JSON lines instead of formatted console output
UseEmoji false Prefix unknown log levels with an emoji

Notes

  • New sets the global zerolog level, which affects all zerolog loggers in the process
  • caller information (file and line number) is included automatically with a skip frame count of 3
  • WithField, WithFields, and WithError return new Logger instances; the original is not modified
  • in JSON mode the output format still goes through zerolog's ConsoleWriter; for true JSON lines, wire zerolog directly to os.Stdout using the underlying *zerolog.Logger

Documentation

Overview

Package log provides a structured logger built on top of zerolog with colored console output, JSON mode, API request logging, and field helpers.

Creating a logger

zl, err := log.New(&log.Config{
    Level:          "info",
    DateTimeLayout: time.RFC3339,
    Colored:        true,
    JSONFormat:     false,
})
if err != nil {
    log.Fatal(err)
}

Basic logging

zl.Info("server started")
zl.Warnf("retrying in %s", delay)
zl.WithField("user", userID).Error("authentication failed")

Wrapping in Logger

Logger embeds Zerolog and adds convenience methods compatible with common logging interfaces.

logger := &log.Logger{Zerolog: zl}
logger.Infof("listening on :%d", port)

API request logging

zl.API(r.Method, r.URL.Path, r.RemoteAddr, status, duration)

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidLogLevel = errors.New("invalid logger level")

Functions

This section is empty.

Types

type Config

type Config struct {
	Level          string
	DateTimeLayout string
	Colored        bool
	JSONFormat     bool
	UseEmoji       bool
}

Config holds logger configuration

type Logger

type Logger struct {
	*Zerolog
}

func (*Logger) Debug

func (s *Logger) Debug(args ...any)

Debug implements Logging.

func (*Logger) Debugf

func (s *Logger) Debugf(format string, args ...any)

Debugf implements Logging.

func (*Logger) Error

func (s *Logger) Error(args ...any)

Error implements Logging.

func (*Logger) Errorf

func (s *Logger) Errorf(format string, args ...any)

Errorf implements Logging.

func (*Logger) Fatal

func (s *Logger) Fatal(args ...any)

Fatal implements Logging.

func (*Logger) Fatalf

func (s *Logger) Fatalf(format string, args ...any)

Fatalf implements Logging.

func (*Logger) Info

func (s *Logger) Info(args ...any)

Info implements Logging.

func (*Logger) Infof

func (s *Logger) Infof(format string, args ...any)

Infof implements Logging.

func (*Logger) Panic

func (s *Logger) Panic(args ...any)

Panic implements Logging.

func (*Logger) Panicf

func (s *Logger) Panicf(format string, args ...any)

Panicf implements Logging.

func (*Logger) Print

func (s *Logger) Print(args ...any)

Print implements Logging.

func (*Logger) Printf

func (s *Logger) Printf(format string, args ...any)

Printf implements Logging.

func (*Logger) Warn

func (s *Logger) Warn(args ...any)

Warn implements Logging.

func (*Logger) Warnf

func (s *Logger) Warnf(format string, args ...any)

Warnf implements Logging.

func (*Logger) WithError

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

WithError implements Logging.

func (*Logger) WithField

func (s *Logger) WithField(key string, value any) *Logger

WithField implements Logging.

func (*Logger) WithFields

func (s *Logger) WithFields(fields map[string]any) *Logger

WithFields implements Logging.

type Zerolog

type Zerolog struct {
	*zerolog.Logger
	// contains filtered or unexported fields
}

Zerolog wraps zerolog.Logger with enhanced functionality

func New

func New(config *Config) (*Zerolog, error)

New creates a new Logger instance

func (*Zerolog) API

func (zl *Zerolog) API(method, path, remoteAddr string, statusCode int, duration time.Duration, skipFrameCount ...int)

API logs an API request

func (*Zerolog) Benchmark

func (zl *Zerolog) Benchmark(name string, duration time.Duration)

Benchmark logs a benchmark result

func (*Zerolog) Failure

func (zl *Zerolog) Failure(msg string)

Failure logs a failure message

func (*Zerolog) Success

func (zl *Zerolog) Success(msg string)

Success logs a success message

func (*Zerolog) WithContext

func (zl *Zerolog) WithContext(ctx map[string]any) *Zerolog

WithContext creates a new logger with additional context

Jump to

Keyboard shortcuts

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