| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
// This logger implements zapcore.Core and is based on zaptest/observer. |
| 5 |
|
| 6 |
package otelcol // import "go.opentelemetry.io/collector/otelcol" |
| 7 |
|
| 8 |
import ( |
| 9 |
"errors" |
| 10 |
"sync" |
| 11 |
|
| 12 |
"go.uber.org/zap/zapcore" |
| 13 |
) |
| 14 |
|
| 15 |
type loggedEntry struct { |
| 16 |
zapcore.Entry |
| 17 |
Context []zapcore.Field |
| 18 |
} |
| 19 |
|
| 20 |
func newBufferedCore(enab zapcore.LevelEnabler) *bufferedCore { |
| 21 |
return &bufferedCore{LevelEnabler: enab} |
| 22 |
} |
| 23 |
|
| 24 |
var _ zapcore.Core = (*bufferedCore)(nil) |
| 25 |
|
| 26 |
type bufferedCore struct { |
| 27 |
zapcore.LevelEnabler |
| 28 |
mu sync.Mutex |
| 29 |
logs []loggedEntry |
| 30 |
context []zapcore.Field |
| 31 |
logsTaken bool |
| 32 |
} |
| 33 |
|
| 34 |
func (bc *bufferedCore) Level() zapcore.Level { |
| 35 |
return zapcore.LevelOf(bc.LevelEnabler) |
| 36 |
} |
| 37 |
|
| 38 |
func (bc *bufferedCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry { |
| 39 |
if bc.Enabled(ent.Level) { |
| 40 |
return ce.AddCore(ent, bc) |
| 41 |
} |
| 42 |
return ce |
| 43 |
} |
| 44 |
|
| 45 |
func (bc *bufferedCore) With(fields []zapcore.Field) zapcore.Core { |
| 46 |
return &bufferedCore{ |
| 47 |
LevelEnabler: bc.LevelEnabler, |
| 48 |
logs: bc.logs, |
| 49 |
logsTaken: bc.logsTaken, |
| 50 |
context: append(bc.context, fields...), |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
func (bc *bufferedCore) Write(ent zapcore.Entry, fields []zapcore.Field) error { |
| 55 |
bc.mu.Lock() |
| 56 |
defer bc.mu.Unlock() |
| 57 |
if bc.logsTaken { |
| 58 |
return errors.New("the buffered logs have already been taken so writing is no longer supported") |
| 59 |
} |
| 60 |
all := make([]zapcore.Field, 0, len(fields)+len(bc.context)) |
| 61 |
all = append(all, bc.context...) |
| 62 |
all = append(all, fields...) |
| 63 |
bc.logs = append(bc.logs, loggedEntry{ent, all}) |
| 64 |
return nil |
| 65 |
} |
| 66 |
|
| 67 |
func (bc *bufferedCore) Sync() error { |
| 68 |
return nil |
| 69 |
} |
| 70 |
|
| 71 |
func (bc *bufferedCore) TakeLogs() []loggedEntry { |
| 72 |
bc.mu.Lock() |
| 73 |
defer bc.mu.Unlock() |
| 74 |
if bc.logsTaken { |
| 75 |
return nil |
| 76 |
} |
| 77 |
logs := bc.logs |
| 78 |
bc.logs = nil |
| 79 |
bc.logsTaken = true |
| 80 |
return logs |
| 81 |
} |