log

package
v1.23.5 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: MIT Imports: 11 Imported by: 0

README

log

基于标准库 slog 的轻量封装,import 路径:

import "github.com/lishimeng/app-starter/log"

注意:与标准库 log 同名,同一文件不要混用 import "log"

默认配置

包加载时(init)已生效,不调用 log.Config().Apply() 也使用下表默认值:

默认值 说明
级别 INFO slog.LevelInfo
格式 Text slog 文本 handler(time=... level=... msg=...
输出 os.Stdout 标准输出
source= source=file:line 字段
module 自动 每条业务日志推断包路径(app-starter/ 后),非 Config 项
时间格式 slog 内置 RFC3339 纳秒,如 2026-06-18T17:43:01.524+08:00,不可配置

log.Config() 未显式设置的链式项与上表一致;Apply() 前若已调过 SetLevelFromString,级别取当前全局值。

示例(均为显式写出默认值,等价于仅 Apply()):

log.Config().
    LevelFromString("INFO").
    Text().
    Out(os.Stdout).
    Caller(false).
    Apply()

快速开始

启动时在 main 中配置(application 不再代为初始化):

log.Config().LevelFromString("INFO").Text().Apply()

可选源码位置(默认关闭):log.Config().Caller(true).Apply()。业务 log 入口栈过滤(跳过 log/ 封装);GORM SQL 由 persistence 自行过滤(跳过 gorm.io/)。

time=... level=ERROR msg="transaction fail" module=examples/web-basic/router source=examples/web-basic/router/transaction_fail.api.go:42 err="..."

用法

API 与 slog 一致:msg + 可选 key-value 对;格式化用 *f

log.Info("server started")
log.Infof("listen %s", addr)
log.Info("query", "pageNum", pageNum, "pageSize", pageSize)
log.With("err", err).Error("verify failed")

module 从调用栈推断。source(可选)由各入口栈过滤后写入(跳过 log/gorm.io/ 等封装层),相对路径 file:line

可选 For:显式模块名
log.For("syncdb").Infof("create table %s", table)
log.For("").Info("same as default auto module")
链式
log.With("err", err).Error("verify failed")
log.For("mqtt").With("client", id).Info("connected")
热路径:包内固定 logger
var logger = log.For("mqtt")

func Connect() {
    logger.Info("connected")
}

级别

字符串 slog
FINEST, FINE, DEBUG Debug
TRACE, INFO Info
WARNING, WARN Warn
ERROR, CRITICAL Error

运行时调整:log.SetLevelFromString("ERROR")(HTTP API:application/api/log.level.go)。

配置链

方法 作用 默认
Level / LevelFromString 日志级别 INFO
Text / JSON 输出格式 Text
Out(w) 输出目标 os.Stdout
Caller(bool) source=file:line false
Apply() 生效并设为 slog.Default
log.Config().
    LevelFromString("DEBUG").
    Caller(true).
    Text().              // 或 JSON()
    Out(os.Stderr).      // 不写则 stdout
    Apply()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CallerFrame added in v1.22.6

func CallerFrame() runtime.Frame

CallerFrame returns the first stack frame outside log package wrappers (business log only).

func LevelFromString

func LevelFromString(s string) (slog.Level, error)

LevelFromString maps go-log style level names to slog.Level.

func PrependSource added in v1.22.6

func PrependSource(frame runtime.Frame, attrs []any) []any

PrependSource adds source=file:line when enabled (for slog integrations such as GORM).

func SetLevelFromString

func SetLevelFromString(s string) error

SetLevelFromString changes global log level at runtime.

func Slog added in v1.22.6

func Slog(module string) *slog.Logger

Slog returns a stdlib slog.Logger for integrations (e.g. GORM).

func WriteRaw

func WriteRaw(msg string)

WriteRaw writes pre-formatted text directly to the configured output (no slog key=value wrapper). Use for ANSI-colored lines such as GORM SQL traces.

Types

type FanoutConfig added in v1.22.6

type FanoutConfig struct {
	Buffer       int           // channel capacity; default 256
	WriteTimeout time.Duration // per-backend write deadline; default 2s
	Cooldown     time.Duration // blacklist duration after timeout; default 30s
}

FanoutConfig controls async fan-out behavior.

func DefaultFanoutConfig added in v1.22.6

func DefaultFanoutConfig() FanoutConfig

type FanoutWriter added in v1.22.6

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

FanoutWriter duplicates log lines to multiple io.Writer backends asynchronously.

func NewFanout added in v1.22.6

func NewFanout(ctx context.Context, writers ...io.Writer) *FanoutWriter

NewFanout returns a fan-out writer with DefaultFanoutConfig.

func NewFanoutBuffer added in v1.22.6

func NewFanoutBuffer(size int, writers ...io.Writer) *FanoutWriter

NewFanoutBuffer is deprecated naming; use NewFanoutConfig.

func NewFanoutConfig added in v1.22.6

func NewFanoutConfig(ctx context.Context, cfg FanoutConfig, writers ...io.Writer) *FanoutWriter

NewFanoutConfig builds a fan-out writer. ctx cancellation stops the worker.

func (*FanoutWriter) BackendTimeouts added in v1.22.6

func (f *FanoutWriter) BackendTimeouts() uint64

BackendTimeouts returns how many backend writes hit the timeout.

func (*FanoutWriter) Close added in v1.22.6

func (f *FanoutWriter) Close() error

Close drains pending lines and stops the worker.

func (*FanoutWriter) Dropped added in v1.22.6

func (f *FanoutWriter) Dropped() uint64

Dropped returns lines dropped (channel full or shed after backend timeout).

func (*FanoutWriter) TimeoutDrops added in v1.22.6

func (f *FanoutWriter) TimeoutDrops() uint64

TimeoutDrops returns lines not delivered due to backend write timeouts.

func (*FanoutWriter) Write added in v1.22.6

func (f *FanoutWriter) Write(p []byte) (int, error)

Write enqueues a log line copy; returns immediately without waiting for backends.

type Logger

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

Logger wraps slog with optional fixed module and chainable With.

func Debug

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

func Debugf

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

func Error

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

func Errorf

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

func For

func For(module string) *Logger

For returns a logger with explicit module name. Empty module uses caller inference.

func Info

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

func Infof

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

func Warn

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

func Warnf

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

func With

func With(args ...any) *Logger

With returns a logger with extra attributes (module still auto or fixed).

func (*Logger) Debug

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

func (*Logger) Debugf

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

func (*Logger) Error

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

func (*Logger) Errorf

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

func (*Logger) Info

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

func (*Logger) Infof

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

func (*Logger) Slog added in v1.22.6

func (l *Logger) Slog() *slog.Logger

Slog returns a stdlib slog.Logger sharing the configured handler and fixed module.

func (*Logger) Warn

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

func (*Logger) Warnf

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

func (*Logger) With

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

type Options

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

Options builds slog handler settings (chainable).

func Config

func Config() *Options

Config starts a configuration chain.

func (*Options) Apply

func (c *Options) Apply()

Apply installs handler as slog.Default and package default.

func (*Options) Caller added in v1.22.6

func (c *Options) Caller(enabled bool) *Options

Caller enables source file:line on each record; entries attach source= via stack walk (default off).

func (*Options) JSON

func (c *Options) JSON() *Options

func (*Options) Level

func (c *Options) Level(l slog.Level) *Options

func (*Options) LevelFromString

func (c *Options) LevelFromString(s string) *Options

func (*Options) Out added in v1.22.6

func (c *Options) Out(w io.Writer) *Options

func (*Options) Text

func (c *Options) Text() *Options

Jump to

Keyboard shortcuts

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