@marcel91200 / caddy Mirror · read-only
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 10, 23:45 UTC

master
go 82 lines 2.06 KB
Raw
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package internal
16
17 import (
18 "sync"
19
20 "go.uber.org/zap"
21 "go.uber.org/zap/zapcore"
22 )
23
24 // LogBufferCore is a zapcore.Core that buffers log entries in memory.
25 type LogBufferCore struct {
26 mu sync.Mutex
27 entries []zapcore.Entry
28 fields [][]zapcore.Field
29 level zapcore.LevelEnabler
30 }
31
32 type LogBufferCoreInterface interface {
33 zapcore.Core
34 FlushTo(*zap.Logger)
35 }
36
37 func NewLogBufferCore(level zapcore.LevelEnabler) *LogBufferCore {
38 return &LogBufferCore{
39 level: level,
40 }
41 }
42
43 func (c *LogBufferCore) Enabled(lvl zapcore.Level) bool {
44 return c.level.Enabled(lvl)
45 }
46
47 func (c *LogBufferCore) With(fields []zapcore.Field) zapcore.Core {
48 return c
49 }
50
51 func (c *LogBufferCore) Check(entry zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
52 if c.Enabled(entry.Level) {
53 return ce.AddCore(entry, c)
54 }
55 return ce
56 }
57
58 func (c *LogBufferCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {
59 c.mu.Lock()
60 defer c.mu.Unlock()
61 c.entries = append(c.entries, entry)
62 c.fields = append(c.fields, fields)
63 return nil
64 }
65
66 func (c *LogBufferCore) Sync() error { return nil }
67
68 // FlushTo flushes buffered logs to the given zap.Logger.
69 func (c *LogBufferCore) FlushTo(logger *zap.Logger) {
70 c.mu.Lock()
71 defer c.mu.Unlock()
72 for idx, entry := range c.entries {
73 logger.WithOptions().Check(entry.Level, entry.Message).Write(c.fields[idx]...)
74 }
75 c.entries = nil
76 c.fields = nil
77 }
78
79 var (
80 _ zapcore.Core = (*LogBufferCore)(nil)
81 _ LogBufferCoreInterface = (*LogBufferCore)(nil)
82 )