verbose.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package log
  2. import (
  3. "context"
  4. "fmt"
  5. "path/filepath"
  6. "runtime"
  7. "strings"
  8. )
  9. // V reports whether verbosity at the call site is at least the requested level.
  10. // The returned value is a boolean of type Verbose, which implements Info, Infov etc.
  11. // These methods will write to the Info log if called.
  12. // Thus, one may write either
  13. // if log.V(2) { log.Info("log this") }
  14. // or
  15. // log.V(2).Info("log this")
  16. // The second form is shorter but the first is cheaper if logging is off because it does
  17. // not evaluate its arguments.
  18. //
  19. // Whether an individual call to V generates a log record depends on the setting of
  20. // the Config.VLevel and Config.Module flags; both are off by default. If the level in the call to
  21. // V is at least the value of Config.VLevel, or of Config.Module for the source file containing the
  22. // call, the V call will log.
  23. // v must be more than 0.
  24. func V(v int32) Verbose {
  25. var (
  26. file string
  27. )
  28. if v < 0 {
  29. return Verbose(false)
  30. } else if c.V >= v {
  31. return Verbose(true)
  32. }
  33. if pc, _, _, ok := runtime.Caller(1); ok {
  34. file, _ = runtime.FuncForPC(pc).FileLine(pc)
  35. }
  36. if strings.HasSuffix(file, ".go") {
  37. file = file[:len(file)-3]
  38. }
  39. if slash := strings.LastIndex(file, "/"); slash >= 0 {
  40. file = file[slash+1:]
  41. }
  42. for filter, lvl := range c.Module {
  43. var match bool
  44. if match = filter == file; !match {
  45. match, _ = filepath.Match(filter, file)
  46. }
  47. if match {
  48. return Verbose(lvl >= v)
  49. }
  50. }
  51. return Verbose(false)
  52. }
  53. // Info logs a message at the info log level.
  54. func (v Verbose) Info(format string, args ...interface{}) {
  55. if v {
  56. h.Log(context.Background(), _infoLevel, KV(_log, fmt.Sprintf(format, args...)))
  57. }
  58. }
  59. // Infov logs a message at the info log level.
  60. func (v Verbose) Infov(ctx context.Context, args ...D) {
  61. if v {
  62. h.Log(ctx, _infoLevel, args...)
  63. }
  64. }
  65. // Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
  66. func (v Verbose) Infow(ctx context.Context, args ...interface{}) {
  67. if v {
  68. h.Log(ctx, _infoLevel, logw(args)...)
  69. }
  70. }
  71. // Close close resource.
  72. func (v Verbose) Close() (err error) {
  73. if h == nil {
  74. return
  75. }
  76. return h.Close()
  77. }