slogx

package module
v1.4.0 Latest Latest
Warning

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

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

README

Slogx Package

Introduction

Slogx is an enhanced logging package built on top of Go's standard library log/slog. It provides rich extensions to standard logging capabilities including:

  • Multiple log formats (Text/JSON/Colorful output with Tint)
  • Log rotation support via Lumberjack
  • Configurable log levels, output destinations, and time formats
  • Built-in support for console output and file logging
  • Developer-friendly source code location tracking
  • Terminal color output customization

Features

  • Format Support: Text/JSON/Tint/Dev formats
  • Rotation: Automatic log rotation with Lumberjack
  • Flexibility:
    • Configure output destinations (console/file)
    • Custom time formats via WithTimeLayout()
    • Enable source code location tracking with WithAddSource()
  • Color Control: Disable color output with WithNoColor()
  • Level Control: Set from LevelDebug to LevelFatal

Installation

Usage

Basic Setup
import "github.com/origadmin/toolkits/slogx"

func main() {
  logger := slogx.New(
    slogx.WithFile("app.log"),
    slogx.WithFormat(slogx.FormatJSON),
    slogx.WithLumberjack(&lumberjack.Logger{
    MaxSize: 50, // MB
    MaxAge:  28, // days
    }),
  )
}
Advanced Examples
Colored Console Output
logger := slogx.New(
  slogx.WithFormat(slogx.FormatTint),
  slogx.WithConsoleOnly(),
)
Developer-friendly Format
logger := slogx.New(
  slogx.WithFormat(slogx.FormatDev),
  slogx.WithAddSource(),
  slogx.WithTimeLayout("2006-01-02 15:04:05.000"),
)
JSON Log Format with Rotation
logger := slogx.New(
  slogx.WithFile("app.json.log"),
  slogx.WithFormat(slogx.FormatJSON),
  slogx.WithLumberjack(&lumberjack.Logger{
    Filename:   "app.json.log",
    MaxSize:    10, // megabytes per file
    MaxBackups: 5,
    MaxAge:     30, // days
  }),
)

Configuration Options

Option Description
WithFile Specify log file path
WithLumberjack Configure log rotation using Lumberjack
WithFormat Choose log format (FormatText/JSON/Tint/Dev)
WithTimeLayout Set custom time format (default: 2006-01-02 15:04:05 MST)
WithAddSource Include file/line number information in logs
WithConsole Enable console output (can be combined with file output)
WithConsoleOnly Output logs to console only (no file)
WithLevel Set log level (LevelDebug/Info/Warning/Error/Fatal)
WithNoColor Disable terminal color output
WithDefault Set as global default logger

Format Details

  • FormatDev: Developer-friendly format with color coding and source location
  • FormatTint: Terminal-friendly colored text output
  • FormatJSON: Machine-readable structured logging
  • FormatText: Plain text format with basic timestamp and level info

Documentation

Overview

Package slogx implements the functions, types, and interfaces for the module.

Package slogx contains generated code by adptool.

Package slogx contains the go:generate directives for adptool. This file exists to ensure the generated output is named log.adapter.go.

Package slogx implements enhanced logging functions for slog

Index

Constants

View Source
const (
	Black         = devslog.Black
	Blue          = devslog.Blue
	Cyan          = devslog.Cyan
	Green         = devslog.Green
	Magenta       = devslog.Magenta
	Red           = devslog.Red
	UnknownColor  = devslog.UnknownColor
	White         = devslog.White
	Yellow        = devslog.Yellow
	KindAny       = slog.KindAny
	KindBool      = slog.KindBool
	KindDuration  = slog.KindDuration
	KindFloat64   = slog.KindFloat64
	KindGroup     = slog.KindGroup
	KindInt64     = slog.KindInt64
	KindLogValuer = slog.KindLogValuer
	KindString    = slog.KindString
	KindTime      = slog.KindTime
	KindUint64    = slog.KindUint64
	LevelDebug    = slog.LevelDebug
	LevelError    = slog.LevelError
	LevelInfo     = slog.LevelInfo
	LevelKey      = slog.LevelKey
	LevelWarn     = slog.LevelWarn
	MessageKey    = slog.MessageKey
	SourceKey     = slog.SourceKey
	TimeKey       = slog.TimeKey
)
View Source
const (
	// DefaultTimeLayout the default time layout;
	DefaultTimeLayout = time.DateTime
)
View Source
const (
	LevelFatal = slog.Level(12)
)

LevelFatal is a custom log level, demonstrating how to extend slog's levels.

Variables

View Source
var DiscardHandler = slog.DiscardHandler

Functions

func Any

func Any(key string, value any) slog.Attr

func AnyValue

func AnyValue(v any) slog.Value

func Bool

func Bool(key string, v bool) slog.Attr

func BoolValue

func BoolValue(v bool) slog.Value

func Debug

func Debug(msg string, args ...any)

func DebugContext

func DebugContext(ctx context.Context, msg string, args ...any)

func Default

func Default() *slog.Logger

func Duration

func Duration(key string, v time.Duration) slog.Attr

func DurationValue

func DurationValue(v time.Duration) slog.Value

func Error

func Error(msg string, args ...any)

func ErrorContext

func ErrorContext(ctx context.Context, msg string, args ...any)

func Float64

func Float64(key string, v float64) slog.Attr

func Float64Value

func Float64Value(v float64) slog.Value

func Group

func Group(key string, args ...any) slog.Attr

func GroupValue

func GroupValue(as ...slog.Attr) slog.Value

func Info

func Info(msg string, args ...any)

