英文:
How to implement idiomatic logging in a Go library?
问题
在Go中,执行日志记录的惯用方式是什么?
英文:
What is an idiomatic way to perform logging in Go?
答案1
得分: 11
Create a file that declares a global variable logger. Then, use the idiomatic init() function of Go to initialize the variable on startup.
logger.go:
package xxx
import (
"log"
"os"
)
var logger *log.Logger
func init() {
logger = log.New(os.Stderr, "xxx: ", log.Ldate | log.Ltime | log.Lshortfile)
}
example.go:
func test() {
logger.Println("Logged")
}
This method offers the benefit that you can use a single logger implementation that can be configured from a single file.
EDIT: ThomasKappler pointed out that if you are only using a single global logger, you can use the log package's inbuilt logger and configure it with SetFlags. The only difference is you must be more explicit and import the log package.
英文:
Create a file that declares a global variable logger. Then, use the idiomatic init() function of Go to initialize the variable on startup.
logger.go:
package xxx
import (
"log"
"os"
)
var logger *log.Logger
func init() {
logger = log.New(os.Stderr, "xxx: ", log.Ldate | log.Ltime | log.Lshortfile)
}
example.go:
func test() {
logger.Println("Logged")
}
This method offers the benefit that you can use a single logger implementation that can be configured from a single file.
EDIT: ThomasKappler pointed out that if you are only using a single global logger, you can use the log package's inbuilt logger and configure it with SetFlags. The only difference is you must be more explicit and import the log package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论