简单的golang Logrus使用教程

来自:互联网
时间:2021-05-25
阅读:

golang Logrus简易使用教程

使用Logrus的最简单方法:

package mAIn
import (
  log "github.com/sirupsen/logrus"
)
func main() {
  log.WithFields(log.Fields{
    "animal": "walrus",
  }).Info("A walrus appears")
}

请注意,它与stdlib记录器完全api兼容,因此您可以在log任何地方替换导入,log "github.com/sirupsen/logrus" 。也可以自定义所有内容:

package main
import (
  "os"
  log "github.com/sirupsen/logrus"
)
func init() {
  // Log 为JSON而不是默认的ASCII格式。
  log.SetFormatter(&log.JSONFormatter{})
  // 输出到标准输出,而不是默认的标准错误
  //可以是任何io.Writer,请参阅下面的文件例如日志。
  log.SetOutput(os.Stdout)
  // 仅记录严重警告以上。
  log.SetLevel(log.WarnLevel)
}
func main() {
  log.WithFields(log.Fields{
    "animal": "walrus",
    "size":   10,
  }).Info("A group of walrus emerges from the ocean")
  log.WithFields(log.Fields{
    "omg":    true,
    "number": 122,
  }).Warn("The group's number increased tremendously!")
  log.WithFields(log.Fields{
    "omg":    true,
    "number": 100,
  }).Fatal("The ice breaks!")
  // 一种常见的模式是通过重用
  //从WithFields返回的logrus.Entry 来重用日志记录语句之间的字段
  contextLogger := log.WithFields(log.Fields{
    "common": "this is a common field",
    "other": "I also should be logged always",
  })
  contextLogger.Info("I'll be logged with common and other field")
  contextLogger.Info("Me too")
}

对于更高级的用法,对于一个大型项目,往往需要一个全局的logrus实例,即logger对象,来记录项目所有的日志。示例如下:

package main
import (
  "os"
  "github.com/sirupsen/logrus"
)
// 创建记录器的一个新实例。您可以有任意多个实例
var log = logrus.New()
func main() {
  // 用于设置属性的API与程序包级别
  // 导出的记录器有些不同。见Godoc。
  log.Out = os.Stdout
  // 您可以将其设置为任何`io.Writer`
  // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  // if err == nil {
  //  log.Out = file
  // } else {
  //  log.Info("Failed to log to file, using default stderr")
  // }
  log.WithFields(logrus.Fields{
    "animal": "walrus",
    "size":   10,
  }).Info("A group of walrus emerges from the ocean")
}

Fields:

Logrus鼓励通过日志记录字段而不是冗长且无法解析的错误消息进行仔细的结构化日志记录。例如,代替:log.Fatalf("Failed to send event %s to topic %s with key %d"),您应该使用:

log.WithFields(log.Fields{
  "event": event,
  "topic": topic,
  "key": key,
}).Fatal("Failed to send event")

我们发现此API会迫使您考虑以产生更多有用日志消息的方式进行日志记录。我们曾经遇到过无数种情况,在该情况下,仅向已存在的日志语句添加一个字段就可以为我们节省时间。该WithFields呼叫是可选的。

通常,使用Logrus使用printf-family函数中的任何一个应被视为提示,您应该添加一个字段,但是,您仍然可以将 printf-family函数与Logrus一起使用。

默认字段

将字段始终附加到应用程序或应用程序的一部分中的日志语句通常会很有帮助。例如,您可能希望始终在请求的上下文中记录 request_id和user_ip。无需log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})在每一行上都写 ,而是可以创建一个logrus.Entry传递:

requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
requestLogger.Info("something happened on that request") # will log request_id and user_ip
requestLogger.Warn("something not great happened")

Hooks

您可以添加用于日志记录级别的挂钩。例如,将错误发送到上的异常跟踪服务Error,Fatal并将Panic信息发送到StatsD或同时记录到多个位置,例如syslog。

Logrus带有内置挂钩。在其中添加这些或您的自定义钩子 init:

import (
  log "github.com/sirupsen/logrus"
  "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake"
  logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
  "log/syslog"
)
func init() {
  // Use the Airbrake hook to report errors that have Error severity or above to
  // an exception tracker. You can create custom hooks, see the Hooks section.
  log.AddHook(airbrake.NewHook(123, "xyz", "production"))
  hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
  if err != nil {
    log.Error("Unable to connect to local syslog daemon")
  } else {
    log.AddHook(hook)
  }
}

注意:Syslog钩子还支持连接到本地syslog(例如“ / dev / log”或“ / var / run / syslog”或“ / var / run / log”)。有关详细信息,请检查syslog挂钩README。

可以在此Wiki 页面中找到当前已知的服务挂钩的列表。

日志记录级别

