Home > Article > Backend Development > Simple golang Logrus usage tutorial
The following is a simple golang Logrus usage tutorial from the golang tutorial column. I hope it will be helpful to friends in need!
golang Logrus Easy to Use Tutorial
The easiest way to use Logrus:
package main import ( log "github.com/sirupsen/logrus" ) func main() { log.WithFields(log.Fields{ "animal": "walrus", }).Info("A walrus appears") }
Please note that it is fully api compatible with the stdlib logger, so You can replace the import anywhere in log, log "github.com/sirupsen/logrus" . You can also customize everything:
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") }
For more advanced usage, for a large project, a global logrus instance, that is, the logger object, is often needed to record all the logs of the project. Examples include:
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 encourages careful structured logging via logging fields rather than lengthy and unparseable error messages. For example, instead of: log.Fatalf("Failed to send event %s to topic %s with key %d"), you should use:
log.WithFields(log.Fields{ "event": event, "topic": topic, "key": key, }).Fatal("Failed to send event")
We found that this API forces you to think about generating more useful Log records in the form of log messages. We've encountered countless situations where simply adding a field to an already existing log statement saved us time. The WithFields call is optional.
Generally, using any of the printf-family functions with Logrus should be considered a hint and you should add a field, however, you can still use the printf-family functions with Logrus.
Default Fields
It is often helpful to always attach fields to log statements in your application or part of an application. For example, you might want to always log request_id and user_ip in the context of a request. Instead of writing log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) on every line, you can create a logrus.Entry passing:
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
You can add hooks for logging levels. For example, send errors to the exception tracking service on Error, Fatal and Panic information to StatsD or log to multiple locations at the same time, such as syslog.
Logrus comes with built-in hooks. Add these or your custom hook 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) } }
Note: Syslog hooks also support connecting to local syslog (such as "/dev/log" or "/var/run/syslog" or "/var /run/log"). For details, check the syslog hooks README.
A list of currently known service hooks can be found on this wiki page.
Logging Levels
Logrus has seven logging levels: trace, debug, information, warning, error, critical, and emergency.
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.")
You can set the logging level on Logger and it will only log entries with that severity or higher:
// Will log anything that is info or above (warn, error, fatal, panic). Default. log.SetLevel(log.InfoLevel)
log.Level = logrus.DebugLevel if applied If your program has a debug or verbose environment, it may be useful to set it up there.
ENTRIES
In addition to the added fields WithField or WithFields certain fields will be automatically added to all logging events:
time. The timestamp when the entry was created.
msg. The log message passed to AddFields after calling {Info, Warn, Error, Fatal, Panic}. For example, Failed to send event.
level. Logging level. For example info.
Environment
Logrus has no concept of environment.
If you wish to use hooks and formatters only in a specific environment, you should handle this yourself. For example, if your application has a global variable Environment, which is a string representation of the environment, you can do the following:
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{}) } }
This configuration is used as expected by logrus, but the JSON in production only This is only useful when using tools like Splunk or Logstash for log aggregation.
Formatter
The built-in log formatter is:
logrus.TextFormatter. Events are logged in color if stdout is a tty, otherwise events are logged in color.
Note: To force color output when there is no TTY, set the ForceColors field to true. To not force output to be in color even with a TTY, set the DisableColors field to true. For Windows, see github.com/mattn/go-colorable.
When colors are enabled, levels will be truncated to 4 characters by default. To disable truncation, set the DisableLevelTruncation field to true.
When outputting to a TTY, it is often helpful to visually scan down columns where all levels are the same width. Enable this behavior by adding padding to the level text, setting the PadLevelText field to true.
All options are listed in the generated documentation.
logrus.JSONFormatter. Log fields as JSON.
All options are listed in the generated documentation.
Third-party log formatter:
FluentdFormatter. Format entries that can be parsed by Kubernetes and Google Container Engine.
GELF. Format entries to conform to Graylog's GELF 1.1 specification.
logstash. Log fields as Logstash events.
prefixed. Shows log entry sources as well as alternate layouts.
zalgo. Call upon the power of Zalgo.
nested-logrus-formatter. Convert logarithmic fields to nested structures.
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)可以压缩和删除旧日志条目的外部程序(如)完成。它不应该是应用程序级记录器的功能。
The above is the detailed content of Simple golang Logrus usage tutorial. For more information, please follow other related articles on the PHP Chinese website!