// Create a new instance of the logger. You can have any number of instances. var log = logrus.New()
func main() { // The API for setting attributes is a little different than the package level // exported logger. See Godoc. log.Out = os.Stdout
// You could set this to any `io.Writer` such as a file // 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") }
logger, _ := zap.NewProduction() defer logger.Sync() // flushes buffer, if any sugar := logger.Sugar() sugar.Infow("failed to fetch URL", // Structured context as loosely typed key-value pairs. "url", url, "attempt", 3, "backoff", time.Second, ) sugar.Infof("Failed to fetch URL: %s", url)
输出
1 2 3
{"level":"info","ts":1703922949.209576,"caller":"server/main.go:109","msg":"failed to fetch URL","url":"http://example.com","attempt":3,"backoff":1} {"level":"info","ts":1703922949.209731,"caller":"server/main.go:115","msg":"Failed to fetch URL: http://example.com"}
在性能要求高且需要类型安全的场景下,适合使用Logger
1 2 3 4 5 6 7 8 9 10
logger, _ := zap.NewProduction() defer logger.Sync() url := "http://example.com" logger.Info("failed to fetch URL", // Structured context as strongly typed Field values. zap.String("url", url), zap.Int("attempt", 3), zap.Duration("backoff", time.Second), )
输出
1 2
{"level":"info","ts":1703923022.603034,"caller":"server/main.go:108","msg":"failed to fetch URL","url":"http://example.com","attempt":3,"backoff":1}
// POST JSON string // No need to set content type, if you have client level setting resp, err := client.R(). SetHeader("Content-Type", "application/json"). SetBody(`{"username":"testuser", "password":"testpass"}`). SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). Post("https://myapp.com/login")