slogx

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: MIT Imports: 8 Imported by: 0

README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

slogx

Enhanced slog package with invoke skip support to enable accurate source location reporting in Go logging assist functions.


CHINESE README

中文说明

Core Features

🎯 Invoke Skip Support: Provides WithCallerSkip function like zap.AddCallerSkip
📍 Accurate Source Location: Maintains correct invoke information in nested assist functions
🔗 1:1 API Support: 100% compatible with slog.Log Instance API
🍬 SugaredLogger Support: Includes zap.SugaredLogger-like flattened argument logging
Worldwide Variables: Available LOG and SUG worldwide loggers

Installation

go get github.com/yylego/slogx

Usage

Basic Usage
package main

import (
	"github.com/yylego/slogx"
)

func main() {
	// Use worldwide LOG with structured logging
	slogx.LOG.Info("application started", "version", "1.0.0", "mode", "production")

	// Use worldwide SUG with flattened arguments
	slogx.SUG.Info("client", "alice", "logged in")

	// SUG with Infoln adds spaces between arguments
	slogx.SUG.Infoln("Processing", "item", 123, "of", 456)

	// Debug level logging with structured data
	slogx.LOG.Debug("database query", "table", "clients", "duration", "45ms")

	// Warning level with flattened arguments
	slogx.SUG.Warn("high", "memory", "usage", 85, "%")
}

⬆️ Source: Source

Custom Log Instance with Invoke Skip
package main

import (
	"log/slog"
	"os"

	"github.com/yylego/slogx"
)

// logHelper demonstrates stack-frame skip in assist functions
func logHelper(instance *slogx.Logger, message string) {
	// Skip 1 frame to show logHelper invoke point instead of this function
	instance.Skip(1).Info(message, "from", "assist function")
}

// nestedLogHelper demonstrates multiple level stack-frame skip
func nestedLogHelper(instance *slogx.Logger, operation string) {
	// Skip 2 frames to show the original invoke point
	instance.Skip(2).Info("nested operation", "op", operation)
}

func main() {
	// Create custom slog log instance with JSON handler
	jsonHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		AddSource: true,
		Level:     slog.LevelDebug,
	})
	baseLogger := slog.New(jsonHandler)

	// Wrap with slogx to enable stack-frame skip support
	instance := slogx.New(baseLogger)

	// Use in assist function with correct source location
	logHelper(instance, "message from main")

	// Direct logging without skip shows current location
	instance.Info("direct message", "level", "info")

	// Use WithCallerSkip as alternative to Skip
	instance.WithCallerSkip(1).Warn("warning from main", "skip", 1)

	// Chain with other slog methods
	instance.With("request_id", "12345").
		WithGroup("app").
		Info("chained logging", "status", "success")

	// Demonstrate nested assist with multiple skip levels
	func() {
		nestedLogHelper(instance, "cleanup")
	}()
}

⬆️ Source: Source

SugaredLogger Usage
package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/yylego/slogx"
)

// processData demonstrates SugaredLogger in business logic
func processData(sugar *slogx.SugaredLogger, itemID int) {
	sugar.Info("Start", "processing", "item", itemID)
	sugar.Infoln("Completed", "item", itemID, "status", "success")
}

// contextLogger demonstrates context-aware logging
func contextLogger(sugar *slogx.SugaredLogger, ctx context.Context) {
	sugar.InfoContext(ctx, "Processing", "with", "context", "data")
	sugar.InfolnContext(ctx, "Status", "check", "complete")
}

func main() {
	// Create custom handler with text output
	textHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		AddSource: false,
		Level:     slog.LevelInfo,
	})
	baseLogger := slog.New(textHandler)

	// Create Log Instance and convert to SugaredLogger
	instance := slogx.New(baseLogger)
	sugar := instance.Sugar()

	// Sprint-style concatenation without extra spaces
	sugar.Info("Processing", "item", 123, "of", 456)
	// Output: "Processingitem123of456"

	// Sprintln-style with spaces between each argument
	sugar.Infoln("Processing", "item", 123, "of", 456)
	// Output: "Processing item 123 of 456"

	// Warning with numeric data
	sugar.Warn("Memory", "usage", 85.5, "%", "threshold", 80)

	// Use in business logic function
	processData(sugar, 42)

	// Context-aware logging
	ctx := context.Background()
	contextLogger(sugar, ctx)

	// Create SugaredLogger from worldwide LOG
	globalSugar := slogx.LOG.Sugar()
	globalSugar.Infoln("Using", "worldwide", "LOG", "instance")

	// Combine different logging styles
	globalSugar.Info("Event", 1, "Type", "startup")
	globalSugar.Infoln("Event", 2, "Type", "ready")
}