Logrus具有七个日志记录级别:跟踪,调试,信息,警告,错误,严重和紧急。

log.Trace("Something very low level.")
log.Debug("Useful debugging information.")
log.Info("Something noteworthy happened!")
log.Warn("You should probably take a look at this.")
log.Error("Something failed but I'm not quitting.")
// Calls os.Exit(1) after logging
log.Fatal("Bye.")
// Calls panic() after logging
log.Panic("I'm bailing.")

您可以在上设置日志记录级别Logger,然后它将仅记录具有该严重性或更高严重性的条目:

// Will log anything that is info or above (warn, error, fatal, panic). Default.
log.SetLevel(log.InfoLevel)

log.Level = logrus.DebugLevel如果应用程序具有调试或详细环境,则在其中进行设置可能会很有用。

参赛作品

除了添加的字段WithField或WithFields某些字段外,还会自动将其添加到所有日志记录事件中:

time。创建条目的时间戳。

msg。呼叫{Info,Warn,Error,Fatal,Panic}后传递到的日志消息AddFields。例如Failed to send event.

level。日志记录级别。例如info。

环境

Logrus没有环境概念。

如果希望只在特定环境中使用钩子和格式化程序,则应自己处理。例如,如果您的应用程序具有全局变量Environment,它是环境的字符串表示形式,则可以执行以下操作:

import (
  log "github.com/sirupsen/logrus"
)
init() {
  // do something here to set environment depending on an environment variable
  // or command-line flag
  if Environment == "production" {
    log.SetFormatter(&log.JSONFormatter{})
  } else {
    // The TextFormatter is default, you don't actually have to do this.
    log.SetFormatter(&log.TextFormatter{})
  }
}

此配置是按logrus预期方式使用的,但是生产中的JSON仅在使用Splunk或Logstash等工具进行日志聚合时才有用。

格式化程序

内置的日志格式器是:

logrus.TextFormatter。如果stdout是tty,则以彩色记录事件,否则以彩色记录事件。

注意:要在没有TTY时强制输出彩色,请将ForceColors 字段设置为true。即使有TTY,也要不强制输出彩色,请将DisableColors字段设置 为true。对于Windows,请参阅 github.com/mattn/go-colorable。

启用颜色后,默认情况下级别将被截断为4个字符。要禁用截断功能,请将DisableLevelTruncation字段设置为true。

输出到TTY时,以可视方式向下扫描所有级别均为相同宽度的列通常会很有帮助。通过在级别文本中添加填充,将PadLevelText字段设置为true启用此行为。

所有选项都在生成的文档中列出。

logrus.JSONFormatter。将字段记录为JSON。

所有选项都在生成的文档中列出。

第三方日志格式化程序:

FluentdFormatter。格式化可由Kubernetes和Google Container Engine解析的条目。

GELF。格式化条目,使其符合Graylog的GELF 1.1规范。

logstash。将字段记录为Logstash事件。

prefixed。显示日志条目源以及备用布局。

zalgo。调用Zalgo的力量。

nested-logrus-formatter。将对数字段转换为嵌套结构。

powerful-logrus-formatter。打印日志时获取文件名,日志行号和最新函数名称;Sava日志到文件。

caption-json-formatter。添加了人类可读标题的logrus消息json格式化程序。

您可以通过实现Formatter接口(需要一种Format方法)来定义格式化程序。Format需要一个*Entry。entry.Data是一种 Fields类型(map[string]interface{}),其中包含您的所有字段以及默认字段(请参见上面的条目部分):

type MyJSONFormatter struct {
}
log.SetFormatter(new(MyJSONFormatter))
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
  // Note this doesn't include Time, Level and Message which are available on
  // the Entry. Consult `godoc` on information about those fields or read the
  // source of the official loggers.
  serialized, err := json.Marshal(entry.Data)
    if err != nil {
      return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
    }
  return append(serialized, '\n'), nil
}

记录为 io.Writer

Logrus可以转换为io.Writer。该作家是an的结尾,io.Pipe您有责任关闭它。

w := logger.Writer()
defer w.Close()
srv := http.Server{
    // create a stdlib log.Logger that writes to
    // logrus.Logger.
    ErrorLog: log.New(w, "", 0),
}

写入该写入器的每一行都将使用格式化程序和钩子以常规方式打印。这些条目的级别为info。

这意味着我们可以轻松覆盖标准库记录器:

logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{}
// Use logrus for standard log output
// Note that `log` here references stdlib's log
// Not logrus imported under the name `log`.
log.SetOutput(logger.Writer())

日志轮换

Logrus不提供日志轮换。日志轮换应由logrotate(8)可以压缩和删除旧日志条目的外部程序(如)完成。它不应该是应用程序级记录器的功能。

返回顶部
顶部