blob: 5db4afb302b3785d133369a1be26ac713c7ea91c [file] [log] [blame]
Don Newton7577f072020-01-06 12:41:11 -05001// 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
21package zapcore
22
23import "go.uber.org/multierr"
24
25type hooked struct {
26 Core
27 funcs []func(Entry) error
28}
29
30// RegisterHooks wraps a Core and runs a collection of user-defined callback
31// hooks each time a message is logged. Execution of the callbacks is blocking.
32//
33// This offers users an easy way to register simple callbacks (e.g., metrics
34// collection) without implementing the full Core interface.
35func RegisterHooks(core Core, hooks ...func(Entry) error) Core {
36 funcs := append([]func(Entry) error{}, hooks...)
37 return &hooked{
38 Core: core,
39 funcs: funcs,
40 }
41}
42
43func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {
44 // Let the wrapped Core decide whether to log this message or not. This
45 // also gives the downstream a chance to register itself directly with the
46 // CheckedEntry.
47 if downstream := h.Core.Check(ent, ce); downstream != nil {
48 return downstream.AddCore(ent, h)
49 }
50 return ce
51}
52
53func (h *hooked) With(fields []Field) Core {
54 return &hooked{
55 Core: h.Core.With(fields),
56 funcs: h.funcs,
57 }
58}
59
60func (h *hooked) Write(ent Entry, _ []Field) error {
61 // Since our downstream had a chance to register itself directly with the
62 // CheckedMessage, we don't need to call it here.
63 var err error
64 for i := range h.funcs {
65 err = multierr.Append(err, h.funcs[i](ent))
66 }
67 return err
68}