⬆️ Source: Source

API Documentation

Core Types
Log Instance

Lightweight package around slog.LogInstance with invoke skip support:

// Create new Log Instance package
logInstance := slogx.New(slogLogger)

// Skip extra stack frames
logInstance.Skip(1).Info("message")
logInstance.WithCallerSkip(2).Warn("warning message")

// Each slog.LogInstance method supported
logInstance.Info(msg, args...)
logInstance.Debug(msg, args...)
logInstance.Warn(msg, args...)
logInstance.Warn(msg, args...)
logInstance.InfoContext(ctx, msg, args...)
logInstance.With(args...)
logInstance.WithGroup(name)
SugaredLogger

Provides flattened argument logging like zap.SugaredLogger:

// Create SugaredLogger
sugar := slogx.NewSugaredLogger(logInstance)
// And from Log Instance
sugar := logInstance.Sugar()

// Sprint-style concatenation
sugar.Info("client", 123, "action")     // "user123 action"
sugar.Debug("1", 2, 3, 4, "5", 6)     // "12 3 456"

// Sprintln-style with spaces
sugar.Infoln("client", 123, "action")   // "client 123 action"
sugar.Debugln("1", 2, 3, 4, "5", 6)   // "1 2 3 4 5 6"

// Context methods
sugar.InfoContext(ctx, args...)
sugar.InfolnContext(ctx, args...)
Worldwide Variables
// LOG - Worldwide Log Instance with structured logging
slogx.LOG.Info("message", "key", "value")

// SUG - Worldwide SugaredLog Instance with flattened arguments
slogx.SUG.Info("multiple", "arguments", 123)

// SetLog - Configure worldwide loggers with custom slog instance
customLogger := slog.New(customHandler)
slogx.SetLog(customLogger)

// NewDefault - Create Log Instance with default JSON configuration
logInstance := slogx.NewDefault()

Advanced Examples

Nested Assist Functions
func serviceMethod() {
    // Will show serviceMethod as source
    logWithContext("operation", "data")
}

func logWithContext(op string, data string) {
    // Skip 1 to show serviceMethod instead of logWithContext
    slogx.LOG.Skip(1).Info("processing", "op", op, "data", data)
}
Method Chaining
logInstance := slogx.New(slogLogger)
    .WithGroup("app")
    .With("request_id", "123")
    .Skip(1)
    
logInstance.Info("chained log instance prepared")
Custom Log Levels
ctx := context.Background()
if slogx.LOG.Enabled(ctx, slog.LevelDebug) {
    slogx.LOG.Debug("debug mode enabled")
}

📄 License

MIT License - see LICENSE.


💬 Contact & Feedback

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • 🐛 Mistake reports? Open an issue on GitHub with reproduction steps
  • 💡 Fresh ideas? Create an issue to discuss
  • 📖 Documentation confusing? Report it so we can enhance it
  • 🚀 Need new features? Share the use cases to help us understand requirements
  • Performance issue? Help us optimize via reporting slow operations
  • 🔧 Configuration problem? Ask questions about complex setups
  • 📢 Track project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package enhanced the workflow
  • 💬 Feedback? We welcome suggestions and comments

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and adhere to Go code style conventions
  7. Documentation: Update documentation to support client-facing changes
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • Give GitHub stars if this project helps you
  • 🤝 Share with teammates and (golang) programming friends
  • 📝 Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! 🎉🎉🎉


GitHub Stars

Stargazers

Documentation

Overview

Package slogx: Lightweight package around slog with caller skip support Provides zap.AddCallerSkip-like function that standard log/slog package lacks Solves caller location issues in logging assist functions with 1:1 API compatible support

slogx: 提供支持 caller skip 的 slog 轻量包装器 为标准 log/slog 包提供类似 zap.AddCallerSkip 的功能 在保持 1:1 API 兼容的前提下解决日志助手函数中的调用位置问题

Index

Constants

This section is empty.

Variables

View Source
var LOG = NewDefault()

LOG provides structured attribute logging with pairs LOG 提供键值对日志记录

SUG provides flattened argument logging like zap.SugaredLogger SUG 提供平铺参数日志记录,类似 zap.SugaredLogger

Functions

func SetLog

func SetLog(slog *slog.Logger)

SetLog configures LOG and SUG with custom slog instance SetLog 使用自定义 slog 实例配置 LOG 和 SUG

Types

type Logger

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

