我知道这可能是如何在 Golang 中实现基于级别的日志记录?的重复,但我很感激针对我的情况的其他建议,也许 11 年来出现了一些新的东西 :D.
我已经使用了 Go 的内置 log 包,它工作得很好,但我想增强,请参阅一个简单但仍然可用的实现示例。我牢记这些标准:
如果你真的需要一些简单的东西,这是我通常为宠物项目编写的方式:
package logging
import (
"fmt"
"log"
"os"
"regexp"
"runtime"
)
type logLevel int
const (
INFO logLevel = iota
ERR
)
type application struct {
level logLevel
errorLog *log.Logger
infoLog *log.Logger
}
var infoLog = log.New(os.Stdout, "INFO: \t", log.Ltime)
var errorLog = log.New(os.Stderr, "ERROR: \t", log.Ltime)
var path string
func NewLogger(Level logLevel) *application {
return &application{
level: Level,
errorLog: errorLog,
infoLog: infoLog,
}
}
func (l *application) Info(msg ...any) {
if l.level <= INFO {
file, line := getCaller()
l.infoLog.Printf("[%s : %d] \n\n%s\n\n", file, line, fmt.Sprint(msg...))
}
}
func (l *application) Error(err ...any) {
if l.level <= ERR {
file, line := getCaller()
l.errorLog.Fatalf("[%s : %d] \n\n%s\n\n", file, line, fmt.Sprint(err...))
}
}
func getCaller() (string, int) {
key := os.Getenv("KEY_WORD") // assign your folder name, so we can crop no-required part
_, file, line, ok := runtime.Caller(2)
if !ok {
log.Fatal("runtime caller has an error")
}
if key == "" {
fmt.Print("key is empty")
return file, line // Return without modifying if key is not set
}
regExp, _ := regexp.Compile(".*" + regexp.QuoteMeta(key)) // regex for deleting left side
file = regExp.ReplaceAllString(file, key)
return file, line
}
它不是超级先进之类的,但仍然可以很好地完成工作,主要功能也许是将logs和errors调平到不同的流中,并显示发生错误的文件路径。
如果您的目标是学习 - 查看您所附的问题,
有很多例子。看看它们并尝试以您喜欢的方式推进我提供的片段