package slog
import "log/slog"
Package slog 提供结构化日志, 其中日志记录包含一条消息、 一个严重级别,以及以键值对形式 表达的各种其他属性。
它定义了一个类型 Logger, 该类型提供了若干方法(例如 Logger.Info 和 Logger.Error) 用于报告关注的事件。
每个 Logger 都与一个 Handler 相关联。 Logger 的输出方法会根据方法参数创建一个 Record, 并将其传递给 Handler,由后者决定如何处理它。 通过顶层函数(例如 Info 和 Error)可以访问一个默认的 Logger, 这些顶层函数会调用相应的 Logger 方法。
一条日志记录由时间、级别、消息以及一组键值对组成, 其中键是字符串,值可以是任意类型。 例如,
slog.Info("hello", "count", 3)
会创建一条记录,其中包含调用时的时间、 Info 级别、消息 "hello",以及一个 键为 "count"、值为 3 的键值对。
顶层函数 Info 会调用默认 Logger 上的 Logger.Info 方法。 除了 Logger.Info 之外,还有用于 Debug、Warn 和 Error 级别的方法。 除了这些用于常见级别的便捷方法之外, 还有一个 Logger.Log 方法,它将级别作为参数。 上述每个方法都有一个对应的、使用默认 logger 的顶层函数。
默认 handler 会将日志记录的消息、时间、级别和属性格式化为 一个字符串,并将其传递给 log 包。
2022/11/08 15:28:26 INFO hello count=3
若要对输出格式进行更多控制,可以创建一个使用不同 handler 的 logger。 下面的语句使用 New 创建一个带有 TextHandler 的新 logger, 该 handler 会将结构化记录以文本形式写入标准错误:
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
TextHandler 的输出是一系列 key=value 键值对,便于机器轻松且无歧义地 解析。下面的语句:
logger.Info("hello", "count", 3)
会产生如下输出:
time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3
该包还提供了 JSONHandler,其输出是以行分隔的 JSON:
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("hello", "count", 3)
会产生如下输出:
{"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3}
TextHandler 和 JSONHandler 都可以使用 HandlerOptions 进行配置。 其中包含用于设置最低级别(参见下文“级别”一节)、 显示日志调用的源文件和行号,以及 在记录属性前修改属性的选项。
使用以下方式将某个 logger 设为默认:
slog.SetDefault(logger)
会使诸如 Info 之类的顶层函数使用它。 SetDefault 还会更新 log 包所使用的默认 logger, 这样,使用 log.Printf 及相关函数的现有应用程序 无需重写即可将日志记录发送到该 logger 的 handler。
有些属性在许多日志调用中都很常见。 例如,你可能希望将某个服务器请求的 URL 或跟踪标识符 包含在由该请求产生的所有日志事件中。 与其在每次日志调用中重复该属性,你可以使用 Logger.With 构造一个包含这些属性的新 Logger:
logger2 := logger.With("url", r.URL)
With 的参数与 Logger.Info 中使用的键值对相同。 其结果是一个新 Logger,它与原 Logger 具有相同的 handler,但会额外 包含将出现在每次调用输出中的属性。
级别
Level 是一个整数,表示日志事件的重要性或严重程度。 级别越高,事件越严重。 该包为最常见的级别定义了常量, 但任何 int 都可以用作级别。
在应用程序中,你可能希望只记录达到某个级别或更高级别的消息。 一种常见的配置是记录 Info 或更高级别的消息, 在需要之前抑制 debug 日志。 内置 handler 可以通过设置 HandlerOptions.Level 来配置要输出的最低级别。 程序的 `main` 函数通常会这样做。 默认值是 LevelInfo。
将 HandlerOptions.Level 字段设置为一个 Level 值, 会在 handler 的整个生命周期内固定其最低级别。 将其设置为一个 LevelVar 则允许动态地改变级别。 LevelVar 持有一个 Level,并且可以安全地被多个 goroutine 读写。 若要为整个程序动态改变级别,首先初始化 一个全局 LevelVar:
var programLevel = new(slog.LevelVar) // Info by default
然后使用该 LevelVar 构造一个 handler,并将其设为默认:
h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel})
slog.SetDefault(slog.New(h))
现在,程序只需一条语句即可更改其日志级别:
programLevel.Set(slog.LevelDebug)
分组
属性可以被收集到分组中。 分组有一个名称,用于限定其属性名称。 这种限定如何显示取决于 handler。 TextHandler 用一个点分隔分组名称和属性名称。 JSONHandler 将每个分组视为一个单独的 JSON 对象,以分组名称作为键。
使用 Group 根据名称和一组键值对创建一个 Group 属性:
slog.Group("request",
"method", r.Method,
"url", r.URL)
TextHandler 会将该分组显示为
request.method=GET request.url=http://example.com
JSONHandler 会将其显示为
"request":{"method":"GET","url":"http://example.com"}
使用 Logger.WithGroup 可以用一个分组名称限定某个 Logger 的所有输出。 对 Logger 调用 WithGroup 会得到一个新的 Logger,它与原 Logger 具有相同的 Handler,但 其所有属性都由该分组名称限定。
在大型系统中,这有助于防止属性键重复, 因为各个子系统可能会使用相同的键。 为每个子系统传入一个带有各自分组名称的不同 Logger,以便 潜在的重复项得到限定:
logger := slog.Default().With("id", systemID)
parserLogger := logger.WithGroup("parser")
parseInput(input, parserLogger)
当 parseInput 使用 parserLogger 记录日志时,其键将由 "parser" 限定, 因此即使它使用了常见的键 "id",日志行也会具有不同的键。
上下文
有些 handler 可能希望包含调用点处可用的 context.Context 中的信息。 这类信息的一个例子 是在启用跟踪时当前 span 的标识符。
Logger.Log 和 Logger.LogAttrs 方法将 context 作为第一个 参数,它们对应的顶层函数也是如此。
尽管 Logger 上的便捷方法(Info 等)以及 对应的顶层函数不接受 context,但以 "Context" 结尾的替代方法接受。 例如,
slog.InfoContext(ctx, "message")
如果可用,建议向输出方法传入一个 context。
Attr 与 Value
Attr 是一个键值对。Logger 的输出方法既接受 Attr,也接受 交替出现的键和值。语句
slog.Info("hello", slog.Int("count", 3))
的行为与
slog.Info("hello", "count", 3)
相同。
对于常见类型,有 Attr 的便捷构造函数,例如 Int、String 和 Bool, 还有用于构造任意类型 Attr 的函数 Any。
Attr 的值部分是一个称为 Value 的类型。 与 [any] 类似,Value 可以保存任意 Go 值, 但它可以表示典型值(包括所有数字和字符串), 而无需分配内存。
为了获得最高效的日志输出,请使用 Logger.LogAttrs。 它类似于 Logger.Log,但只接受 Attr,而不接受交替的 键和值;这使它也能避免分配内存。
调用
logger.LogAttrs(ctx, slog.LevelInfo, "hello", slog.Int("count", 3))
是实现与
slog.InfoContext(ctx, "hello", "count", 3)
相同输出的最高效方式。
自定义类型的日志行为
如果某个类型实现了 LogValuer 接口,则其 LogValue 方法返回的 Value 会被用于日志记录。你可以借此控制该类型的值 在日志中的呈现方式。例如,你可以对密码等机密信息进行脱敏, 或将结构体的字段收集到一个 Group 中。有关详细信息, 请参见 LogValuer 下的示例。
LogValue 方法可能返回一个本身实现了 LogValuer 的 Value。Value.Resolve 方法会谨慎处理这些情况,避免无限循环和无界递归。 Handler 作者及其他人员可能希望使用 Value.Resolve,而不是直接调用 LogValue。
包装输出方法
logger 函数会对调用栈进行反射,以查找应用程序内日志调用的 文件名和行号。对于包装了 slog 的函数,这可能会产生 错误的源信息。例如,如果你 在文件 mylog.go 中定义了如下函数:
func Infof(logger *slog.Logger, format string, args ...any) {
logger.Info(fmt.Sprintf(format, args...))
}
并在 main.go 中像这样调用它:
Infof(slog.Default(), "hello, %s", "world")
那么 slog 会将源文件报告为 mylog.go,而不是 main.go。
Infof 的正确实现会获取源位置 (pc) 并将其传递给 NewRecord。 包级示例中名为 "wrapping" 的 Infof 函数演示了如何做到这一点。
使用 Record
有时 Handler 需要在将 Record 传递给另一个 Handler 或后端 之前对其进行修改。 Record 包含简单公有字段(例如 Time、Level、Message)和 间接引用状态(例如属性)的隐藏字段的混合体。这 意味着修改 Record 的一个简单副本(例如通过调用 Record.Add 或 Record.AddAttrs 来添加属性) 可能会对原始对象产生意外影响。 在修改 Record 之前,请使用 Record.Clone 创建一个与原对象不共享状态的副本, 或使用 NewRecord 创建一个新的 Record, 并通过 Record.Attrs 遍历旧的 Attrs 来构建其 Attrs。
性能注意事项
如果对应用程序进行性能分析表明日志记录占用了大量时间, 以下建议可能会有所帮助。
如果许多日志行都有一个共同的属性,请使用 Logger.With 创建一个带有 该属性的 Logger。内置 handler 只会在调用 Logger.With 时 对该属性格式化一次。Handler 接口的设计允许进行这种优化, 编写良好的 Handler 应当利用它。
日志调用的参数总是会被求值,即使该日志事件被丢弃。 如果可能,请推迟计算,使其仅在该值确实被记录时才发生。 例如,考虑以下调用
slog.Info("starting request", "url", r.URL.String()) // may compute String unnecessarily
即使 logger 丢弃 Info 级别的事件,URL.String 方法仍会被调用。 相反,请直接传入 URL:
slog.Info("starting request", "url", &r.URL) // calls URL.String only if needed
内置的 TextHandler 会调用其 String 方法,但仅 在该日志事件启用时才会调用。 避免调用 String 还能保留底层值的结构。 例如 JSONHandler 会将解析后 URL 的各组成部分作为 JSON 对象输出。 如果你想避免过早承担 String 调用的开销, 而又不让 handler 可能检查值的结构, 请将该值包装在一个隐藏其 Marshal 方法的 fmt.Stringer 实现中。
你还可以使用 LogValuer 接口来避免在未启用的日志 调用中进行不必要的工作。假设你需要记录某个开销很大的值:
slog.Debug("frobbing", "value", computeExpensiveValue(arg))
即使这一行被禁用,computeExpensiveValue 仍会被调用。 为避免这种情况,请定义一个实现 LogValuer 的类型:
type expensive struct { arg int }
func (e expensive) LogValue() slog.Value {
return slog.AnyValue(computeExpensiveValue(e.arg))
}
然后在日志调用中使用该类型的值:
slog.Debug("frobbing", "value", expensive{arg})
现在,computeExpensiveValue 只会在该行启用时才被调用。
内置 handler 在调用 io.Writer.Write 之前会先获取锁, 以确保一次恰好完整地写入一个 Record。 尽管每条日志记录都有时间戳, 但内置 handler 不会使用该时间对写入的记录进行排序。 用户自定义的 handler 需自行负责加锁和排序。
编写 handler
有关编写自定义 handler 的指南,请参见 https://golang.org/s/slog-handler-guide。
Output: Output:Example (DiscardHandler)
package main
import (
"log/slog"
"os"
)
func main() {
removeTime := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
}
// A slog.TextHandler can output log messages.
logger1 := slog.New(slog.NewTextHandler(
os.Stdout,
&slog.HandlerOptions{ReplaceAttr: removeTime},
))
logger1.Info("message 1")
// A slog.DiscardHandler will discard all messages.
logger2 := slog.New(slog.DiscardHandler)
logger2.Info("message 2")
}
level=INFO msg="message 1"
Example (Wrapping)
package main
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"runtime"
"time"
)
// Infof is an example of a user-defined logging function that wraps slog.
// The log record contains the source position of the caller of Infof.
func Infof(logger *slog.Logger, format string, args ...any) {
if !logger.Enabled(context.Background(), slog.LevelInfo) {
return
}
var pcs [1]uintptr
runtime.Callers(2, pcs[:]) // skip [Callers, Infof]
r := slog.NewRecord(time.Now(), slog.LevelInfo, fmt.Sprintf(format, args...), pcs[0])
_ = logger.Handler().Handle(context.Background(), r)
}
func main() {
replace := func(groups []string, a slog.Attr) slog.Attr {
// Remove time.
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
// Remove the directory from the source's filename.
if a.Key == slog.SourceKey {
source := a.Value.Any().(*slog.Source)
source.File = filepath.Base(source.File)
}
return a
}
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
Infof(logger, "message, %s", "formatted")
}
level=INFO source=example_wrap_test.go:43 msg="message, formatted"
Index
- Constants
- func Debug(msg string, args ...any)
- func DebugContext(ctx context.Context, msg string, args ...any)
- func Error(msg string, args ...any)
- func ErrorContext(ctx context.Context, msg string, args ...any)
- func Info(msg string, args ...any)
- func InfoContext(ctx context.Context, msg string, args ...any)
- func Log(ctx context.Context, level Level, msg string, args ...any)
- func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
- func NewLogLogger(h Handler, level Level) *log.Logger
- func SetDefault(l *Logger)
- func Warn(msg string, args ...any)
- func WarnContext(ctx context.Context, msg string, args ...any)
-
type Attr
- func Any(key string, value any) Attr
- func Bool(key string, v bool) Attr
- func Duration(key string, v time.Duration) Attr
- func Float64(key string, v float64) Attr
- func Group(key string, args ...any) Attr
- func GroupAttrs(key string, attrs ...Attr) Attr
- func Int(key string, value int) Attr
- func Int64(key string, value int64) Attr
- func String(key, value string) Attr
- func Time(key string, v time.Time) Attr
- func Uint64(key string, v uint64) Attr
- func (a Attr) Equal(b Attr) bool
- func (a Attr) String() string
- type Handler
- type HandlerOptions
-
type JSONHandler
- func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler
- func (h *JSONHandler) Enabled(_ context.Context, level Level) bool
- func (h *JSONHandler) Handle(_ context.Context, r Record) error
- func (h *JSONHandler) WithAttrs(attrs []Attr) Handler
- func (h *JSONHandler) WithGroup(name string) Handler
- type Kind
-
type Level
- func SetLogLoggerLevel(level Level) (oldLevel Level)
- func (l Level) AppendText(b []byte) ([]byte, error)
- func (l Level) Level() Level
- func (l Level) MarshalJSON() ([]byte, error)
- func (l Level) MarshalText() ([]byte, error)
- func (l Level) String() string
- func (l *Level) UnmarshalJSON(data []byte) error
- func (l *Level) UnmarshalText(data []byte) error
- type LevelVar
- type Leveler
- type LogValuer
-
type Logger
- func Default() *Logger
- func New(h Handler) *Logger
- func With(args ...any) *Logger
- func (l *Logger) Debug(msg string, args ...any)
- func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Enabled(ctx context.Context, level Level) bool
- func (l *Logger) Error(msg string, args ...any)
- func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Handler() Handler
- func (l *Logger) Info(msg string, args ...any)
- func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)
- func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
- func (l *Logger) Warn(msg string, args ...any)
- func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any)
- func (l *Logger) With(args ...any) *Logger
- func (l *Logger) WithGroup(name string) *Logger
- type MultiHandler
- type Record
- type Source
-
type TextHandler
- func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler
- func (h *TextHandler) Enabled(_ context.Context, level Level) bool
- func (h *TextHandler) Handle(_ context.Context, r Record) error
- func (h *TextHandler) WithAttrs(attrs []Attr) Handler
- func (h *TextHandler) WithGroup(name string) Handler
-
type Value
- func AnyValue(v any) Value
- func BoolValue(v bool) Value
- func DurationValue(v time.Duration) Value
- func Float64Value(v float64) Value
- func GroupValue(as ...Attr) Value
- func Int64Value(v int64) Value
- func IntValue(v int) Value
- func StringValue(value string) Value
- func TimeValue(v time.Time) Value
- func Uint64Value(v uint64) Value
- func (v Value) Any() any
- func (v Value) Bool() bool
- func (v Value) Duration() time.Duration
- func (v Value) Equal(w Value) bool
- func (v Value) Float64() float64
- func (v Value) Group() []Attr
- func (v Value) Int64() int64
- func (v Value) Kind() Kind
- func (v Value) LogValuer() LogValuer
- func (v Value) Resolve() (rv Value)
- func (v Value) String() string
- func (v Value) Time() time.Time
- func (v Value) Uint64() uint64
Examples
- Group
- GroupAttrs
- Handler (LevelHandler)
- HandlerOptions (CustomLevels)
- LogValuer (Group)
- LogValuer (Secret)
- MultiHandler
- SetLogLoggerLevel (Log)
- SetLogLoggerLevel (Slog)
- package (DiscardHandler)
- package (Wrapping)
Constants
const ( // TimeKey 是内置 handler 用于表示日志方法被调用时间的键。 // 关联的 Value 是一个 [time.Time]。 TimeKey = "time" // LevelKey 是内置 handler 用于表示日志调用级别的键。 // 关联的值是一个 [Level]。 LevelKey = "level" // MessageKey 是内置 handler 用于表示日志调用消息的键。 // 关联的值是一个字符串。 MessageKey = "msg" // SourceKey 是内置 handler 用于表示日志调用源文件和行号的键。 // 关联的值是一个 *[Source]。 SourceKey = "source" )
“内置”属性的键。
Functions
func Debug
func Debug(msg string, args ...any)
Debug 在默认 logger 上调用 Logger.Debug。
func DebugContext
func DebugContext(ctx context.Context, msg string, args ...any)
DebugContext 在默认 logger 上调用 Logger.DebugContext。
func Error
func Error(msg string, args ...any)
Error 在默认 logger 上调用 Logger.Error。
func ErrorContext
func ErrorContext(ctx context.Context, msg string, args ...any)
ErrorContext 在默认 logger 上调用 Logger.ErrorContext。
func Info
func Info(msg string, args ...any)
Info 在默认 logger 上调用 Logger.Info。
func InfoContext
func InfoContext(ctx context.Context, msg string, args ...any)
InfoContext 在默认 logger 上调用 Logger.InfoContext。
func Log
func Log(ctx context.Context, level Level, msg string, args ...any)
Log 在默认 logger 上调用 Logger.Log。
func LogAttrs
func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
LogAttrs 在默认 logger 上调用 Logger.LogAttrs。
func NewLogLogger
func NewLogLogger(h Handler, level Level) *log.Logger
NewLogLogger 返回一个新的 log.Logger,使得对其 Output 方法的每次调用 都会将 Record 分派给指定的 handler。该 logger 充当从 较旧的 log API 到较新的结构化日志 handler 的桥梁。
func SetDefault
func SetDefault(l *Logger)
SetDefault 使 l 成为默认的 Logger,供顶层函数 Info、Debug 等 使用。 在此调用之后,log 包默认 Logger 的输出 (如 log.Print 等)将使用 l 的 Handler 记录, 其级别由 SetLogLoggerLevel 控制。
func Warn
func Warn(msg string, args ...any)
Warn 在默认 logger 上调用 Logger.Warn。
func WarnContext
func WarnContext(ctx context.Context, msg string, args ...any)
WarnContext 在默认 logger 上调用 Logger.WarnContext。
Types
type Attr
type Attr struct { Key string Value Value }
Attr 是一个键值对。
func Any
func Any(key string, value any) Attr
Any 返回一个用于所提供值的 Attr。 关于值的处理方式,参见 AnyValue。
func Bool
func Bool(key string, v bool) Attr
Bool 返回一个用于 bool 的 Attr。
func Duration
func Duration(key string, v time.Duration) Attr
Duration 返回一个用于 time.Duration 的 Attr。
func Float64
func Float64(key string, v float64) Attr
Float64 返回一个用于浮点数的 Attr。
func Group
func Group(key string, args ...any) Attr
Group 返回一个用于 Group Value 的 Attr。 第一个参数是键;其余参数 会像 Logger.Log 中那样被转换为 Attr。
使用 Group 可以在日志行中将多个键值对收集到
同一个键下,或作为 LogValue 的结果,
以便将单个值记录为多个 Attr。
Output:Example
package main
import (
"log/slog"
"net/http"
"os"
"time"
)
func main() {
r, _ := http.NewRequest("GET", "localhost", nil)
// ...
logger := slog.New(
slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
},
}),
)
logger.Info("finished",
slog.Group("req",
slog.String("method", r.Method),
slog.String("url", r.URL.String())),
slog.Int("status", http.StatusOK),
slog.Duration("duration", time.Second))
}
level=INFO msg=finished req.method=GET req.url=localhost status=200 duration=1s
func GroupAttrs
func GroupAttrs(key string, attrs ...Attr) Attr
GroupAttrs 返回一个由给定 Attr 组成的 Group Value 的 Attr。
GroupAttrs 是 Group 的更高效版本,
它只接受 Attr 值。
Output:Example
package main
import (
"context"
"log/slog"
"net/http"
"os"
)
func main() {
r, _ := http.NewRequest("POST", "localhost", http.NoBody)
// ...
logger := slog.New(
slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
},
}),
)
// Use []slog.Attr to accumulate attributes.
attrs := []slog.Attr{slog.String("method", r.Method)}
attrs = append(attrs, slog.String("url", r.URL.String()))
if r.Method == "POST" {
attrs = append(attrs, slog.Int("content-length", int(r.ContentLength)))
}
// Group the attributes under a key.
logger.LogAttrs(context.Background(), slog.LevelInfo,
"finished",
slog.Int("status", http.StatusOK),
slog.GroupAttrs("req", attrs...),
)
// Groups with empty keys are inlined.
logger.LogAttrs(context.Background(), slog.LevelInfo,
"finished",
slog.Int("status", http.StatusOK),
slog.GroupAttrs("", attrs...),
)
}
level=INFO msg=finished status=200 req.method=POST req.url=localhost req.content-length=0
level=INFO msg=finished status=200 method=POST url=localhost content-length=0
func Int
func Int(key string, value int) Attr
Int 将 int 转换为 int64,并返回 具有该值的 Attr。
func Int64
func Int64(key string, value int64) Attr
Int64 返回一个用于 int64 的 Attr。
func String
func String(key, value string) Attr
String 返回一个用于字符串值的 Attr。
func Time
func Time(key string, v time.Time) Attr
Time 返回一个用于 time.Time 的 Attr。 它会丢弃单调时钟部分。
func Uint64
func Uint64(key string, v uint64) Attr
Uint64 返回一个用于 uint64 的 Attr。
func (Attr) Equal
func (a Attr) Equal(b Attr) bool
Equal 报告 a 和 b 是否具有相等的键和值。
func (Attr) String
func (a Attr) String() string
type Handler
type Handler interface { // Enabled 报告 handler 是否处理给定级别的记录。 // handler 会忽略级别更低的记录。 // 它会在处理任何参数之前被提前调用, // 以便在日志事件应被丢弃时省去开销。 // 如果从 Logger 方法调用,第一个参数是传递给 // 该方法的 context,若传入 nil 或该方法不接受 context, // 则为 context.Background()。 // 传入 context 是为了让 Enabled 能够使用其值 // 做出判断。 Enabled(context.Context, Level) bool // Handle 处理 Record。 // 它仅在 Enabled 返回 true 时才会被调用。 // Context 参数与 Enabled 的相同。 // 它存在的唯一目的是让 Handler 能够访问 context 的值。 // 取消 context 不应影响记录的处理。 // (除其他事项外,日志消息可能是调试 // 与取消相关问题的必要条件。) // // 产生输出的 Handle 方法应遵守以下规则: // - 如果 r.Time 是零值时间,则忽略时间。 // - 如果 r.PC 为零,则忽略它。 // - Attr 的值应被解析。 // - 如果某个 Attr 的键和值都是零值,则忽略该 Attr。 // 这可以用 attr.Equal(Attr{}) 来判断。 // - 如果某个分组的键为空,则内联该分组的 Attrs。 // - 如果某个分组没有 Attrs(即使它的键非空), // 则忽略它。 // // [Logger] 会丢弃来自 Handle 的任何错误。包装 Handle 方法以 // 处理来自 Handler 的任何错误。 Handle(context.Context, Record) error // WithAttrs 返回一个新的 Handler,其属性由 // 接收者的属性和参数共同组成。 // Handler 拥有该切片:它可以保留、修改或丢弃它。 WithAttrs(attrs []Attr) Handler // WithGroup 返回一个新的 Handler,其中给定的分组被追加到 // 接收者已有的分组之后。 // 所有后续属性的键,无论是由 With 添加还是在 // Record 中添加,都应由该分组名称序列来限定。 // // 这种限定如何发生由 Handler 决定,只要 // 该 Handler 的属性键与具有不同分组名称序列的 // 另一个 Handler 的属性键不同即可。 // // Handler 应将 WithGroup 视为开始一个 Attrs 分组,该分组在 // 日志事件结束时结束。也就是说, // // logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2)) // // 的行为应类似于 // // logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2))) // // 如果名称为空,WithGroup 返回接收者。 WithGroup(name string) Handler }
Handler 处理由 Logger 产生的日志记录。
典型的 handler 可能会将日志记录打印到标准错误, 或将它们写入文件或数据库,或可能用额外的属性 增强它们,并将其传递给另一个 handler。
Handler 的任意方法都可能与自身或其他方法 并发调用。管理这种并发性是 Handler 的 责任。
slog 包的用户不应直接调用 Handler 方法。 而应改用 Logger 的方法。
在实现你自己的 handler 之前,请查阅 https://go.dev/s/slog-handler-guide。
This example shows how to Use a LevelHandler to change the level of an
existing Handler while preserving its other behavior.
This example demonstrates increasing the log level to reduce a logger's
output.
Another typical use would be to decrease the log level (to LevelDebug, say)
during a part of the program that was suspected of containing a bug.
Output:Example (LevelHandler)
package main
import (
"context"
"log/slog"
"os"
)
// A LevelHandler wraps a Handler with an Enabled method
// that returns false for levels below a minimum.
type LevelHandler struct {
level slog.Leveler
handler slog.Handler
}
// NewLevelHandler returns a LevelHandler with the given level.
// All methods except Enabled delegate to h.
func NewLevelHandler(level slog.Leveler, h slog.Handler) *LevelHandler {
// Optimization: avoid chains of LevelHandlers.
if lh, ok := h.(*LevelHandler); ok {
h = lh.Handler()
}
return &LevelHandler{level, h}
}
// Enabled implements Handler.Enabled by reporting whether
// level is at least as large as h's level.
func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool {
return level >= h.level.Level()
}
// Handle implements Handler.Handle.
func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error {
return h.handler.Handle(ctx, r)
}
// WithAttrs implements Handler.WithAttrs.
func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return NewLevelHandler(h.level, h.handler.WithAttrs(attrs))
}
// WithGroup implements Handler.WithGroup.
func (h *LevelHandler) WithGroup(name string) slog.Handler {
return NewLevelHandler(h.level, h.handler.WithGroup(name))
}
// Handler returns the Handler wrapped by h.
func (h *LevelHandler) Handler() slog.Handler {
return h.handler
}
// This example shows how to Use a LevelHandler to change the level of an
// existing Handler while preserving its other behavior.
//
// This example demonstrates increasing the log level to reduce a logger's
// output.
//
// Another typical use would be to decrease the log level (to LevelDebug, say)
// during a part of the program that was suspected of containing a bug.
func main() {
removeTime := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
}
th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: removeTime})
logger := slog.New(NewLevelHandler(slog.LevelWarn, th))
logger.Info("not printed")
logger.Warn("printed")
}
level=WARN msg=printed
var DiscardHandler Handler = discardHandler{}
DiscardHandler 丢弃所有日志输出。 DiscardHandler.Enabled 对所有 Level 都返回 false。
type HandlerOptions
type HandlerOptions struct { // AddSource 使 handler 计算日志语句的源代码位置, // 并在输出中添加一个 SourceKey 属性。 AddSource bool // Level 报告将被记录的最低记录级别。 // handler 会丢弃级别更低的记录。 // 如果 Level 为 nil,则 handler 假定为 LevelInfo。 // handler 会为处理的每条记录调用 Level.Level; // 若要动态调整最低级别,请使用 LevelVar。 Level Leveler // ReplaceAttr 会在每条非分组属性被记录之前调用,以对其进行改写。 // 属性的值已被解析(参见 [Value.Resolve])。 // 如果 ReplaceAttr 返回一个零值 Attr,则该属性会被丢弃。 // // 键为 "time"、"level"、"source" 和 "msg" 的内置属性 // 会被传递给该函数,但 time 为零时会被省略, // 且 AddSource 为 false 时 source 会被省略。 // // 第一个参数是当前打开的、包含该 Attr 的分组列表。 // 不得保留或修改它。ReplaceAttr 从不会为 // Group 属性调用,只会为其内容调用。例如,属性 // 列表 // // Int("a", 1), Group("g", Int("b", 2)), Int("c", 3) // // 会导致以以下参数连续调用 ReplaceAttr: // // nil, Int("a", 1) // []string{"g"}, Int("b", 2) // nil, Int("c", 3) // // ReplaceAttr 可用于更改内置属性的默认键、转换类型 // (例如,将 `time.Time` 替换为自 Unix 纪元以来的整数秒数)、 // 脱敏个人信息,或从输出中移除属性。 ReplaceAttr func(groups []string, a Attr) Attr }
HandlerOptions 是 TextHandler 或 JSONHandler 的选项。
零值 HandlerOptions 完全由默认值组成。
This example demonstrates using custom log levels and custom log level names.
In addition to the default log levels, it introduces Trace, Notice, and
Emergency levels. The ReplaceAttr changes the way levels are printed for both
the standard log levels and the custom log levels.
Output:Example (CustomLevels)
package main
import (
"context"
"log/slog"
"os"
)
func main() {
// Exported constants from a custom logging package.
const (
LevelTrace = slog.Level(-8)
LevelDebug = slog.LevelDebug
LevelInfo = slog.LevelInfo
LevelNotice = slog.Level(2)
LevelWarning = slog.LevelWarn
LevelError = slog.LevelError
LevelEmergency = slog.Level(12)
)
th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
// Set a custom level to show all log output. The default value is
// LevelInfo, which would drop Debug and Trace logs.
Level: LevelTrace,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
// Remove time from the output for predictable test output.
if a.Key == slog.TimeKey {
return slog.Attr{}
}
// Customize the name of the level key and the output string, including
// custom level values.
if a.Key == slog.LevelKey {
// Rename the level key from "level" to "sev".
a.Key = "sev"
// Handle custom level values.
level := a.Value.Any().(slog.Level)
// This could also look up the name from a map or other structure, but
// this demonstrates using a switch statement to rename levels. For
// maximum performance, the string values should be constants, but this
// example uses the raw strings for readability.
switch {
case level < LevelDebug:
a.Value = slog.StringValue("TRACE")
case level < LevelInfo:
a.Value = slog.StringValue("DEBUG")
case level < LevelNotice:
a.Value = slog.StringValue("INFO")
case level < LevelWarning:
a.Value = slog.StringValue("NOTICE")
case level < LevelError:
a.Value = slog.StringValue("WARNING")
case level < LevelEmergency:
a.Value = slog.StringValue("ERROR")
default:
a.Value = slog.StringValue("EMERGENCY")
}
}
return a
},
})
logger := slog.New(th)
ctx := context.Background()
logger.Log(ctx, LevelEmergency, "missing pilots")
logger.Error("failed to start engines", "err", "missing fuel")
logger.Warn("falling back to default value")
logger.Log(ctx, LevelNotice, "all systems are running")
logger.Info("initiating launch")
logger.Debug("starting background job")
logger.Log(ctx, LevelTrace, "button clicked")
}
sev=EMERGENCY msg="missing pilots"
sev=ERROR msg="failed to start engines" err="missing fuel"
sev=WARNING msg="falling back to default value"
sev=NOTICE msg="all systems are running"
sev=INFO msg="initiating launch"
sev=DEBUG msg="starting background job"
sev=TRACE msg="button clicked"
type JSONHandler
type JSONHandler struct { // contains filtered or unexported fields }
JSONHandler 是一个 Handler,它将 Record 以行分隔的 JSON 对象 形式写入 io.Writer。
func NewJSONHandler
func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler
NewJSONHandler 创建一个写入 w 的 JSONHandler, 使用给定的选项。 如果 opts 为 nil,则使用默认选项。
func (*JSONHandler) Enabled
func (h *JSONHandler) Enabled(_ context.Context, level Level) bool
Enabled 报告 handler 是否处理给定级别的记录。 handler 会忽略级别更低的记录。
func (*JSONHandler) Handle
func (h *JSONHandler) Handle(_ context.Context, r Record) error
Handle 将它的参数 Record 格式化为单行 JSON 对象。
如果 Record 的时间为零,则省略时间。 否则,键为 "time", 其值按照 json.Marshal 的方式输出。
级别的键为 "level",其值是调用 Level.String 的结果。
如果设置了 AddSource 选项且源信息可用, 则键为 "source",其值是 Source 类型的记录。
消息的键为 "msg"。
若要修改这些属性或其他属性,或将它们从输出中移除,请使用 HandlerOptions.ReplaceAttr。
值的格式化方式与设置了 SetEscapeHTML(false) 的 encoding/json.Encoder 相同, 但有两个例外。
第一,Value 类型为 error 的 Attr 会通过调用其 Error 方法 格式化为字符串。只有 Attr 中的 error 会得到这种特殊处理, 嵌入在由 encoding/json 包处理的 struct、slice、map 或其他 数据结构中的 error 不会。
第二,编码失败不会导致 Handle 返回错误。 相反,错误消息会被格式化为字符串。
每次调用 Handle 都会导致一次对 io.Writer.Write 的序列化调用。
func (*JSONHandler) WithAttrs
func (h *JSONHandler) WithAttrs(attrs []Attr) Handler
WithAttrs 返回一个新的 JSONHandler,其属性由 h 的属性后跟 attrs 组成。
func (*JSONHandler) WithGroup
func (h *JSONHandler) WithGroup(name string) Handler
type Kind
type Kind int
Kind 是 Value 的种类。
const ( KindAny Kind = iota KindBool KindDuration KindFloat64 KindInt64 KindString KindTime KindUint64 KindGroup KindLogValuer )
func (Kind) String
func (k Kind) String() string
type Level
type Level int
Level 是日志事件的重要性或严重程度。 级别越高,事件越重要或越严重。
const ( LevelDebug Level = -4 LevelInfo Level = 0 LevelWarn Level = 4 LevelError Level = 8 )
常见级别的名称。
级别数字本质上是任意的, 但我们选择它们是为了满足三个约束条件。 任何系统都可以在需要时将它们映射到另一种编号方案。
第一,我们希望默认级别为 Info,由于 Level 是 int,Info 就是 int 的默认值,即零。
第二,我们希望便于使用级别来指定 logger 的详细程度。 由于级别越大意味着事件越严重,接受级别更小(或更负)事件的 logger 意味着更详细的 logger。因此 logger 的详细程度 是事件严重程度的相反数,默认详细程度 0 接受所有 至少与 INFO 同样严重的事件。
第三,我们希望在级别之间留出一些空间,以容纳 那些在级别命名上介于我们之间的方案。例如,Google Cloud Logging 在 Info 和 Warn 之间定义了一个 Notice 级别。由于这类中间 级别很少,数字之间的间隔不必很大。我们的间隔 4 与 OpenTelemetry 的映射一致。将 OpenTelemetry 在 DEBUG、INFO、WARN 和 ERROR 范围内的级别减去 9,即可将其转换为对应的 slog Level 范围。OpenTelemetry 还有 TRACE 和 FATAL 名称,而 slog 没有。但这些 OpenTelemetry 级别仍然可以通过使用适当的整数 表示为 slog Level。
func SetLogLoggerLevel
func SetLogLoggerLevel(level Level) (oldLevel Level)
SetLogLoggerLevel 控制通往 log 包的桥接的级别。
在调用 SetDefault 之前,slog 顶层日志函数会调用默认的 log.Logger。 在该模式下,SetLogLoggerLevel 为这些调用设置最低级别。 默认情况下,最低级别为 Info,因此对 Debug 的调用 (以及更低级别的顶层日志调用) 不会传递给 log.Logger。在调用
slog.SetLogLoggerLevel(slog.LevelDebug)
之后,对 Debug 的调用将被传递给 log.Logger。
在调用 SetDefault 之后,对默认 log.Logger 的调用会被传递给 slog 默认 handler。在该模式下, SetLogLoggerLevel 设置这些调用被记录的级别。 也就是说,在调用
slog.SetLogLoggerLevel(slog.LevelDebug)
之后,对 log.Printf 的调用将导致以 LevelDebug 级别输出。
SetLogLoggerLevel 返回之前的值。
This example shows how to use slog.SetLogLoggerLevel to change the minimal level
of the internal default handler for slog package before calling slog.SetDefault.
Output: This example shows how to use slog.SetLogLoggerLevel to change the minimal level
of the internal writer that uses the custom handler for log package after
calling slog.SetDefault.
Output:Example (Log)
package main
import (
"log"
"log/slog"
"os"
)
func main() {
defer log.SetFlags(log.Flags()) // revert changes after the example
log.SetFlags(0)
defer log.SetOutput(log.Writer()) // revert changes after the example
log.SetOutput(os.Stdout)
// Default logging level is slog.LevelInfo.
log.Print("log debug") // log debug
slog.Debug("debug") // no output
slog.Info("info") // INFO info
// Set the default logging level to slog.LevelDebug.
currentLogLevel := slog.SetLogLoggerLevel(slog.LevelDebug)
defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
log.Print("log debug") // log debug
slog.Debug("debug") // DEBUG debug
slog.Info("info") // INFO info
}
log debug
INFO info
log debug
DEBUG debug
INFO info
Example (Slog)
package main
import (
"log"
"log/slog"
"os"
)
func main() {
// Set the default logging level to slog.LevelError.
currentLogLevel := slog.SetLogLoggerLevel(slog.LevelError)
defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
defer slog.SetDefault(slog.Default()) // revert changes after the example
removeTime := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
}
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: removeTime})))
log.Print("error") // level=ERROR msg=error
}
level=ERROR msg=error
func (Level) AppendText
func (l Level) AppendText(b []byte) ([]byte, error)
AppendText 通过调用 Level.String 来实现 encoding.TextAppender。
func (Level) Level
func (l Level) Level() Level
Level 返回接收者。 它实现 Leveler。
func (Level) MarshalJSON
func (l Level) MarshalJSON() ([]byte, error)
MarshalJSON 通过引用 Level.String 的输出来实现 encoding/json.Marshaler。
func (Level) MarshalText
func (l Level) MarshalText() ([]byte, error)
MarshalText 通过调用 Level.AppendText 来实现 encoding.TextMarshaler。
func (Level) String
func (l Level) String() string
String 返回该级别的名称。 如果该级别有名称,则返回 该名称的大写形式。 如果该级别介于已命名的值之间,则 会在大写名称后附加一个整数。 示例:
LevelWarn.String() => "WARN" (LevelInfo+2).String() => "INFO+2"
func (*Level) UnmarshalJSON
func (l *Level) UnmarshalJSON(data []byte) error
UnmarshalJSON 实现 encoding/json.Unmarshaler 它接受由 Level.MarshalJSON 产生的任何字符串, 忽略大小写。 它还接受会导致输出字符串不同的数字偏移量。 例如,"Error-8" 会被序列化为 "INFO"。
func (*Level) UnmarshalText
func (l *Level) UnmarshalText(data []byte) error
UnmarshalText 实现 encoding.TextUnmarshaler。 它接受由 Level.MarshalText 产生的任何字符串, 忽略大小写。 它还接受会导致输出字符串不同的数字偏移量。 例如,"Error-8" 会被序列化为 "INFO"。
type LevelVar
type LevelVar struct { // contains filtered or unexported fields }
LevelVar 是一个 Level 变量,用于让 Handler 的级别能够 动态变化。 它实现 Leveler 以及一个 Set 方法, 并且可以安全地被多个 goroutine 使用。 零值 LevelVar 对应于 LevelInfo。
func (*LevelVar) AppendText
func (v *LevelVar) AppendText(b []byte) ([]byte, error)
AppendText 通过调用 Level.AppendText 来实现 encoding.TextAppender。
func (*LevelVar) Level
func (v *LevelVar) Level() Level
Level 返回 v 的级别。
func (*LevelVar) MarshalText
func (v *LevelVar) MarshalText() ([]byte, error)
MarshalText 通过调用 LevelVar.AppendText 来实现 encoding.TextMarshaler。
func (*LevelVar) Set
func (v *LevelVar) Set(l Level)
Set 将 v 的级别设置为 l。
func (*LevelVar) String
func (v *LevelVar) String() string
func (*LevelVar) UnmarshalText
func (v *LevelVar) UnmarshalText(data []byte) error
UnmarshalText 通过调用 Level.UnmarshalText 来实现 encoding.TextUnmarshaler。
type Leveler
type Leveler interface { Level() Level }
Leveler 提供一个 Level 值。
由于 Level 本身实现了 Leveler,客户端通常在任何需要 Leveler 的地方 (例如在 HandlerOptions 中)提供 Level 值。 需要动态改变级别的客户端可以提供更复杂的 Leveler 实现,例如 *LevelVar。
type LogValuer
type LogValuer interface { LogValue() Value }
LogValuer 是任何能够将自身转换为用于日志的 Value 的 Go 值。
该机制可用于将昂贵的操作推迟到需要时才执行,
或将单个值展开为一系列组件。
This example demonstrates a Value that replaces itself
with an alternative representation to avoid revealing secrets.
Output:Example (Group)
package main
import "log/slog"
type Name struct {
First, Last string
}
// LogValue implements slog.LogValuer.
// It returns a group containing the fields of
// the Name, so that they appear together in the log output.
func (n Name) LogValue() slog.Value {
return slog.GroupValue(
slog.String("first", n.First),
slog.String("last", n.Last))
}
func main() {
n := Name{"Perry", "Platypus"}
slog.Info("mission accomplished", "agent", n)
// JSON Output would look in part like:
// {
// ...
// "msg": "mission accomplished",
// "agent": {
// "first": "Perry",
// "last": "Platypus"
// }
// }
}
Example (Secret)
package main
import (
"log/slog"
"os"
)
// A token is a secret value that grants permissions.
type Token string
// LogValue implements slog.LogValuer.
// It avoids revealing the token.
func (Token) LogValue() slog.Value {
return slog.StringValue("REDACTED_TOKEN")
}
// This example demonstrates a Value that replaces itself
// with an alternative representation to avoid revealing secrets.
func main() {
t := Token("shhhh!")
removeTime := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
}
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: removeTime}))
logger.Info("permission granted", "user", "Perry", "token", t)
}
level=INFO msg="permission granted" user=Perry token=REDACTED_TOKEN
type Logger
type Logger struct { // contains filtered or unexported fields }
Logger 记录对其 Log、Debug、Info、Warn 和 Error 方法的 每次调用的结构化信息。 对于每次调用,它创建一个 Record 并将其传递给一个 Handler。
若要创建新的 Logger,请调用 New 或以 "With" 开头的 Logger 方法。
func Default
func Default() *Logger
Default 返回默认的 Logger。
func New
func New(h Handler) *Logger
New 使用给定的非 nil Handler 创建一个新的 Logger。
func With
func With(args ...any) *Logger
With 在默认 logger 上调用 Logger.With。
func (*Logger) Debug
func (l *Logger) Debug(msg string, args ...any)
Debug 以 LevelDebug 级别记录日志。
func (*Logger) DebugContext
func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any)
DebugContext 使用给定的 context 以 LevelDebug 级别记录日志。
func (*Logger) Enabled
func (l *Logger) Enabled(ctx context.Context, level Level) bool
Enabled 报告 l 是否在给定的 context 和级别下发出日志记录。
func (*Logger) Error
func (l *Logger) Error(msg string, args ...any)
Error 以 LevelError 级别记录日志。
func (*Logger) ErrorContext
func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any)
ErrorContext 使用给定的 context 以 LevelError 级别记录日志。
func (*Logger) Handler
func (l *Logger) Handler() Handler
Handler 返回 l 的 Handler。
func (*Logger) Info
func (l *Logger) Info(msg string, args ...any)
Info 以 LevelInfo 级别记录日志。
func (*Logger) InfoContext
func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any)
InfoContext 使用给定的 context 以 LevelInfo 级别记录日志。
func (*Logger) Log
func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)
Log 使用当前时间以及给定的级别和消息发出日志记录。 Record 的 Attrs 由 Logger 的属性后跟 args 指定的 Attrs 组成。
属性参数的处理方式如下:
- 如果参数是 Attr,则按原样使用。
- 如果参数是字符串且不是最后一个参数, 则下一个参数被当作值,两者合并 为一个 Attr。
- 否则,该参数被当作键为 "!BADKEY" 的值。
func (*Logger) LogAttrs
func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
LogAttrs 是 Logger.Log 的更高效版本,它只接受 Attrs。
func (*Logger) Warn
func (l *Logger) Warn(msg string, args ...any)
Warn 以 LevelWarn 级别记录日志。
func (*Logger) WarnContext
func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any)
WarnContext 使用给定的 context 以 LevelWarn 级别记录日志。
func (*Logger) With
func (l *Logger) With(args ...any) *Logger
With 返回一个 Logger,它在每次输出操作中都包含给定的属性。 参数会像 Logger.Log 那样被转换为属性。
func (*Logger) WithGroup
func (l *Logger) WithGroup(name string) *Logger
WithGroup 返回一个启动分组的 Logger,前提是 name 非空。 添加到该 Logger 的所有属性的键都将由给定的名称 限定。(这种限定如何发生取决于该 Logger 的 Handler 的 Handler.WithGroup 方法。)
如果 name 为空,WithGroup 返回接收者。
type MultiHandler
type MultiHandler struct { // contains filtered or unexported fields }
MultiHandler 是一个 Handler,它会调用所有给定的 Handler。
它的 Enabled 方法报告是否有任何 handler 的 Enabled 方法返回 true。
它的 Handle、WithAttrs 和 WithGroup 方法会在每个已启用的 handler 上调用相应的方法。
Output:Example
package main
import (
"bytes"
"log/slog"
"os"
)
func main() {
removeTime := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
}
var textBuf, jsonBuf bytes.Buffer
textHandler := slog.NewTextHandler(&textBuf, &slog.HandlerOptions{ReplaceAttr: removeTime})
jsonHandler := slog.NewJSONHandler(&jsonBuf, &slog.HandlerOptions{ReplaceAttr: removeTime})
multiHandler := slog.NewMultiHandler(textHandler, jsonHandler)
logger := slog.New(multiHandler)
logger.Info("login",
slog.String("name", "whoami"),
slog.Int("id", 42),
)
os.Stdout.WriteString(textBuf.String())
os.Stdout.WriteString(jsonBuf.String())
}
level=INFO msg=login name=whoami id=42
{"level":"INFO","msg":"login","name":"whoami","id":42}
func NewMultiHandler
func NewMultiHandler(handlers ...Handler) *MultiHandler
NewMultiHandler 使用给定的 Handler 创建一个 MultiHandler。
func (*MultiHandler) Enabled
func (h *MultiHandler) Enabled(ctx context.Context, l Level) bool
func (*MultiHandler) Handle
func (h *MultiHandler) Handle(ctx context.Context, r Record) error
func (*MultiHandler) WithAttrs
func (h *MultiHandler) WithAttrs(attrs []Attr) Handler
func (*MultiHandler) WithGroup
func (h *MultiHandler) WithGroup(name string) Handler
type Record
type Record struct { // 调用输出方法(Log、Info 等)的时间。 Time time.Time // 日志消息。 Message string // 事件的级别。 Level Level // 构造记录时的程序计数器,由 runtime.Callers 确定。 // 如果为零,则表示没有可用的程序计数器。 // // 该值的唯一有效用途是作为 [runtime.CallersFrames] 的参数。 // 特别是,不得将其传递给 [runtime.FuncForPC]。 PC uintptr // contains filtered or unexported fields }
Record 保存关于日志事件的信息。 Record 的副本共享状态。 在将 Record 的副本分发出去后,不要修改该 Record。 调用 NewRecord 创建新的 Record。 使用 Record.Clone 创建一个不共享状态的副本。
func NewRecord
func NewRecord(t time.Time, level Level, msg string, pc uintptr) Record
NewRecord 根据给定的参数创建一个 Record。 使用 Record.AddAttrs 向 Record 添加属性。
NewRecord 适用于希望将 Handler 作为 后端支持的日志记录 API。
func (*Record) Add
func (r *Record) Add(args ...any)
Add 按照 Logger.Log 中描述的方式将 args 转换为 Attrs, 然后将这些 Attrs 追加到 Record 的 Attrs 列表中。 它会省略空分组。
func (*Record) AddAttrs
func (r *Record) AddAttrs(attrs ...Attr)
AddAttrs 将给定的 Attrs 追加到 Record 的 Attrs 列表中。 它会省略空分组。
func (Record) Attrs
func (r Record) Attrs(f func(Attr) bool)
Attrs 对 Record 中的每个 Attr 调用 f。 如果 f 返回 false,则停止迭代。
func (Record) Clone
func (r Record) Clone() Record
Clone 返回记录的一个不共享状态的副本。 原始记录和副本都可以被修改, 而不会相互干扰。
func (Record) NumAttrs
func (r Record) NumAttrs() int
NumAttrs 返回 Record 中属性的数量。
func (Record) Source
func (r Record) Source() *Source
Source 使用 r 的 PC 为日志事件返回一个新的 Source。 如果 PC 字段为零,意味着创建 Record 时缺少必要信息 或位置不可用,则返回 nil。
type Source
type Source struct { // Function 是包含该源代码行的、以包路径限定的函数名。 // 如果非空,该字符串唯一标识程序中的单个函数。 // 如果未知,则可能是空字符串。 Function string `json:"function"` // File 和 Line 是该源代码行的文件名和行号(从 1 开始)。 // 如果未知,它们可能分别为空字符串和零。 File string `json:"file"` Line int `json:"line"` }
Source 描述一行源代码的位置。
type TextHandler
type TextHandler struct { // contains filtered or unexported fields }
TextHandler 是一个 Handler,它将 Record 以由空格分隔、 并以换行结尾的 key=value 对序列形式写入 io.Writer。
func NewTextHandler
func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler
NewTextHandler 创建一个写入 w 的 TextHandler, 使用给定的选项。 如果 opts 为 nil,则使用默认选项。
func (*TextHandler) Enabled
func (h *TextHandler) Enabled(_ context.Context, level Level) bool
Enabled 报告 handler 是否处理给定级别的记录。 handler 会忽略级别更低的记录。
func (*TextHandler) Handle
func (h *TextHandler) Handle(_ context.Context, r Record) error
Handle 将它的参数 Record 格式化为由空格分隔的 key=value 项组成的单行。
如果 Record 的时间为零,则省略时间。 否则,键为 "time", 其值以毫秒精度的 RFC3339 格式输出。
级别的键为 "level",其值是调用 Level.String 的结果。
如果设置了 AddSource 选项且源信息可用, 则键为 "source",其值以 FILE:LINE 形式输出。
消息的键为 "msg"。
若要修改这些属性或其他属性,或将它们从输出中移除,请使用 HandlerOptions.ReplaceAttr。
如果某个值实现了 encoding.TextMarshaler,则写入 MarshalText 的结果。 否则,写入 fmt.Sprint 的结果。
如果键和值包含 Unicode 空白字符、不可打印字符、'"' 或 '=', 则会用 strconv.Quote 对它们加引号。
分组内的键由以点分隔的组件(键或分组名称)组成。 不会进行进一步的转义。 因此,无法从键 "a.b.c" 判断是否存在 两个分组 "a" 和 "b" 以及一个键 "c",还是单个分组 "a.b" 和一个键 "c", 或单个分组 "a" 和一个键 "b.c"。 如果即使组件内存在点,也有必要重建某个键的分组结构, 请使用 HandlerOptions.ReplaceAttr 将该信息编码到键中。
每次调用 Handle 都会导致一次对 io.Writer.Write 的序列化调用。
func (*TextHandler) WithAttrs
func (h *TextHandler) WithAttrs(attrs []Attr) Handler
WithAttrs 返回一个新的 TextHandler,其属性由 h 的属性后跟 attrs 组成。
func (*TextHandler) WithGroup
func (h *TextHandler) WithGroup(name string) Handler
type Value
type Value struct { // contains filtered or unexported fields }
Value 可以表示任意 Go 值,但与 any 类型不同, 它可以在不分配内存的情况下表示大多数小值。 零值 Value 对应于 nil。
func AnyValue
func AnyValue(v any) Value
AnyValue 返回一个用于所提供值的 Value。
如果所提供的值的类型是 Value,则原样返回它, 不做修改。
对于 Go 预声明的 string、bool 或(非复数)数值类型之一的值, AnyValue 返回种类为 KindString、KindBool、KindUint64、KindInt64 或 KindFloat64 的 Value。原始数值类型的宽度不会被保留。
对于 time.Time 或 time.Duration 值,AnyValue 返回种类为 KindTime 或 KindDuration 的 Value。单调时钟不会被保留。
对于 nil,或所有其他类型的值(包括底层类型为数值的命名类型), AnyValue 返回种类为 KindAny 的值。
func BoolValue
func BoolValue(v bool) Value
BoolValue 返回一个用于 bool 的 Value。
func DurationValue
func DurationValue(v time.Duration) Value
DurationValue 返回一个用于 time.Duration 的 Value。
func Float64Value
func Float64Value(v float64) Value
Float64Value 返回一个用于浮点数的 Value。
func GroupValue
func GroupValue(as ...Attr) Value
GroupValue 返回一个用于 Attr 列表的新 Value。 调用者之后不得修改参数切片。
func Int64Value
func Int64Value(v int64) Value
Int64Value 返回一个用于 int64 的 Value。
func IntValue
func IntValue(v int) Value
IntValue 返回一个用于 int 的 Value。
func StringValue
func StringValue(value string) Value
StringValue 返回一个用于字符串的新 Value。
func TimeValue
func TimeValue(v time.Time) Value
TimeValue 返回一个用于 time.Time 的 Value。 它会丢弃单调时钟部分。
func Uint64Value
func Uint64Value(v uint64) Value
Uint64Value 返回一个用于 uint64 的 Value。
func (Value) Any
func (v Value) Any() any
Any 将 v 的值作为 any 返回。
func (Value) Bool
func (v Value) Bool() bool
Bool 将 v 的值作为 bool 返回。如果 v 不是 bool,它会 panic。
func (Value) Duration
func (v Value) Duration() time.Duration
Duration 将 v 的值作为 time.Duration 返回。如果 v 不是 time.Duration,它会 panic。
func (Value) Equal
func (v Value) Equal(w Value) bool
Equal 报告 v 和 w 是否表示相同的 Go 值。
func (Value) Float64
func (v Value) Float64() float64
Float64 将 v 的值作为 float64 返回。如果 v 不是 float64,它会 panic。
func (Value) Group
func (v Value) Group() []Attr
Group 将 v 的值作为 []Attr 返回。 如果 v 的 Kind 不是 KindGroup,它会 panic。
func (Value) Int64
func (v Value) Int64() int64
Int64 将 v 的值作为 int64 返回。如果 v 不是 有符号整数,它会 panic。
func (Value) Kind
func (v Value) Kind() Kind
Kind 返回 v 的 Kind。
func (Value) LogValuer
func (v Value) LogValuer() LogValuer
LogValuer 将 v 的值作为 LogValuer 返回。如果 v 不是 LogValuer,它会 panic。
func (Value) Resolve
func (v Value) Resolve() (rv Value)
Resolve 在 v 实现 LogValuer 期间反复调用 v 上的 LogValue, 并返回结果。 如果 v 解析为一个分组,则该分组的属性值不会被递归 解析。 如果 LogValue 的调用次数超过阈值,则返回一个包含 错误的 Value。 Resolve 的返回值保证不会是 KindLogValuer 种类。
func (Value) String
func (v Value) String() string
String 将 Value 的值作为字符串返回,格式类似于 fmt.Sprint。 与在 v 的种类错误时会 panic 的 Int64、Float64 等方法不同, String 从不 panic。
func (Value) Time
func (v Value) Time() time.Time
Time 将 v 的值作为 time.Time 返回。如果 v 不是 time.Time,它会 panic。
func (Value) Uint64
func (v Value) Uint64() uint64
Uint64 将 v 的值作为 uint64 返回。如果 v 不是 无符号整数,它会 panic。