Logger is a lightweight package that supports AddCallerSkip-like action Provides 1:1 API compatible support with slog.Logger while enabling correct caller skip Uses runtime.Callers to adjust code position to ensure accurate source location reporting

Logger 是一个轻量包装器,支持 AddCallerSkip 类似的行为 与 slog.Logger 提供 1:1 API 兼容性,同时支持正确的调用者跳过 使用 runtime.Callers 调整程序计数器,确保准确的源位置报告

func New

func New(slog *slog.Logger) *Logger

New creates a package with given logger. Logger must not be none Sets default skip value to 4 to ensure accurate caller location reporting Returns reference to enable method chaining and correct cloning action

New 用给定 logger 创建包装器。Logger 不能为 none 设置默认 skip 值为 4,确保准确的调用者位置报告 返回指针以支持方法链式调用和正确的克隆行为

func NewDefault

func NewDefault() *Logger

NewDefault creates a Logger with default JSON handler configuration Auto configures with source location and debug level output

NewDefault 创建具有默认 JSON 处理器配置的 Logger 自动配置源位置和调试级别输出

func (*Logger) Debug

func (G *Logger) Debug(msg string, args ...any)

Debug logs a debug message with key-value pairs Debug 记录带键值对的调试消息

func (*Logger) DebugContext

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

DebugContext logs a debug message with context and key-value pairs DebugContext 记录带上下文和键值对的调试消息

func (*Logger) Enabled

func (G *Logger) Enabled(ctx context.Context, level slog.Level) bool

Enabled checks if the log instance emits log records at the given log-level Enabled 检查日志实例是否在给定日志级别发出日志记录

func (*Logger) Error

func (G *Logger) Error(msg string, args ...any)

Error logs an error message with key-value pairs Error 记录带键值对的错误消息

func (*Logger) ErrorContext

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

ErrorContext logs an error message with context and key-value pairs ErrorContext 记录带上下文和键值对的错误消息

func (*Logger) Handler

func (G *Logger) Handler() slog.Handler

Handler returns the base slog.Handler component Handler 返回底层 slog.Handler 组件

func (*Logger) Info

func (G *Logger) Info(msg string, args ...any)

Info logs an info message with key-value pairs Info 记录带键值对的信息消息

func (*Logger) InfoContext

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

InfoContext logs an info message with context and key-value pairs InfoContext 记录带上下文和键值对的信息消息

func (*Logger) Log

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

Log logs a message with key-value pairs at given level (generic logging method) Log 在指定级别记录带键值对的消息(通用日志方法)

func (*Logger) LogAttrs

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

LogAttrs logs a message with structured attributes at given level LogAttrs 在指定级别记录带结构化属性的消息

func (*Logger) Skip

func (G *Logger) Skip(depth int) *Logger

Skip is a convenience alias of WithCallerSkip method Provides short method name in common caller skip operations

Skip 是 WithCallerSkip 方法的便利别名 为常用调用者跳过操作提供更短的方法名

func (*Logger) Sugar

func (G *Logger) Sugar() *SugaredLogger

Sugar returns a SugaredLogger to enable flattened argument logging Sugar 返回用于平铺参数日志记录的 SugaredLogger

func (*Logger) Warn

func (G *Logger) Warn(msg string, args ...any)

Warn logs a warn message with key-value pairs Warn 记录带键值对的警告消息

func (*Logger) WarnContext

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

WarnContext logs a warn message with context and key-value pairs WarnContext 记录带上下文和键值对的警告消息

func (*Logger) With

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

With returns a new Logger that includes the given arguments Creates a clone with extra context fields attached to subsequent log entries

With 返回包含给定参数的新 Logger 创建一个带有额外上下文字段的克隆,附加到后续日志条目

func (*Logger) WithCallerSkip

func (G *Logger) WithCallerSkip(depth int) *Logger

WithCallerSkip returns a new Logger with extra stack frame skip Creates a clone with adjusted skip value in nested assist functions Enables accurate source location reporting in multi-stage package scenarios

WithCallerSkip 返回一个新的 Logger,增加跳过的栈帧层数 为嵌套助手函数创建带有调整 skip 值的克隆 在多层包装器场景中实现准确的源位置报告

func (*Logger) WithGroup

func (G *Logger) WithGroup(name string) *Logger

WithGroup returns a new Logger that groups attributes within the given name Creates a clone that nests subsequent attributes within a group namespace

WithGroup 返回在给定名称下分组属性的新 Logger 创建一个将后续属性嵌套在组命名空间下的克隆

type SugaredLogger

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

