|
1 | 1 | package zapadapter |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "runtime" |
| 5 | + |
4 | 6 | "github.com/graphmetrics/logger-go" |
| 7 | + "github.com/graphmetrics/logger-go/options" |
5 | 8 | "go.uber.org/zap" |
| 9 | + "go.uber.org/zap/zapcore" |
6 | 10 | ) |
7 | 11 |
|
8 | 12 | type zapAdapter struct { |
9 | | - parent *zap.Logger |
| 13 | + parent *zap.Logger |
| 14 | + callerSkipOffset int |
10 | 15 | } |
11 | 16 |
|
12 | 17 | func New(parent *zap.Logger) logger.Logger { |
13 | | - return &zapAdapter{parent: parent} |
| 18 | + return &zapAdapter{parent: parent, callerSkipOffset: 0} |
14 | 19 | } |
15 | 20 |
|
16 | 21 | func (z *zapAdapter) Debug(msg string, metadata map[string]interface{}) { |
17 | | - z.parent.Debug(msg, prepareFields(metadata)...) |
| 22 | + if ce := z.parent.Check(zap.DebugLevel, msg); ce != nil { |
| 23 | + ce.Caller = z.caller() |
| 24 | + ce.Write(prepareFields(metadata)...) |
| 25 | + } |
18 | 26 | } |
19 | 27 |
|
20 | 28 | func (z *zapAdapter) Info(msg string, metadata map[string]interface{}) { |
21 | | - z.parent.Info(msg, prepareFields(metadata)...) |
| 29 | + if ce := z.parent.Check(zap.InfoLevel, msg); ce != nil { |
| 30 | + ce.Caller = z.caller() |
| 31 | + ce.Write(prepareFields(metadata)...) |
| 32 | + } |
22 | 33 | } |
23 | 34 |
|
24 | 35 | func (z *zapAdapter) Warn(msg string, metadata map[string]interface{}) { |
25 | | - z.parent.Warn(msg, prepareFields(metadata)...) |
| 36 | + if ce := z.parent.Check(zap.WarnLevel, msg); ce != nil { |
| 37 | + ce.Caller = z.caller() |
| 38 | + ce.Write(prepareFields(metadata)...) |
| 39 | + } |
26 | 40 | } |
27 | 41 |
|
28 | 42 | func (z *zapAdapter) Error(msg string, metadata map[string]interface{}) { |
29 | | - z.parent.Error(msg, prepareFields(metadata)...) |
| 43 | + if ce := z.parent.Check(zap.ErrorLevel, msg); ce != nil { |
| 44 | + ce.Caller = z.caller() |
| 45 | + ce.Write(prepareFields(metadata)...) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +func (z *zapAdapter) WithOptions(opts ...options.LoggerOption) logger.Logger { |
| 50 | + adapter := z |
| 51 | + for _, o := range opts { |
| 52 | + switch o.Parameter() { |
| 53 | + case "CallerSkipOffset": |
| 54 | + adapter = &zapAdapter{ |
| 55 | + parent: adapter.parent, |
| 56 | + callerSkipOffset: adapter.callerSkipOffset + o.Value().(int), |
| 57 | + } |
| 58 | + break |
| 59 | + case "Named": |
| 60 | + adapter = &zapAdapter{ |
| 61 | + parent: adapter.parent.Named(o.Value().(string)), |
| 62 | + callerSkipOffset: adapter.callerSkipOffset, |
| 63 | + } |
| 64 | + break |
| 65 | + default: |
| 66 | + break |
| 67 | + } |
| 68 | + } |
| 69 | + return adapter |
| 70 | +} |
| 71 | + |
| 72 | +func (z *zapAdapter) caller() zapcore.EntryCaller { |
| 73 | + return zapcore.NewEntryCaller(runtime.Caller(z.callerSkipOffset + 2)) |
30 | 74 | } |
31 | 75 |
|
32 | 76 | func prepareFields(metadata map[string]interface{}) []zap.Field { |
|
0 commit comments