logs

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2023 License: MIT Imports: 19 Imported by: 2

README

code.gopub.tech/logs

sync-to-gitee test codecov Go Report Card Go Reference FOSSA Status

Logger 前端

全局函数
基本用法
import	"code.gopub.tech/logs"

logs.Trace(ctx context.Context, format string, args ...any)
logs.Debug()
logs.Info()
logs.Notice()
logs.Warn()
logs.Error()
logs.Panic() // 输出日志后抛出 panic
logs.Fatal() // 输出日志后终止程序 os.Exit
高级用法
// [kv]
// 在 Logger 上关联 kv
// With() returns a Logger
logs.With(key, value).Info(ctx, "xxx") // key=value xxx

// 在 ctx 上关联 kv
ctx = kv.Add(ctx, key, value)
logs.Info(ctx, "xxx")// key=value xxx

// [leven enable]
// 判断日志级别
if logs.Enable(logs.LevelDebug) {
	logs.Debug(ctx, "debug log")
}

// [marshal args as json]
// 输出参数为 json 格式
type MyStruct struct{
	// ...
}
var myStruct MyStruct

// 不使用 arg.JSON() 的不推荐写法
b,_ := json.Marshal(myStruct) // 无论日志级别配置为多高 都会执行这行 浪费性能
lgos.Debug(ctx,"my struct json = %s", b)

// 不使用 arg.JSON() 的正确写法
if logs.Enable(logs.LevelDebug) {
	b,_ := json.Marshal(myStruct) // 已经判断日志级别
	lgos.Debug(ctx,"my struct json = %s", b)
}

// 使用 arg.JSON() 的简便写法
// 借助 arg.JSON() 包装,无需使用 Enable 判断,会自动延迟到 toString 时才调用 json.Marshal
logs.Debug(ctx, "my struct json = %v", arg.JSON(myStruct))
// 注意应当使用 %v, %s 等格式化动词, 而不能使用 %#v, 否则会打印出 arg.JSON 返回的内部包装对象 &arg.Arg{data:xxx}
设置全局默认 Logger
logs.SetDefault(Logger)
Logger 接口
type Logger interface {
	With(key, value any) Logger
	Trace(ctx context.Context, format string, args ...any)
	Debug(ctx context.Context, format string, args ...any)
	Info(ctx context.Context, format string, args ...any)
	Notice(ctx context.Context, format string, args ...any)
	Warn(ctx context.Context, format string, args ...any)
	Error(ctx context.Context, format string, args ...any)
	Panic(ctx context.Context, format string, args ...any)
	Fatal(ctx context.Context, format string, args ...any)
	// Log 打印日志接口
	// callDepth: 0=caller position
	Log(ctx context.Context, callDepth int, level Level, format string, args ...any)
	Enable(level Level) bool
	EnableDepth(level Level, callDepth int) bool
}
内置默认的 Logger 实现
logs.NewLogger(handler) // 需要传入 handler 用于日志后端处理

Handler 后端

Handler 接口
type Handler interface {
	Output(Record)
	Enable(level Level, pc uintptr) bool
}
内置默认的 Handler 实现
// create a default handler.
// 默认处理器, 输出到 stderr, 自动检测颜色, Info 级别.
logs.NewHandler(opts...)
// Options:
logs.WithWriter(io.Writer)     // 输出目的地 默认 stderr
logs.WithFile(fileName string) // 自动轮转日志文件
logs.WithColor()               // 强制开启颜色
logs.WithNoColor()             // 强制关闭颜色
logs.WithName(loggerName)      // 设置logger名称 默认为空则使用日志打印处的包名
logs.WithLevel(level Level)    // 默认 Info 级别
logs.WithLevels(LevelProvider) // 为不同包名配置不同级别
logs.WithFormatFun(fn)         // 自定义日志格式
logs.WithJSON()                // json 格式输出日志

log/slog 兼容

	import "code.gopub.tech/logs"
	// use logs.Default()
	slog.SetDefault(slog.New(logs.NewSlogHandler()))
	slog.Info("Hello, Log", "key", "value")
	// ...
	h := logs.NewHandler(logs.WithWriter(os.Stderr), logs.WithJSON())
	logger := logs.NewLogger(h)
	sh := logs.NewSlogHandler().SetLogger(logger)
	slog.SetDefault(slog.New(sh))
	slog.Info("JSON Log")

License

FOSSA Status

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var CtxKeyRecord ctxKeyRecord

Functions

func Debug

func Debug(ctx context.Context, format string, args ...any)

func Enable added in v0.0.4

func Enable(level Level) bool

func Error

func Error(ctx context.Context, format string, args ...any)

func Fatal

func Fatal(ctx context.Context, format string, args ...any)

func Info

func Info(ctx context.Context, format string, args ...any)

func Log

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

func Notice

func Notice(ctx context.Context, format string, args ...any)

func Panic