func InfoContext

func InfoContext(ctx context.Context, msg string, args ...any)

func Int

func Int(key string, value int) slog.Attr

func Int64

func Int64(key string, value int64) slog.Attr

func Int64Value

func Int64Value(v int64) slog.Value

func IntValue

func IntValue(v int) slog.Value

func Log

func Log(ctx context.Context, level slog.Level, msg string, args ...any)

func LogAttrs

func LogAttrs(ctx context.Context, level slog.Level, msg string, attrs ...slog.Attr)

func New

func New(options ...Option) *slog.Logger

New creates a new slog.Logger by applying the provided functional options. This function is a refactored, cleaner version of the original NewSlogx, preserving all functionality while improving maintainability.

func NewDebug

func NewDebug(options ...Option) *slog.Logger

NewDebug creates a new slog.Logger with debug level. It's a convenient shortcut for New(WithLevel(slog.LevelDebug)).

func NewJSONHandler

func NewJSONHandler(w io.Writer, opts *slog.HandlerOptions) *slog.JSONHandler

func NewLogLogger

func NewLogLogger(h slog.Handler, level slog.Level) *log.Logger

func NewRecord

func NewRecord(t time.Time, level slog.Level, msg string, pc uintptr) slog.Record

func NewSlog added in v0.3.20

func NewSlog(h slog.Handler) *slog.Logger

func NewTextHandler

func NewTextHandler(w io.Writer, opts *slog.HandlerOptions) *slog.TextHandler

func NewTintHandler

func NewTintHandler(w io.Writer, opts *tint.Options) slog.Handler

func SetDefault

func SetDefault(l *slog.Logger)

func SetLogLoggerLevel

func SetLogLoggerLevel(level slog.Level) (oldLevel slog.Level)

func String

func String(key, value string) slog.Attr

func StringValue

func StringValue(value string) slog.Value

func Time

func Time(key string, v time.Time) slog.Attr

func TimeValue

func TimeValue(v time.Time) slog.Value

func TintAttr added in v0.3.20

func TintAttr(color uint8, attr slog.Attr) slog.Attr

func TintErr added in v0.3.20

func TintErr(err error) slog.Attr

func Uint64

func Uint64(key string, v uint64) slog.Attr

func Uint64Value

func Uint64Value(v uint64) slog.Value

func Warn

func Warn(msg string, args ...any)

func WarnContext

func WarnContext(ctx context.Context, msg string, args ...any)

func With

func With(args ...any) *slog.Logger

Types

type Attr

type Attr = slog.Attr

type Color

type Color = devslog.Color

type DevslogOptions added in v0.3.20

type DevslogOptions = devslog.Options

type Format

type Format int
const (
	// FormatJSON json format
	FormatJSON Format = iota
	// FormatText text format
	FormatText
	// FormatTint tint format
	FormatTint
	// FormatDev dev format
	FormatDev
)

func (Format) String

func (i Format) String() string

type Handler

type Handler = slog.Handler

type HandlerOptions

type HandlerOptions = slog.HandlerOptions

type JSONHandler

type JSONHandler = slog.JSONHandler

type Kind

type Kind = slog.Kind

type Level

type Level = slog.Level

type LevelVar

type LevelVar = slog.LevelVar

type Leveler

type Leveler = slog.Leveler

type LogValuer

type LogValuer = slog.LogValuer

type Logger

type Logger = slog.Logger

type LumberjackLogger

type LumberjackLogger = lumberjack.Logger

type Option

type Option = func(*Options)

func WithAddSource

func WithAddSource() Option

WithAddSource add source info to log

func WithConsole

func WithConsole(set bool) Option

WithConsole set the log to console or /dev/null

func WithConsoleOnly

func WithConsoleOnly() Option

WithConsoleOnly set the log to console only

func WithDefault

func WithDefault(set bool) Option

WithDefault use output as slog.Default()

func WithDevConfig

func WithDevConfig(config *DevslogOptions) Option

WithDevConfig set dev config

func WithFile

func WithFile(file string) Option

WithFile write log to some File Deprecated: use WithOutputFile instead

func WithFormat

func WithFormat(format Format) Option

WithFormat custom format

func WithLevel

func WithLevel(level Leveler) Option

WithLevel custom log level

func WithLumberjack

func WithLumberjack(lumberjackLogger *LumberjackLogger) Option

WithLumberjack write log to some File with rotation

func WithNoColor

func WithNoColor() Option

WithNoColor disable color

func WithOutputFile added in v0.3.20

func WithOutputFile(file string) Option

WithOutputFile write log to some File

func WithReplaceAttr

func WithReplaceAttr(replaceAttr func(groups []string, attr Attr) Attr) Option

WithReplaceAttr custom replaceAttr

func WithTimeLayout

func WithTimeLayout(timeLayout string) Option

WithTimeLayout custom time format

type Options

type Options struct {
	Output           string
	Format           Format
	TimeLayout       string
	Console          bool
	Level            Leveler
	ReplaceAttr      func(groups []string, attr Attr) Attr
	AddSource        bool
	LumberjackLogger *LumberjackLogger
	DevslogOptions   *DevslogOptions
	NoColor          bool
	Default          bool
}

Options custom setup config

func DefaultOptions added in v0.3.20

func DefaultOptions() Options

type Record

type Record = slog.Record

type Source

type Source = slog.Source

type TextHandler

type TextHandler = slog.TextHandler

type TintOptions

type TintOptions = tint.Options

type Value

type Value = slog.Value

Jump to

Keyboard shortcuts

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