在 Golang 中,可以使用 log 包来记录日志。要在日志中添加上下文信息,可以使用 log 包的 WithFields
或 WithValues
方法。这两个方法都接受一个 log.Fields
类型的参数,它是一个键值对的映射。通过这种方式,可以在日志中添加上下文信息,以便更好地了解日志记录时的情况。
下面是一个使用 WithFields
方法添加上下文信息的示例:
package main import ( "log" "os" "github.com/sirupsen/logrus" ) func main() { logrus.SetOutput(os.Stdout) logrus.SetLevel(logrus.DebugLevel) // 创建一个包含上下文信息的 logrus.Fields 类型的变量 fields := logrus.Fields{ "user_id": 123, "user_name": "John Doe", "request_id": "abc123", } // 使用 WithFields 方法将上下文信息添加到日志中 logrus.WithFields(fields).Debug("This is a debug message with context") logrus.WithFields(fields).Info("This is an info message with context") logrus.WithFields(fields).Warn("This is a warning message with context") logrus.WithFields(fields).Error("This is an error message with context") }
在这个示例中,我们首先导入了 logrus 包,并设置了日志输出和日志级别。然后,我们创建了一个名为 fields
的变量,其中包含了上下文信息。接下来,我们使用 WithFields
方法将这些上下文信息添加到日志中,并记录了不同级别的日志。
运行这个程序,你将看到类似以下的输出:
time="2022-01-01T00:00:00+00:00" level=debug msg="This is a debug message with context" user_id=123 user_name="John Doe" request_id="abc123" time="2022-01-01T00:00:00+00:00" level=info msg="This is an info message with context" user_id=123 user_name="John Doe" request_id="abc123" time="2022-01-01T00:00:00+00:00" level=warn msg="This is a warning message with context" user_id=123 user_name="John Doe" request_id="abc123" time="2022-01-01T00:00:00+00:00" level=error msg="This is an error message with context" user_id=123 user_name="John Doe" request_id="abc123"
可以看到,日志中包含了我们添加的上下文信息。