func Panic(ctx context.Context, format string, args ...any)

func SetDefault

func SetDefault(l Logger)

func Trace

func Trace(ctx context.Context, format string, args ...any)

func Warn

func Warn(ctx context.Context, format string, args ...any)

Types

type FormatFun added in v0.0.4

type FormatFun func(*Record) string

FormatFun format a log Record to string. the return string should ends with a '\n' as usual.

格式化一条日志记录. 通常, 返回的字符串应当以换行 '\n' 符结尾.

type Handler

type Handler interface {
	// Output output the log Record.
	//
	// 输出日志.
	Output(Record)
	Enable(level Level, pc uintptr) bool
}

Handler handles log record, output it to somewhere.

处理日志的接口.

func CombineHandlers added in v0.0.2

func CombineHandlers(h ...Handler) Handler

func NewHandler

func NewHandler(opt ...Option) Handler

NewHandler create a new Handler with Info level by default.

创建一个日志处理器, 默认日志级别是 Info.

type Handlers added in v0.0.2

type Handlers []Handler

func (Handlers) Enable added in v0.0.4

func (s Handlers) Enable(level Level, pc uintptr) bool

func (Handlers) Output added in v0.0.2

func (s Handlers) Output(r Record)

type Level

type Level int
const (
	LevelTrace  Level = (iota - 2) * 10 // 用于[追踪]执行路径 -20
	LevelDebug                          // 用于[调试]输出    -10
	LevelInfo                           // 用于[信息]输出    0=默认值
	LevelNotice                         // 用于[注意]引起注视 10
	LevelWarn                           // 用于[警告]提醒    20
	LevelError                          // 用于[错误]提醒    30
	LevelPanic                          // 用于[恐慌]出错提醒并抛出 panic 40
	LevelFatal                          // 用于[致命]出错提醒并终止程序    50
)
const (
	LevelALL Level = math.MinInt // [所有]
	LevelOFF Level = math.MaxInt // [关闭]
)

func (Level) String

func (l Level) String() string

type LevelProvider added in v0.0.2

type LevelProvider interface {
	Search(loggerName string) Level
}

type Logger

type Logger interface {
	With(key, value any) Logger
	Trace(ctx context.Context, format string, args ...any)
	Debug(ctx context.Context, format string, args ...any)
	Info(ctx context.Context, format string, args ...any)
	Notice(ctx context.Context, format string, args ...any)
	Warn(ctx context.Context, format string, args ...any)
	Error(ctx context.Context, format string, args ...any)
	Panic(ctx context.Context, format string, args ...any)
	Fatal(ctx context.Context, format string, args ...any)
	// Log 打印日志接口
	// callDepth: 0=caller position
	Log(ctx context.Context, callDepth int, level Level, format string, args ...any)
	Enable(level Level) bool
	EnableDepth(level Level, callDepth int) bool
}

func Default

func Default() Logger

func NewLogger

func NewLogger(h Handler) Logger

func With

func With(key, value any) Logger

type Option

type Option func(*handler)

Option Handler options.

日志处理器的配置选项.

func WithColor added in v0.0.2

func WithColor() Option

WithColor enable output color.

彩色输出日志.

func WithFile added in v0.0.2

func WithFile(name string) Option

WithFile set the log output to a file.

设置输出目的地为文件,日志文件自动轮转.

func WithFormat added in v0.0.2

func WithFormat(format string) Option

WithFormat set the log format. [experimental] implements by regular expressions, performance may not be very good.

[实验性]设置日志格式. 使用正则表达式实现, 性能可能不是很好.

placeholder     args        describe
%n or %N        N/A       print a newline
%l or %level    (-?\d+)?  print the log level; the args set print width
%F or %FILE     N/A       print the file name
%File or %file
%L              N/A       print the line number
%fun            N/A       print the function name
%P / %P[Kk][Gg] N/A       print the package name
%path           N/A       print the file path
%T         (date-format)  print time with date-format
%t           ([num]?s)?   print timestampt
%X          (key-name)    print the Attr
%X             N/A        print all Attr
%Attr {KV}{prefix}{jointer}{suffix} range print Attr
   %K                     print the key
   %V or %Vjson           print the value or json format of the value
%M or %m       N/A        print the log message
{left}%or{right}          if left is empty then print right
%Q or %q       (str)      print the quote form for str

JSON format:
{"ts":%t(ns),"time":%Q(%T(2006-01-02T15:04:05.000000000-07:00)),"level":%Q(%level),
"pkg":%Q(%Pkg),"fun":%Q(%fun),"path":%Q(%path),"file":%Q(%F),"line":%L,
%Attr{%Q(%K):%Vjson}{}{,}{,}"msg":%Q(%m)}%n

String format:
%T(2006-01-02T15:04:05.000-07:00) %level(-5) {%Pkg}%or{?}.{%fun}%or{?} {%path}%or{?}/{%F}%or{???}:%L %X %m%n

