基于 `zap` 包封装。除了实现 `Go` 日志包的基本功能外,还实现了很多高级功能 本包基于`github.com/tkestack/tke/pkg/util/log`裁剪
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.8 KiB

2 years ago
  1. // Copyright 2020 Lingfei Kong <colin404@foxmail.com>. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "context"
  7. "flag"
  8. "cynking.com/pkg/log"
  9. )
  10. var (
  11. h bool
  12. level int
  13. format string
  14. )
  15. func main() {
  16. flag.BoolVar(&h, "h", false, "Print this help.")
  17. flag.IntVar(&level, "l", 0, "Log level.")
  18. flag.StringVar(&format, "f", "console", "log output format.")
  19. flag.Parse()
  20. if h {
  21. flag.Usage()
  22. return
  23. }
  24. // logger配置
  25. opts := &log.Options{
  26. Level: "debug",
  27. Format: "console",
  28. EnableColor: true, // if you need output to local path, with EnableColor must be false.
  29. DisableCaller: true,
  30. OutputPaths: []string{"test.log", "stdout"},
  31. ErrorOutputPaths: []string{"error.log"},
  32. }
  33. // 初始化全局logger
  34. log.Init(opts)
  35. defer log.Flush()
  36. // Debug、Info(with field)、Warnf、Errorw使用
  37. log.Debug("This is a debug message")
  38. log.Info("This is a info message", log.Int32("int_key", 10))
  39. log.Warnf("This is a formatted %s message", "warn")
  40. log.Errorw("Message printed with Errorw", "X-Request-ID", "fbf54504-64da-4088-9b86-67824a7fb508")
  41. // WithValues使用
  42. lv := log.WithValues("X-Request-ID", "7a7b9f24-4cae-4b2a-9464-69088b45b904")
  43. lv.Infow("Info message printed with [WithValues] logger")
  44. lv.Infow("Debug message printed with [WithValues] logger")
  45. // Context使用
  46. ctx := lv.WithContext(context.Background())
  47. lc := log.FromContext(ctx)
  48. lc.Info("Message printed with [WithContext] logger")
  49. ln := lv.WithName("test")
  50. ln.Info("Message printed with [WithName] logger")
  51. // V level使用
  52. log.V(log.InfoLevel).Info("This is a V level message")
  53. log.V(log.ErrorLevel).
  54. Infow("This is a V level message with fields", "X-Request-ID", "7a7b9f24-4cae-4b2a-9464-69088b45b904")
  55. }