Debian Codegraph @

debian/vendor/github.com/pingcap/log/zap_text_core.go

raw
1 // Copyright 2019 PingCAP, Inc.
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 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package log
15
16 import "go.uber.org/zap/zapcore"
17
18 // NewTextCore creates a Core that writes logs to a WriteSyncer.
19 func NewTextCore(enc *textEncoder, ws zapcore.WriteSyncer, enab zapcore.LevelEnabler) zapcore.Core {
20 return &textIOCore{
21 LevelEnabler: enab,
22 enc: enc,
23 out: ws,
24 }
25 }
26
27 // textIOCore is a copy of zapcore.ioCore that only accept *textEncoder
28 // it can be removed after https://github.com/uber-go/zap/pull/685 be merged
29 type textIOCore struct {
30 zapcore.LevelEnabler
31 enc *textEncoder
32 out zapcore.WriteSyncer
33 }
34
35 func (c *textIOCore) With(fields []zapcore.Field) zapcore.Core {
36 clone := c.clone()
37 // it's different to ioCore, here call textEncoder#addFields to fix https://github.com/pingcap/log/issues/3
38 clone.enc.addFields(fields)
39 return clone
40 }
41
42 func (c *textIOCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
43 if c.Enabled(ent.Level) {
44 return ce.AddCore(ent, c)
45 }
46 return ce
47 }
48
49 func (c *textIOCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
50 buf, err := c.enc.EncodeEntry(ent, fields)
51 if err != nil {
52 return err
53 }
54 _, err = c.out.Write(buf.Bytes())
55 buf.Free()
56 if err != nil {
57 return err
58 }
59 if ent.Level > zapcore.ErrorLevel {
60 // Since we may be crashing the program, sync the output. Ignore Sync
61 // errors, pending a clean solution to issue https://github.com/uber-go/zap/issues/370.
62 c.Sync()
63 }
64 return nil
65 }
66
67 func (c *textIOCore) Sync() error {
68 return c.out.Sync()
69 }
70
71 func (c *textIOCore) clone() *textIOCore {
72 return &textIOCore{
73 LevelEnabler: c.LevelEnabler,
74 enc: c.enc.Clone().(*textEncoder),
75 out: c.out,
76 }
77 }