func WithFormatFun added in v0.0.4

func WithFormatFun(fn FormatFun) Option

WithFormatFun set the format function.

设置格式化日志函数.

func WithJSON added in v0.0.2

func WithJSON() Option

WithJSON output the log as json format.

JSON 格式输出.

func WithJson

func WithJson(b bool) Option

WithJson is a option. output the log as json format if this option is true.

是否以 json 格式输出.

@deprecated use WithJSON instand.

func WithLevel

func WithLevel(level Level) Option

WithLevel set the default log level. If you want set deffirent level for diffenrent package, consider use `WithLevels`

设置默认的日志输出级别. 如需为不同包设置不同的日志级别, 请参见 `WithLevels` 选项.

func WithLevels

func WithLevels(levelConfig LevelProvider) Option

WithLevels set log level by package name. if this option is set, the `WithLevel` option would be ignored.

设置不同包的日志级别. 如果设置了该选项,`WithLevel` 选项将被忽略.

@param LevelProvider is a interface, which has a method called `Search`. It returns a log level for a given input package name. 参数 LevelProvider 是一个接口, 为指定的包名返回日志级别.

@see 参见 [trie.Tree](pkg/trie/tree.go) 前缀树

func WithName added in v0.0.4

func WithName(name string) Option

WithName set the logger name.

设置 logger 名称.

func WithNoColor added in v0.0.2

func WithNoColor() Option

WithNoColor disable output color.

禁用日志颜色.

func WithWriter

func WithWriter(w io.Writer) Option

WithWriter is a option that set the log output.

设置日志输出目的地.

type Record

type Record struct {
	Ctx    context.Context
	Time   time.Time
	Level  Level
	PC     uintptr // see pkg/caller package caller.GetFrame 获取调用栈
	Format string  // message format
	Args   []any   // message args
	Attr   []any   // key-value pair of this log. With+ctx 上的 kv
}

Record is log record.

一条具体的日志.

type SlogHandler added in v0.0.5

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

SlogHandler 实现 slog.Handler 适配 logs

import "code.gopub.tech/logs"
// use logs.Default()
slog.SetDefault(slog.New(logs.NewSlogHandler()))
slog.Info("Hello, Log", "key", "value")
// ...
h := logs.NewHandler(logs.WithWriter(os.Stderr), logs.WithJSON())
logger := logs.NewLogger(h)
sh := logs.NewSlogHandler().SetLogger(logger)
slog.SetDefault(slog.New(sh))
Example
slog.SetDefault(slog.New(NewSlogHandler()))

// key=value Hello, World
slog.Info("Hello, World", "key", "value")

// k1=v1 group=[k2=true k3=false name=[k=v]] TextMsg
slog.With("k1", "v1").WithGroup("group").With("k2", true).Info("TextMsg", "k3", false, slog.Group("name", "k", "v"))

slog.SetDefault(slog.New(NewSlogHandler().SetLogger(NewLogger(NewHandler(WithWriter(os.Stderr), WithJSON())))))

// {"group":{"k2":true,"name":{"a":"b"}},"msg":"JSONMsg"}
slog.Default().WithGroup("group").With("k2", true).Info("JSONMsg", slog.Group("name", "a", "b"))

// {"a":"b","G":{"c":"d","H":{"e":"f"}},"msg":"msg"}
slog.With("a", "b").WithGroup("G").With("c", "d").WithGroup("H").Info("msg", "e", "f")
// {"a":"b","G":{"c":"d"},"msg":"msg"}
slog.With("a", "b").WithGroup("G").With("c", "d").WithGroup("H").Info("msg")
Output:

func NewSlogHandler added in v0.0.5

func NewSlogHandler() *SlogHandler

NewSlogHandler 新建一个实现了 slog.Handler 的实例

func (*SlogHandler) Enabled added in v0.0.5

func (s *SlogHandler) Enabled(_ context.Context, l slog.Level) bool

Enabled implements slog.Handler.

func (*SlogHandler) GetLogger added in v0.0.5

func (s *SlogHandler) GetLogger() Logger

GetLogger 获取 SlogHandler 上关联的 Logger (如果已有 Attrs 也会一并返回,就像在 Logger 上调用了 With 一样)

func (*SlogHandler) Handle added in v0.0.5

func (s *SlogHandler) Handle(ctx context.Context, r slog.Record) error

Handle implements slog.Handler.

func (*SlogHandler) SetLogger added in v0.0.5

func (s *SlogHandler) SetLogger(logger Logger) *SlogHandler

SetLogger 设置关联的 Logger

func (*SlogHandler) WithAttrs added in v0.0.5

func (s *SlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.

func (*SlogHandler) WithGroup added in v0.0.5

func (s *SlogHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler.

Directories

Path Synopsis
pkg
arg
kv

Jump to

Keyboard shortcuts

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