logko

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 24 Imported by: 0

README

logko - Go Logging Package

一个功能丰富的 Go 日志库,基于 log/slog 构建,提供多种输出格式、日志轮转、模块级别过滤等功能。

功能特性

  • 多种输出格式: JSON、Logfmt、Terminal(彩色)
  • 日志轮转: 支持 lumberjack 日志轮转,自动管理日志文件大小和备份
  • 模块级别过滤: 通过 vmodule 对不同模块设置不同的日志级别
  • glog 兼容: 支持类似 Google glog 的 Vmodule 过滤语法
  • 线程安全: 使用 sync.RWMutex 保证并发安全
  • 灵活配置: 支持 TOML 配置文件和函数式选项两种配置方式

安装

go get github.com/koku-web3/logko@latest

文件说明

文件 说明
config.go 配置结构体定义,包含 Config 结构体和默认值配置
option.go 函数式选项模式实现,用于灵活配置日志参数
loader.go TOML 配置文件加载器
appearance.go 日志初始化入口,包含 Setup 函数
logger.go Logger 接口定义和日志级别常量
handler.go 多种 Handler 实现 (JSON、Logfmt、Terminal)
handler_glog.go GlogHandler,实现模块级别日志过滤 (vmodule)
format.go 日志格式化工具,处理特殊类型输出
root.go 全局日志函数 (Info、Debug、Error 等)

快速开始

方式一:TOML 配置文件

支持两种配置格式:

格式一:[log] 命名空间(推荐)

[log]
format = "json"
verbosity = 3
rotation = true
file_path = "/var/log/app.log"
max_size_mb = 100
max_backups = 10
max_age = 30
compress = true
vmodule = "eth/*=5,p2p=4"

格式二:扁平格式

format = "json"
verbosity = 3
rotation = true
file_path = "/var/log/app.log"
max_size_mb = 100
max_backups = 10
max_age = 30
compress = true
vmodule = "eth/*=5,p2p=4"

使用配置:

package main

import logko "github.com/koku-web3/logko"

func main() {
    cfg, err := logko.LoadFromTOML("config.toml")
    if err != nil {
        panic(err)
    }

    if err := logko.Setup(cfg); err != nil {
        panic(err)
    }

    logko.Info("Application started")
}

简化用法(推荐):使用 SetupFromTOML 一行代码搞定:

package main

import logko "github.com/koku-web3/logko"

func main() {
    // 一行代码加载配置并初始化
    if err := logko.SetupFromTOML("config.toml"); err != nil {
        panic(err)
    }

    // 还可以用选项覆盖部分配置
    // logko.MustSetupFromTOML("config.toml", logko.WithVerbosity(5))

    logko.Info("Application started")
}
方式二:代码配置
package main

import logko "github.com/koku-web3/logko"

func main() {
    if err := logko.Setup(&logko.Config{
        Format:    "json",
        Verbosity: 3,
        FilePath:  "/var/log/app.log",
        Rotation:  true,
        MaxSizeMB: 100,
        MaxBackups: 10,
        MaxAge:    30,
        Compress:  true,
    }); err != nil {
        panic(err)
    }

    logko.Info("Application started")
}
方式三:函数式选项
package main

import logko "github.com/koku-web3/logko"

func main() {
    logko.Setup(nil,
        logko.WithFormat("json"),
        logko.WithVerbosity(4),
        logko.WithFilePath("/var/log/app.log"),
        logko.WithRotation(),
    )

    logko.Info("Application started")
}
方式四:混合使用
package main

import logko "github.com/koku-web3/logko"

func main() {
    // 从配置文件加载
    cfg, _ := logko.LoadFromTOML("config.toml")

    // 使用选项覆盖部分配置
    logko.Setup(cfg,
        logko.WithVerbosity(5),
    )

    logko.Info("Application started")
}

日志级别

级别 说明
Trace -8 最详细级别
Debug -4 调试信息
Info 0 一般信息
Warn 4 警告信息
Error 8 错误信息
Crit 12 严重错误,记录后程序退出

Verbosity 参数映射:

Verbosity 对应级别
0 Silent (静默)
1 Error
2 Warn
3 Info (默认)
4 Debug
5 Trace

日志格式

JSON 格式
{"t":"2026-08-02T15:19:03.851975+08:00","lvl":"info","msg":"test message","key":"value"}
Logfmt 格式
t=2026-08-02T15:19:03+08:00 lvl=info msg="test message" key=value
Terminal 格式
[INFO ] [15:19:03] test message                        key=value

日志轮转配置

参数 说明 默认值
FilePath 日志文件路径 -
Rotation 是否启用轮转 false
MaxSizeMB 单个文件最大 MB 数 100
MaxBackups 最大备份文件数 10
MaxAge 文件保留天数 30
Compress 是否压缩历史日志 false

Vmodule 模块过滤

使用 vmodule 可以对不同模块设置不同的日志级别:

logko.Setup(&logko.Config{
    Vmodule: "eth/*=5,p2p=4,chain=3",
})

语法: pattern=level,pattern=level,...

  • eth/*=5: eth 目录下所有文件使用 trace 级别
  • p2p=4: p2p 模块使用 debug 级别
  • chain=3: chain 模块使用 info 级别

使用日志

基本用法
logko.Trace("trace message")
logko.Debug("debug message")
logko.Info("info message")
logko.Warn("warning message")
logko.Error("error message")
带上下文
logko.Info("user logged in", "user_id", 123, "ip", "192.168.1.1")
创建子 Logger
logger := logko.New("module", "auth")
logger.Info("user logged in", "user_id", 123)
检查级别是否启用
if logko.Root().Enabled(ctx, logko.LevelDebug) {
    logko.Debug("expensive debug info")
}

配置选项

选项函数 说明
WithFilePath(path) 设置日志文件路径
WithRotation() 启用日志轮转
WithMaxSizeMB(size) 设置单文件最大 MB
WithMaxBackups(n) 设置最大备份数
WithMaxAge(days) 设置文件保留天数
WithCompress() 启用日志压缩
WithFormat(format) 设置输出格式 (json/logfmt/terminal)
WithVerbosity(level) 设置日志级别
WithVmodule(vmodule) 设置模块过滤规则
WithJSONFormat() 快捷方式:设置为 JSON 格式
WithLogfmtFormat() 快捷方式:设置为 logfmt 格式
WithTerminalFormat() 快捷方式:设置为终端格式

常用开发命令

# 编译检查(验证代码无语法/类型错误)
go build ./...

# 深度检查(比编译更严格的静态分析)
go vet ./...

# 运行所有测试
go test ./...

# 运行测试(带详细输出)
go test ./... -v

# 运行测试(显示覆盖率)
go test ./... -cover

# 检查代码格式
gofmt -l .

# 格式化代码
gofmt -w .

# 清理依赖(添加缺失,移除未使用)
go mod tidy

路径通配符说明:

符号 含义
. 当前目录
... 当前目录及所有子目录

例如 go build ./... 会编译当前目录及所有子包。

依赖

  • Go 1.25+
  • github.com/BurntSushi/toml (配置解析)
  • github.com/mattn/go-colorable (彩色终端)
  • github.com/mattn/go-isatty (终端检测)
  • gopkg.in/natefinch/lumberjack.v2 (日志轮转)
  • github.com/holiman/uint256 (可选,用于特殊类型格式化)

License

MIT

Documentation

Index

Constants

View Source
const (
	LevelTrace slog.Level = -8
	LevelDebug            = slog.LevelDebug
	LevelInfo             = slog.LevelInfo
	LevelWarn             = slog.LevelWarn
	LevelError            = slog.LevelError
	LevelCrit  slog.Level = 12

	// for backward-compatibility
	LvlTrace = LevelTrace
	LvlInfo  = LevelInfo
	LvlDebug = LevelDebug
)

Variables

This section is empty.

Functions

func ApplyOptions

func ApplyOptions(cfg *Config, opts ...Option)

ApplyOptions 将多个选项应用到配置

func Crit

func Crit(msg string, ctx ...interface{})

Crit is a convenient alias for Root().Crit

Log a message at the crit level with context key/value pairs, and then exit.

Usage Examples

log.Crit("msg")
log.Crit("msg", "key1", val1)
log.Crit("msg", "key1", val1, "key2", val2)

func Debug

func Debug(msg string, ctx ...interface{})

Debug is a convenient alias for Root().Debug

Log a message at the debug level with context key/value pairs

Usage Examples

log.Debug("msg")
log.Debug("msg", "key1", val1)
log.Debug("msg", "key1", val1, "key2", val2)

func DiscardHandler

func DiscardHandler() slog.Handler

DiscardHandler returns a no-op handler

func Error

func Error(msg string, ctx ...interface{})

Error is a convenient alias for Root().Error

Log a message at the error level with context key/value pairs

Usage Examples

log.Error("msg")
log.Error("msg", "key1", val1)
log.Error("msg", "key1", val1, "key2", val2)

func FormatLogfmtUint64

func FormatLogfmtUint64(n uint64) string

FormatLogfmtUint64 formats n with thousand separators.

func FormatSlogValue

func FormatSlogValue(v slog.Value, tmp []byte) (result []byte)

FormatSlogValue formats a slog.Value for serialization to terminal.

func FromLegacyLevel

func FromLegacyLevel(lvl int) slog.Level

FromLegacyLevel converts from old Geth verbosity level constants to levels defined by slog

func Info

func Info(msg string, ctx ...interface{})

Info is a convenient alias for Root().Info

Log a message at the info level with context key/value pairs

Usage Examples

log.Info("msg")
log.Info("msg", "key1", val1)
log.Info("msg", "key1", val1, "key2", val2)

func JSONHandler

func JSONHandler(wr io.Writer) slog.Handler

JSONHandler returns a handler which prints records in JSON format.

func JSONHandlerWithLevel

func JSONHandlerWithLevel(wr io.Writer, level slog.Level) slog.Handler

JSONHandlerWithLevel returns a handler which prints records in JSON format that are less than or equal to the specified verbosity level.

func LevelAlignedString

func LevelAlignedString(l slog.Level) string

LevelAlignedString returns a 5-character string containing the name of a Lvl.

func LevelString

func LevelString(l slog.Level) string

LevelString returns a string containing the name of a Lvl.

func LogfmtHandler

func LogfmtHandler(wr io.Writer) slog.Handler

LogfmtHandler returns a handler which prints records in logfmt format, an easy machine-parseable but human-readable format for key/value pairs.

For more details see: http://godoc.org/github.com/kr/logfmt

func LogfmtHandlerWithLevel

func LogfmtHandlerWithLevel(wr io.Writer, level slog.Level) slog.Handler

LogfmtHandlerWithLevel returns the same handler as LogfmtHandler but it only outputs records which are less than or equal to the specified verbosity level.

func MustSetup

func MustSetup(cfg *Config, opts ...Option)

MustSetup 初始化日志,失败则 panic

func MustSetupFromTOML

func MustSetupFromTOML(path string, opts ...Option)

MustSetupFromTOML 从 TOML 文件加载配置并初始化日志,失败则 panic

func SetDefault

func SetDefault(l Logger)

SetDefault sets the default global logger

func Setup

func Setup(cfg *Config, opts ...Option) error

Setup 使用配置和选项初始化日志 如果 cfg 为 nil,则使用默认配置

func SetupFromTOML

func SetupFromTOML(path string, opts ...Option) error

SetupFromTOML 从 TOML 文件加载配置并初始化日志 相当于先调用 LoadFromTOML 再调用 Setup

func Trace

func Trace(msg string, ctx ...interface{})

Trace is a convenient alias for Root().Trace

Log a message at the trace level with context key/value pairs

Usage

log.Trace("msg")
log.Trace("msg", "key1", val1)
log.Trace("msg", "key1", val1, "key2", val2)

func Warn

func Warn(msg string, ctx ...interface{})

Warn is a convenient alias for Root().Warn

Log a message at the warn level with context key/value pairs

Usage Examples

log.Warn("msg")
log.Warn("msg", "key1", val1)
log.Warn("msg", "key1", val1, "key2", val2)

Types

type Config

type Config struct {
	FilePath string // 日志文件路径,为空则不写文件
	Format   string // 日志格式: json, logfmt, terminal (默认)
	Vmodule  string // 模块级别过滤,如: eth/*=5,p2p=4

	MaxSizeMB  int // 单个日志文件最大 MB 数,默认 100
	MaxBackups int // 最大备份文件数,默认 10
	MaxAge     int // 文件最大保存天数,默认 30
	Verbosity  int // 日志级别: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=trace

	Rotation bool // 是否启用日志轮转
	Compress bool // 是否压缩历史日志

}

Config 日志配置选项

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 返回默认配置

func LoadFromBytes

func LoadFromBytes(data []byte) (*Config, error)

LoadFromBytes 从字节 slice 加载配置

func LoadFromFile

func LoadFromFile(path string) (*Config, error)

LoadFromFile 从 TOML 文件加载配置

func LoadFromReader

func LoadFromReader(r io.Reader) (*Config, error)

LoadFromReader 从 io.Reader 加载配置

func LoadFromTOML

func LoadFromTOML(path string) (*Config, error)

LoadFromTOML 从 TOML 文件加载配置 支持两种格式:

  • log 命名空间格式
  • 扁平顶级格式

type GlogHandler

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

GlogHandler is a log handler that mimics the filtering features of Google's glog logger: setting global log levels; overriding with callsite pattern matches; and requesting backtraces at certain positions.

func NewGlogHandler

func NewGlogHandler(h slog.Handler) *GlogHandler

NewGlogHandler creates a new log handler with filtering functionality similar to Google's glog logger. The returned handler implements Handler.

func (*GlogHandler) Enabled

func (h *GlogHandler) Enabled(ctx context.Context, lvl slog.Level) bool

Enabled implements slog.Handler, reporting whether the handler handles records at the given level.

func (*GlogHandler) Handle

func (h *GlogHandler) Handle(_ context.Context, r slog.Record) error

Handle implements slog.Handler, filtering a log record through the global, local and backtrace filters, finally emitting it if either allow it through.

func (*GlogHandler) Verbosity

func (h *GlogHandler) Verbosity(level slog.Level)

Verbosity sets the glog verbosity ceiling. The verbosity of individual packages and source files can be raised using Vmodule.

func (*GlogHandler) Vmodule

func (h *GlogHandler) Vmodule(ruleset string) error

Vmodule sets the glog verbosity pattern.

The syntax of the argument is a comma-separated list of pattern=N, where the pattern is a literal file name or "glob" pattern matching and N is a V level.

For instance:

pattern="gopher.go=3"
 sets the V level to 3 in all Go files named "gopher.go"

pattern="foo=3"
 sets V to 3 in all files of any packages whose import path ends in "foo"

pattern="foo/*=3"
 sets V to 3 in all files of any packages whose import path contains "foo"

func (*GlogHandler) WithAttrs

func (h *GlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler, returning a new Handler whose attributes consist of both the receiver's attributes and the arguments.

func (*GlogHandler) WithGroup

func (h *GlogHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler, returning a new Handler with the given group appended to the receiver's existing groups.

Note, this function is not implemented.

type Logger

type Logger interface {
	// With returns a new Logger that has this logger's attributes plus the given attributes
	With(ctx ...interface{}) Logger

	// New returns a new Logger that has this logger's attributes plus the given attributes. Identical to 'With'.
	New(ctx ...interface{}) Logger

	// Log logs a message at the specified level with context key/value pairs
	Log(level slog.Level, msg string, ctx ...interface{})

	// Trace log a message at the trace level with context key/value pairs
	Trace(msg string, ctx ...interface{})

	// Debug logs a message at the debug level with context key/value pairs
	Debug(msg string, ctx ...interface{})

	// Info logs a message at the info level with context key/value pairs
	Info(msg string, ctx ...interface{})

	// Warn logs a message at the warn level with context key/value pairs
	Warn(msg string, ctx ...interface{})

	// Error logs a message at the error level with context key/value pairs
	Error(msg string, ctx ...interface{})

	// Crit logs a message at the crit level with context key/value pairs, and exits
	Crit(msg string, ctx ...interface{})

	// Write logs a message at the specified level
	Write(level slog.Level, msg string, attrs ...any)

	// Enabled reports whether l emits log records at the given context and level.
	Enabled(ctx context.Context, level slog.Level) bool

	// Handler returns the underlying handler of the inner logger.
	Handler() slog.Handler
}

A Logger writes key/value pairs to a Handler

func New

func New(ctx ...interface{}) Logger

New returns a new logger with the given context. New is a convenient alias for Root().New

func NewLogger

func NewLogger(h slog.Handler) Logger

NewLogger returns a logger with the specified handler set

func Root

func Root() Logger

Root returns the root logger

type Option

type Option func(*Config)

Option 配置选项函数类型,用于函数式选项模式

func WithCompress

func WithCompress() Option

WithCompress 启用日志文件压缩

func WithFilePath

func WithFilePath(path string) Option

WithFilePath 设置日志文件路径

func WithFormat

func WithFormat(format string) Option

WithFormat 设置日志格式 (json, logfmt, terminal)

func WithJSONFormat

func WithJSONFormat() Option

WithJSONFormat 设置为 JSON 格式输出

func WithLogfmtFormat

func WithLogfmtFormat() Option

WithLogfmtFormat 设置为 logfmt 格式输出

func WithMaxAge

func WithMaxAge(days int) Option

WithMaxAge 设置文件最大保存天数

func WithMaxBackups

func WithMaxBackups(n int) Option

WithMaxBackups 设置最大备份文件数

func WithMaxSizeMB

func WithMaxSizeMB(size int) Option

WithMaxSizeMB 设置单个日志文件最大 MB 数

func WithRotation

func WithRotation() Option

WithRotation 启用日志轮转

func WithTerminalFormat

func WithTerminalFormat() Option

WithTerminalFormat 设置为终端格式输出(默认)

func WithVerbosity

func WithVerbosity(level int) Option

WithVerbosity 设置日志级别 (0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=trace)

func WithVmodule

func WithVmodule(vmodule string) Option

WithVmodule 设置模块级别过滤

type TerminalHandler

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

func NewTerminalHandler

func NewTerminalHandler(wr io.Writer, useColor bool) *TerminalHandler

NewTerminalHandler returns a handler which formats log records at all levels optimized for human readability on a terminal with color-coded level output and terser human friendly timestamp. This format should only be used for interactive programs or while developing.

[LEVEL] [TIME] MESSAGE key=value key=value ...

Example:

[DBUG] [May 16 20:58:45] remove route ns=haproxy addr=127.0.0.1:50002

func NewTerminalHandlerWithLevel

func NewTerminalHandlerWithLevel(wr io.Writer, lvl slog.Level, useColor bool) *TerminalHandler

NewTerminalHandlerWithLevel returns the same handler as NewTerminalHandler but only outputs records which are less than or equal to the specified verbosity level.

func (*TerminalHandler) Enabled

func (h *TerminalHandler) Enabled(_ context.Context, level slog.Level) bool

func (*TerminalHandler) Handle

func (h *TerminalHandler) Handle(_ context.Context, r slog.Record) error

func (*TerminalHandler) ResetFieldPadding

func (h *TerminalHandler) ResetFieldPadding()

ResetFieldPadding zeroes the field-padding for all attribute pairs.

func (*TerminalHandler) WithAttrs

func (h *TerminalHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*TerminalHandler) WithGroup

func (h *TerminalHandler) WithGroup(name string) slog.Handler

type TerminalStringer

type TerminalStringer interface {
	TerminalString() string
}

TerminalStringer is an analogous interface to the stdlib stringer, allowing own types to have custom shortened serialization formats when printed to the screen.

Jump to

Keyboard shortcuts

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