如何在Go库中实现惯用的日志记录?

huangapple go评论87阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2012年11月21日 18:18:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/13491032.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定