options.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package logger
  2. import (
  3. "context"
  4. "io"
  5. )
  6. type Option func(*Options)
  7. type Options struct {
  8. // 日志记录级别,默认值为`InfoLevel`
  9. Level Level
  10. // 记录的字段
  11. Fields map[string]interface{}
  12. // 通常将其设置为文件, 默认值 `os.Stderr`
  13. Out io.Writer
  14. // 调用方跳过文件的帧数:行信息
  15. CallerSkipCount int
  16. Context context.Context
  17. // Name logger 名称
  18. Name string
  19. }
  20. // WithFields 设置记录器的默认字段
  21. func WithFields(fields map[string]interface{}) Option {
  22. return func(args *Options) {
  23. args.Fields = fields
  24. }
  25. }
  26. // WithLevel 设置记录器的默认级别
  27. func WithLevel(level Level) Option {
  28. return func(args *Options) {
  29. args.Level = level
  30. }
  31. }
  32. // WithOutput 设置记录器的默认输出编写器
  33. func WithOutput(out io.Writer) Option {
  34. return func(args *Options) {
  35. args.Out = out
  36. }
  37. }
  38. // WithCallerSkipCount 设置帧跳过数
  39. func WithCallerSkipCount(c int) Option {
  40. return func(args *Options) {
  41. args.CallerSkipCount = c
  42. }
  43. }
  44. // WithName 设置记录器的默认名称
  45. func WithName(name string) Option {
  46. return func(args *Options) {
  47. args.Name = name
  48. }
  49. }
  50. func SetOption(k, v interface{}) Option {
  51. return func(o *Options) {
  52. if o.Context == nil {
  53. o.Context = context.Background()
  54. }
  55. o.Context = context.WithValue(o.Context, k, v)
  56. }
  57. }