hook.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) 2016 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. package zapcore
  21. import "go.uber.org/multierr"
  22. type hooked struct {
  23. Core
  24. funcs []func(Entry) error
  25. }
  26. // RegisterHooks wraps a Core and runs a collection of user-defined callback
  27. // hooks each time a message is logged. Execution of the callbacks is blocking.
  28. //
  29. // This offers users an easy way to register simple callbacks (e.g., metrics
  30. // collection) without implementing the full Core interface.
  31. func RegisterHooks(core Core, hooks ...func(Entry) error) Core {
  32. funcs := append([]func(Entry) error{}, hooks...)
  33. return &hooked{
  34. Core: core,
  35. funcs: funcs,
  36. }
  37. }
  38. func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {
  39. // Let the wrapped Core decide whether to log this message or not. This
  40. // also gives the downstream a chance to register itself directly with the
  41. // CheckedEntry.
  42. if downstream := h.Core.Check(ent, ce); downstream != nil {
  43. return downstream.AddCore(ent, h)
  44. }
  45. return ce
  46. }
  47. func (h *hooked) With(fields []Field) Core {
  48. return &hooked{
  49. Core: h.Core.With(fields),
  50. funcs: h.funcs,
  51. }
  52. }
  53. func (h *hooked) Write(ent Entry, _ []Field) error {
  54. // Since our downstream had a chance to register itself directly with the
  55. // CheckedMessage, we don't need to call it here.
  56. var err error
  57. for i := range h.funcs {
  58. err = multierr.Append(err, h.funcs[i](ent))
  59. }
  60. return err
  61. }