SugaredLogger provides zap.SugaredLogger-like interface with flattened arguments Converts arguments into a single message string using fmt.Sprint

SugaredLogger 提供类似 zap.SugaredLogger 的平铺参数接口 使用 fmt.Sprint 将参数转换为单个消息字符串

func NewSugaredLogger

func NewSugaredLogger(logger *Logger) *SugaredLogger

NewSugaredLogger creates a new SugaredLogger with flattened argument support NewSugaredLogger 创建支持平铺参数的新 SugaredLogger

func (*SugaredLogger) Debug

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

Debug logs flattened arguments at debug level (like fmt.Sprint) Debug 在调试级别记录平铺参数(类似 fmt.Sprint)

func (*SugaredLogger) DebugContext

func (s *SugaredLogger) DebugContext(ctx context.Context, args ...any)

DebugContext logs flattened arguments at debug level with context DebugContext 在调试级别记录平铺参数,带上下文

func (*SugaredLogger) Debugln

func (s *SugaredLogger) Debugln(args ...any)

Debugln logs flattened arguments at debug level with spaces (like fmt.Sprintln) Debugln 在调试级别记录平铺参数,用空格分隔(类似 fmt.Sprintln)

func (*SugaredLogger) DebuglnContext

func (s *SugaredLogger) DebuglnContext(ctx context.Context, args ...any)

DebuglnContext logs flattened arguments at debug level with context and spaces DebuglnContext 在调试级别记录平铺参数,带上下文,用空格分隔

func (*SugaredLogger) Error

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

Error logs flattened arguments at error level (like fmt.Sprint) Error 在错误级别记录平铺参数(类似 fmt.Sprint)

func (*SugaredLogger) ErrorContext

func (s *SugaredLogger) ErrorContext(ctx context.Context, args ...any)

ErrorContext logs flattened arguments at error level with context ErrorContext 在错误级别记录平铺参数,带上下文

func (*SugaredLogger) Errorln

func (s *SugaredLogger) Errorln(args ...any)

Errorln logs flattened arguments at error level with spaces (like fmt.Sprintln) Errorln 在错误级别记录平铺参数,用空格分隔(类似 fmt.Sprintln)

func (*SugaredLogger) ErrorlnContext

func (s *SugaredLogger) ErrorlnContext(ctx context.Context, args ...any)

ErrorlnContext logs flattened arguments at error level with context and spaces ErrorlnContext 在错误级别记录平铺参数,带上下文,用空格分隔

func (*SugaredLogger) Info

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

Info logs flattened arguments at info level (like fmt.Sprint) Info 在信息级别记录平铺参数(类似 fmt.Sprint)

func (*SugaredLogger) InfoContext

func (s *SugaredLogger) InfoContext(ctx context.Context, args ...any)

InfoContext logs flattened arguments at info level with context InfoContext 在信息级别记录平铺参数,带上下文

func (*SugaredLogger) Infoln

func (s *SugaredLogger) Infoln(args ...any)

Infoln logs flattened arguments at info level with spaces (like fmt.Sprintln) Infoln 在信息级别记录平铺参数,用空格分隔(类似 fmt.Sprintln)

func (*SugaredLogger) InfolnContext

func (s *SugaredLogger) InfolnContext(ctx context.Context, args ...any)

InfolnContext logs flattened arguments at info level with context and spaces InfolnContext 在信息级别记录平铺参数,带上下文,用空格分隔

func (*SugaredLogger) Warn

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

Warn logs flattened arguments at warn level (like fmt.Sprint) Warn 在警告级别记录平铺参数(类似 fmt.Sprint)

func (*SugaredLogger) WarnContext

func (s *SugaredLogger) WarnContext(ctx context.Context, args ...any)

WarnContext logs flattened arguments at warn level with context WarnContext 在警告级别记录平铺参数,带上下文

func (*SugaredLogger) Warnln

func (s *SugaredLogger) Warnln(args ...any)

Warnln logs flattened arguments at warn level with spaces (like fmt.Sprintln) Warnln 在警告级别记录平铺参数,用空格分隔(类似 fmt.Sprintln)

func (*SugaredLogger) WarnlnContext

func (s *SugaredLogger) WarnlnContext(ctx context.Context, args ...any)

WarnlnContext logs flattened arguments at warn level with context and spaces WarnlnContext 在警告级别记录平铺参数,带上下文,用空格分隔

Directories

Path Synopsis
internal
demos/demo1x command
demos/demo2x command
demos/demo3x command

Jump to

Keyboard shortcuts

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