旅游网站建设现状,wordpress 插件 卡券,农村学校资源网站建设与研究,软件开发包括什么内容上一篇文章讲解了 log/slog 包中的分组、上下文和属性值类型#xff0c;本文讲解下 LogValuer 和日志记录函数的正确包装方法。
slog.LogValuer
如果想改变或者自定义一个类型的日志记录行为#xff0c;可以通过实现 slog.LogValuer 接口来实现#xff0c;slog.LogValuer …上一篇文章讲解了 log/slog 包中的分组、上下文和属性值类型本文讲解下 LogValuer 和日志记录函数的正确包装方法。
slog.LogValuer
如果想改变或者自定义一个类型的日志记录行为可以通过实现 slog.LogValuer 接口来实现slog.LogValuer 接口的定义如下
type LogValuer interface {LogValue() Value
}
定义了一个 LogValue 方法返回一个 Value 类型的对象。如果一个类型实现了 LogValuer 接口那么从它的 LogValue 方法返回的 Value 将被用于日志记录可以用来控制该类型的值在日志中的显示方式。看个简单示例
package mainimport (log/slogos
)type Token string// 实现 slog.LogValuer 接口
// 避免泄露 token
func (Token) LogValue() slog.Value {return slog.StringValue(******)
}func main() {t : Token(shhhh!)logger : slog.New(slog.NewTextHandler(os.Stdout, nil))logger.Info(生成 token, 用户, 路多辛的博客, token, t)
}
输出内容如下
time2023-10-15T15:06:58.25308:00 levelINFO msg生成 token 用户路多辛的博客 token******
从安全角度看密码或者token 等敏感信息是不能被记录在日志里面的可以使用自定义的并且实现了 LogValue 的类型来避免这种情况产生。在这个例子中当记录 token 日志时token 会被转换为“******”后记录在日志里面。再看一个结合字段分组使用的示例
package mainimport (log/slog
)type Name struct {First, Last string
}func (n Name) LogValue() slog.Value {return slog.GroupValue(slog.String(first, n.First),slog.String(last, n.Last))
}func main() {n : Name{路多辛的博客, 路多辛的所思所想}slog.Info(任务结束, agent, n)
}
输出内容如下
2023/10/15 15:06:09 INFO 任务结束 agent.first路多辛的博客 agent.last路多辛的所思所想
包装输出函数
日志记录函数使用调用堆栈上的反射来查找应用程序中日志记录调用的文件名和行号这可能会导致包装 slog 的函数记录错误的的源信息。举个例子如果在 mylog.go 中定义了一个日志记录函数 Infof然后在 main.go 中调用了此函数这种情况下日志会将把源文件记录为 mylog.go 而不是 main.go。正确实现 Infof 函数的方式是将获取的源信息传递给 NewRecord 函数示例代码如下
package mainimport (contextfmtlog/slogospath/filepathruntimetime
)func Infof(logger *slog.Logger, format string, args ...any) {if !logger.Enabled(context.Background(), slog.LevelInfo) {return}var pcs [1]uintptrruntime.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 sources 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)
}