如何将自定义(非常量)字符串信息添加到日志格式中?

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

How to add custom (non const) string information to log format?

问题

你可以通过自定义日志格式来添加额外的信息到日志条目中。在Go中,可以使用log.New函数创建一个自定义的log.Logger实例,并通过设置log.LoggerSetPrefix方法来定义日志的前缀。

在你的例子中,你可以修改Init函数,将函数名作为参数传递,并在创建log.Logger实例时将其添加到日志前缀中。以下是修改后的代码示例:

func Init(
    traceHandle io.Writer,
    infoHandle io.Writer,
    warningHandle io.Writer,
    errorHandle io.Writer,
    functionName string) {

    Trace = log.New(traceHandle,
        "TRACE: "+functionName+": ",
        log.Ldate|log.Ltime|log.Lshortfile)

    Info = log.New(infoHandle,
        "INFO: "+functionName+": ",
        log.Ldate|log.Ltime|log.Lshortfile)

    Warning = log.New(warningHandle,
        "WARNING: "+functionName+": ",
        log.Ldate|log.Ltime|log.Lshortfile)

    Error = log.New(errorHandle,
        "ERROR: "+functionName+": ",
        log.Ldate|log.Ltime|log.Lshortfile)
}

func main() {
    functionName := "your_function_name" // Replace with the actual function name
    Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr, functionName)
}

在上面的代码中,我添加了一个名为functionName的参数,并将其作为前缀添加到每个日志实例中。你需要将functionName替换为实际的函数名。

这样,当你使用Trace.PrintlnInfo.Println等方法记录日志时,日志条目的前缀将包含函数名信息。例如,日志条目可能会显示为:

INFO: your_function_name: 2023/08/15 21:26:25 main.go:10: Entering _enter

希望这可以帮助到你!

英文:

I have started working with logging in Go and I have encountered this article about logging in Go https://www.goinggo.net/2013/11/using-log-package-in-go.html

with the following source code (slightly changed):

var (
  Trace   *log.Logger
  Info    *log.Logger
  Warning *log.Logger
  Error   *log.Logger
)

func Init(
    traceHandle io.Writer,
    infoHandle io.Writer,
    warningHandle io.Writer,
    errorHandle io.Writer) {

    Trace = log.New(traceHandle,
        “TRACE: “,
        log.Ldate|log.Ltime|log.Lshortfile)

    Info = log.New(infoHandle,
        “INFO: “,
        log.Ldate|log.Ltime|log.Lshortfile)

    Warning = log.New(warningHandle,
        “WARNING: “,
        log.Ldate|log.Ltime|log.Lshortfile)

    Error = log.New(errorHandle,
        “ERROR: “,
        log.Ldate|log.Ltime|log.Lshortfile)
}

func main() {
  Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)
}

now I would like to add some custom information to log entries produced by this logger but which are not const string literals (like added there INFO: or WARNING:)

For example I would like to add a name of the function in which the log has been triggered. Let's say I have the following function which I would like to use for this: (from here)

func _enter() {
  // Skip this function, and fetch the PC and file for its parent
  pc, _, _, _ := runtime.Caller(1)
  // Retrieve a Function object this functions parent
  functionObject := runtime.FuncForPC(pc)
  // Regex to extract just the function name (and not the module path)
  extractFnName := regexp.MustCompile(`^.*\.(.*)$`)
  fnName := extractFnName.ReplaceAllString(functionObject.Name(), "$1")
  fmt.Printf("Entering %s\n", fnName)
}

How can I add this to the logger?

答案1

得分: 1

  • 当你编写日志行时,最简单的答案当然是直接输入它。许多库实际上使用了一种约定,例如:

    logger.Logf("myfilename.go:123" + "other logging info")

    其中123是行号。这在IDE或编辑器中也很容易脚本化。

  • 如果你将_enter()改为返回函数的名称,那么剩下的部分就会简单得多。你可以在每个函数内部调用logger.SetPrefix(),根据你的示例代码,可能如下所示:

    Info.SetPrefix("INFO: " + _enter() + ":")

    你可以将日志记录器包装在一个结构体中,以自动执行上述操作,但你应该注意每次调用_enter()都会带来的开销。

  • 不过,此时你可能想要考虑使用具有更多功能的日志记录库。我在使用logrus方面有很好的经验,它可以作为标准库log包的替代品。

英文:
  • The simplest answer of course is to just type it in when you write the line of logging. Lots of libraries actually use a convention like

    logger.Logf("myfilename.go:123" + "other logging info")

    where 123 is the line number. This is pretty scriptable by an ide or editor as well.

  • If you change _enter() to return the name of the function, that would make the rest of this much simpler. You can call logger.SetPrefix() inside each function, which might look like the following based on your example code.

    ```Info.SetPrefix("INFO: " + _enter() + ":")
    

    You could wrap the logger in a struct that would help do the above automatically, but you should be aware of the overhead of making the call to `_enter()` _every_ time.

 - Though at this point, you might want to look into using a logging library with more features.  I have had good experiences with [logrus](https://github.com/Sirupsen/logrus) which can be a drop in replacement for the standard lib's log package.


</details>



huangapple
  • 本文由 发表于 2016年4月10日 00:22:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/36519524.html
匿名

发表评论

匿名网友

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

确定