go - 如何使用新功能扩展日志 API

标签 go logging

我将以下代码与 logrus 一起使用,我想扩展它,即
在每次使用这个 logrus 日志时,它会默认添加 functionfile但它不起作用

我得到了

{
  "level": "info",
  "msg": "info",
  "time": "2019-10-06 17:14:25"
}

我要
{
  "file": “myfile.go",
  "func": “myfunc:95",
  "level": "info",
  "msg": "info",
  "time": "2019-10-06 17:17:53"
}

我不是在谈论使用 ReportCaller:是的,我只是想用我的函数扩展记录器

我该怎么做 ?

这就是我尝试的
package main

import (
   "os"
   "runtime"
   "strconv"
   "strings"
   "github.com/sirupsen/logrus"
)

func main() {
   lgr().Log(logrus.InfoLevel,"info")
}

func lgr() *logrus.Logger {


   loggerImpl := &logrus.Logger{
      Out:   os.Stdout,
      Hooks: nil,
      Formatter: &logrus.JSONFormatter{
         TimestampFormat: "2006-01-02 15:04:05",
         CallerPrettyfier: func(f *runtime.Frame) (string, string) {

            pc, file, line, ok := runtime.Caller(1)
            if !ok {
               panic("Could not get context info for logger!")
            }
            filename := file[strings.LastIndex(file, "/")+1:] + ":" + strconv.Itoa(line)
            funcname := runtime.FuncForPC(pc).Name()
            fn := funcname[strings.LastIndex(funcname, ".")+1:]
            return filename, fn
         },


         PrettyPrint: true,
      },
      Level:        logrus.InfoLevel,
      ExitFunc:     nil,
   }
   return loggerImpl
}

最佳答案

一种方法是使用 WithFieldslogrus.Fields像这样:

package main

import (
    "github.com/sirupsen/logrus"
    "os"
    "runtime"
    "strconv"
    "strings"
)

func main() {
    lgr().Log(logrus.InfoLevel, "info")
}

func lgr() *logrus.Entry {

    pc, file, line, ok := runtime.Caller(1)
    if !ok {
        panic("Could not get context info for logger!")
    }
    filename := file[strings.LastIndex(file, "/")+1:] + ":" + strconv.Itoa(line)
    funcname := runtime.FuncForPC(pc).Name()
    fn := funcname[strings.LastIndex(funcname, ".")+1:]

    loggerImpl := &logrus.Logger{
        Out:   os.Stdout,
        Hooks: nil,
        Formatter: &logrus.JSONFormatter{
            TimestampFormat: "2006-01-02 15:04:05",
            PrettyPrint:     true,
        },
        Level:    logrus.InfoLevel,
        ExitFunc: nil,
    }

    return loggerImpl.WithFields(logrus.Fields{
        "file":     filename,
        "function": fn,
    })
}


上述代码中*logrus.Entry具有您期望从记录器获得的所有方法。也可以使用接口(interface)logrus.FieldLogger但如果我们这样做,我们将需要坚持该接口(interface)上的方法,(例如没有 Log 方法 - 必须使用 Info/Error 等)。
package main

import (
    "github.com/sirupsen/logrus"
    "os"
    "runtime"
    "strconv"
    "strings"
)

func main() {
    lgr().Infoln("Hello world")
}

func lgr() logrus.FieldLogger {

    pc, file, line, ok := runtime.Caller(1)
    if !ok {
        panic("Could not get context info for logger!")
    }
    filename := file[strings.LastIndex(file, "/")+1:] + ":" + strconv.Itoa(line)
    funcname := runtime.FuncForPC(pc).Name()
    fn := funcname[strings.LastIndex(funcname, ".")+1:]

    loggerImpl := &logrus.Logger{
        Out:   os.Stdout,
        Hooks: nil,
        Formatter: &logrus.JSONFormatter{
            TimestampFormat: "2006-01-02 15:04:05",
            PrettyPrint:     true,
        },
        Level:    logrus.InfoLevel,
        ExitFunc: nil,
    }

    return loggerImpl.WithFields(logrus.Fields{
        "file":     filename,
        "function": fn,
    })
}


输出:
{
  "file": "main.go:12",
  "function": "main",
  "level": "info",
  "msg": "Hello world",
  "time": "2019-10-07 01:24:10"
}

关于go - 如何使用新功能扩展日志 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58260137/

相关文章:

logging - 使用 jul-to-slf4j WildFly 记录未格式化的消息

mysql - 无法使用 Xampp 安装 MySQL

go - 去获取github…给GOPATH不能启动〜

go - 带有 v2 Go 模块的项目结构

google-app-engine - AppEngine "appengine"包始终失败,出现 "syscall"或 "unsafe"导入失败

java - 记录生成的 CXF 客户端的原始 XML

go - 如何在 goroutine 中返回值

go - 全局错误变量在初始化后保持为 nil

node.js - 根据条件在react js中导出?

java - 停止 JUNit 记录