英文:
Implement a minimal logger in Golang
问题
我已经创建了一个简单的 Golang 日志记录器。我试图尽可能保持简单,但是出现了两个问题:
- 消息字符串显示为用方括号 [] 包裹的数组
- 使用
log.Lshortfile
标志的文件名始终显示为logger.go
这是我的代码:
package logger
import (
"log"
"os"
)
var (
dlog = log.New(os.Stdout, "\x1B[36mDEBUG: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
wlog = log.New(os.Stdout, "\x1B[35mWARN: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
ilog = log.New(os.Stdout, "\x1B[32mINFO: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
elog = log.New(os.Stderr, "\x1B[31mERROR: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
)
// Debug Log
func Debug(a ...interface{}) {
dlog.Println(a)
}
// Warn log
func Warn(a ...interface{}) {
wlog.Println(a)
}
// Info Log
func Info(a ...interface{}) {
ilog.Println(a)
}
// Error Log
func Error(a ...interface{}) {
elog.Println(a)
}
我像这样使用它们:logger.Debug("Hello")
或 logger.Info("There")
。
你如何正确实现它?谢谢。
英文:
I've created a minimal logger in Golang.
I tried to keep it as simple as possible but two problems arise:
- Message string is shown as array wrapped in brackets []
- filename using
log.Lshortfile
flag is always shown aslogger.go
Here's my code:
package logger
import (
"log"
"os"
)
var (
dlog = log.New(os.Stdout, "\x1B[36mDEBUG: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
wlog = log.New(os.Stdout, "\x1B[35mWARN: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
ilog = log.New(os.Stdout, "\x1B[32mINFO: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
elog = log.New(os.Stderr, "\x1B[31mERROR: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
)
// Debug Log
func Debug(a ...interface{}) {
dlog.Println(a)
}
// Warn log
func Warn(a ...interface{}) {
wlog.Println(a)
}
// Info Log
func Info(a ...interface{}) {
ilog.Println(a)
}
// Error Log
func Error(a ...interface{}) {
elog.Println(a)
}
I use them like this: logger.Debug("Hello") or logger.Info("There")
How do I implement this correctly? Thank you.
答案1
得分: 3
Println接收一个参数,参数类型是interface{}的切片,并使用切片表示法进行打印。要修复这个问题,将可变参数作为可变参数传递给被调用函数。
func Debug(a ...interface{}) {
dlog.Println(a...) // <-- 注意这里的...
}
调用Output来解决文件名问题。
func Debug(a ...interface{}) {
dlog.Output(2, fmt.Sprintln(a...))
}
英文:
Println is passed a single parameter, a slice of interface{}, and prints it using slice notation. To fix this, pass the variadic parameters to your functions as variadic arguments to the called functions.
func Debug(a ...interface{}) {
dlog.Println(a...) // <-- note ... here
}
Here's the doc on variadic args.
Call Output to workaround the file name issue.
func Debug(a ...interface{}) {
dlog.Output(2, fmt.Sprintln(a...))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论