1// 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 (
24	"time"
25
26	"go.uber.org/zap/buffer"
27)
28
29// DefaultLineEnding defines the default line ending when writing logs.
30// Alternate line endings specified in EncoderConfig can override this
31// behavior.
32const DefaultLineEnding = "\n"
33
34// A LevelEncoder serializes a Level to a primitive type.
35type LevelEncoder func(Level, PrimitiveArrayEncoder)
36
37// LowercaseLevelEncoder serializes a Level to a lowercase string. For example,
38// InfoLevel is serialized to "info".
39func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder) {
40	enc.AppendString(l.String())
41}
42
43// LowercaseColorLevelEncoder serializes a Level to a lowercase string and adds coloring.
44// For example, InfoLevel is serialized to "info" and colored blue.
45func LowercaseColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) {
46	s, ok := _levelToLowercaseColorString[l]
47	if !ok {
48		s = _unknownLevelColor.Add(l.String())
49	}
50	enc.AppendString(s)
51}
52
53// CapitalLevelEncoder serializes a Level to an all-caps string. For example,
54// InfoLevel is serialized to "INFO".
55func CapitalLevelEncoder(l Level, enc PrimitiveArrayEncoder) {
56	enc.AppendString(l.CapitalString())
57}
58
59// CapitalColorLevelEncoder serializes a Level to an all-caps string and adds color.
60// For example, InfoLevel is serialized to "INFO" and colored blue.
61func CapitalColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) {
62	s, ok := _levelToCapitalColorString[l]
63	if !ok {
64		s = _unknownLevelColor.Add(l.CapitalString())
65	}
66	enc.AppendString(s)
67}
68
69// UnmarshalText unmarshals text to a LevelEncoder. "capital" is unmarshaled to
70// CapitalLevelEncoder, "coloredCapital" is unmarshaled to CapitalColorLevelEncoder,
71// "colored" is unmarshaled to LowercaseColorLevelEncoder, and anything else
72// is unmarshaled to LowercaseLevelEncoder.
73func (e *LevelEncoder) UnmarshalText(text []byte) error {
74	switch string(text) {
75	case "capital":
76		*e = CapitalLevelEncoder
77	case "capitalColor":
78		*e = CapitalColorLevelEncoder
79	case "color":
80		*e = LowercaseColorLevelEncoder
81	default:
82		*e = LowercaseLevelEncoder
83	}
84	return nil
85}
86
87// A TimeEncoder serializes a time.Time to a primitive type.
88type TimeEncoder func(time.Time, PrimitiveArrayEncoder)
89
90// EpochTimeEncoder serializes a time.Time to a floating-point number of seconds
91// since the Unix epoch.
92func EpochTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) {
93	nanos := t.UnixNano()
94	sec := float64(nanos) / float64(time.Second)
95	enc.AppendFloat64(sec)
96}
97
98// EpochMillisTimeEncoder serializes a time.Time to a floating-point number of
99// milliseconds since the Unix epoch.
100func EpochMillisTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) {
101	nanos := t.UnixNano()
102	millis := float64(nanos) / float64(time.Millisecond)
103	enc.AppendFloat64(millis)
104}
105
106// EpochNanosTimeEncoder serializes a time.Time to an integer number of
107// nanoseconds since the Unix epoch.
108func EpochNanosTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) {
109	enc.AppendInt64(t.UnixNano())
110}
111
112// ISO8601TimeEncoder serializes a time.Time to an ISO8601-formatted string
113// with millisecond precision.
114func ISO8601TimeEncoder(t time.Time, enc PrimitiveArrayEncoder) {
115	enc.AppendString(t.Format("2006-01-02T15:04:05.000Z0700"))
116}
117
118// UnmarshalText unmarshals text to a TimeEncoder. "iso8601" and "ISO8601" are
119// unmarshaled to ISO8601TimeEncoder, "millis" is unmarshaled to
120// EpochMillisTimeEncoder, and anything else is unmarshaled to EpochTimeEncoder.
121func (e *TimeEncoder) UnmarshalText(text []byte) error {
122	switch string(text) {
123	case "iso8601", "ISO8601":
124		*e = ISO8601TimeEncoder
125	case "millis":
126		*e = EpochMillisTimeEncoder
127	case "nanos":
128		*e = EpochNanosTimeEncoder
129	default:
130		*e = EpochTimeEncoder
131	}
132	return nil
133}
134
135// A DurationEncoder serializes a time.Duration to a primitive type.
136type DurationEncoder func(time.Duration, PrimitiveArrayEncoder)
137
138// SecondsDurationEncoder serializes a time.Duration to a floating-point number of seconds elapsed.
139func SecondsDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) {
140	enc.AppendFloat64(float64(d) / float64(time.Second))
141}
142
143// NanosDurationEncoder serializes a time.Duration to an integer number of
144// nanoseconds elapsed.
145func NanosDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) {
146	enc.AppendInt64(int64(d))
147}
148
149// StringDurationEncoder serializes a time.Duration using its built-in String
150// method.
151func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) {
152	enc.AppendString(d.String())
153}
154
155// UnmarshalText unmarshals text to a DurationEncoder. "string" is unmarshaled
156// to StringDurationEncoder, and anything else is unmarshaled to
157// NanosDurationEncoder.
158func (e *DurationEncoder) UnmarshalText(text []byte) error {
159	switch string(text) {
160	case "string":
161		*e = StringDurationEncoder
162	case "nanos":
163		*e = NanosDurationEncoder
164	default:
165		*e = SecondsDurationEncoder
166	}
167	return nil
168}
169
170// A CallerEncoder serializes an EntryCaller to a primitive type.
171type CallerEncoder func(EntryCaller, PrimitiveArrayEncoder)
172
173// FullCallerEncoder serializes a caller in /full/path/to/package/file:line
174// format.
175func FullCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) {
176	// TODO: consider using a byte-oriented API to save an allocation.
177	enc.AppendString(caller.String())
178}
179
180// ShortCallerEncoder serializes a caller in package/file:line format, trimming
181// all but the final directory from the full path.
182func ShortCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) {
183	// TODO: consider using a byte-oriented API to save an allocation.
184	enc.AppendString(caller.TrimmedPath())
185}
186
187// UnmarshalText unmarshals text to a CallerEncoder. "full" is unmarshaled to
188// FullCallerEncoder and anything else is unmarshaled to ShortCallerEncoder.
189func (e *CallerEncoder) UnmarshalText(text []byte) error {
190	switch string(text) {
191	case "full":
192		*e = FullCallerEncoder
193	default:
194		*e = ShortCallerEncoder
195	}
196	return nil
197}
198
199// A NameEncoder serializes a period-separated logger name to a primitive
200// type.
201type NameEncoder func(string, PrimitiveArrayEncoder)
202
203// FullNameEncoder serializes the logger name as-is.
204func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder) {
205	enc.AppendString(loggerName)
206}
207
208// UnmarshalText unmarshals text to a NameEncoder. Currently, everything is
209// unmarshaled to FullNameEncoder.
210func (e *NameEncoder) UnmarshalText(text []byte) error {
211	switch string(text) {
212	case "full":
213		*e = FullNameEncoder
214	default:
215		*e = FullNameEncoder
216	}
217	return nil
218}
219
220// An EncoderConfig allows users to configure the concrete encoders supplied by
221// zapcore.
222type EncoderConfig struct {
223	// Set the keys used for each log entry. If any key is empty, that portion
224	// of the entry is omitted.
225	MessageKey    string `json:"messageKey" yaml:"messageKey"`
226	LevelKey      string `json:"levelKey" yaml:"levelKey"`
227	TimeKey       string `json:"timeKey" yaml:"timeKey"`
228	NameKey       string `json:"nameKey" yaml:"nameKey"`
229	CallerKey     string `json:"callerKey" yaml:"callerKey"`
230	StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey"`
231	LineEnding    string `json:"lineEnding" yaml:"lineEnding"`
232	// Configure the primitive representations of common complex types. For
233	// example, some users may want all time.Times serialized as floating-point
234	// seconds since epoch, while others may prefer ISO8601 strings.
235	EncodeLevel    LevelEncoder    `json:"levelEncoder" yaml:"levelEncoder"`
236	EncodeTime     TimeEncoder     `json:"timeEncoder" yaml:"timeEncoder"`
237	EncodeDuration DurationEncoder `json:"durationEncoder" yaml:"durationEncoder"`
238	EncodeCaller   CallerEncoder   `json:"callerEncoder" yaml:"callerEncoder"`
239	// Unlike the other primitive type encoders, EncodeName is optional. The
240	// zero value falls back to FullNameEncoder.
241	EncodeName NameEncoder `json:"nameEncoder" yaml:"nameEncoder"`
242}
243
244// ObjectEncoder is a strongly-typed, encoding-agnostic interface for adding a
245// map- or struct-like object to the logging context. Like maps, ObjectEncoders
246// aren't safe for concurrent use (though typical use shouldn't require locks).
247type ObjectEncoder interface {
248	// Logging-specific marshalers.
249	AddArray(key string, marshaler ArrayMarshaler) error
250	AddObject(key string, marshaler ObjectMarshaler) error
251
252	// Built-in types.
253	AddBinary(key string, value []byte)     // for arbitrary bytes
254	AddByteString(key string, value []byte) // for UTF-8 encoded bytes
255	AddBool(key string, value bool)
256	AddComplex128(key string, value complex128)
257	AddComplex64(key string, value complex64)
258	AddDuration(key string, value time.Duration)
259	AddFloat64(key string, value float64)
260	AddFloat32(key string, value float32)
261	AddInt(key string, value int)
262	AddInt64(key string, value int64)
263	AddInt32(key string, value int32)
264	AddInt16(key string, value int16)
265	AddInt8(key string, value int8)
266	AddString(key, value string)
267	AddTime(key string, value time.Time)
268	AddUint(key string, value uint)
269	AddUint64(key string, value uint64)
270	AddUint32(key string, value uint32)
271	AddUint16(key string, value uint16)
272	AddUint8(key string, value uint8)
273	AddUintptr(key string, value uintptr)
274
275	// AddReflected uses reflection to serialize arbitrary objects, so it's slow
276	// and allocation-heavy.
277	AddReflected(key string, value interface{}) error
278	// OpenNamespace opens an isolated namespace where all subsequent fields will
279	// be added. Applications can use namespaces to prevent key collisions when
280	// injecting loggers into sub-components or third-party libraries.
281	OpenNamespace(key string)
282}
283
284// ArrayEncoder is a strongly-typed, encoding-agnostic interface for adding
285// array-like objects to the logging context. Of note, it supports mixed-type
286// arrays even though they aren't typical in Go. Like slices, ArrayEncoders
287// aren't safe for concurrent use (though typical use shouldn't require locks).
288type ArrayEncoder interface {
289	// Built-in types.
290	PrimitiveArrayEncoder
291
292	// Time-related types.
293	AppendDuration(time.Duration)
294	AppendTime(time.Time)
295
296	// Logging-specific marshalers.
297	AppendArray(ArrayMarshaler) error
298	AppendObject(ObjectMarshaler) error
299
300	// AppendReflected uses reflection to serialize arbitrary objects, so it's
301	// slow and allocation-heavy.
302	AppendReflected(value interface{}) error
303}
304
305// PrimitiveArrayEncoder is the subset of the ArrayEncoder interface that deals
306// only in Go's built-in types. It's included only so that Duration- and
307// TimeEncoders cannot trigger infinite recursion.
308type PrimitiveArrayEncoder interface {
309	// Built-in types.
310	AppendBool(bool)
311	AppendByteString([]byte) // for UTF-8 encoded bytes
312	AppendComplex128(complex128)
313	AppendComplex64(complex64)
314	AppendFloat64(float64)
315	AppendFloat32(float32)
316	AppendInt(int)
317	AppendInt64(int64)
318	AppendInt32(int32)
319	AppendInt16(int16)
320	AppendInt8(int8)
321	AppendString(string)
322	AppendUint(uint)
323	AppendUint64(uint64)
324	AppendUint32(uint32)
325	AppendUint16(uint16)
326	AppendUint8(uint8)
327	AppendUintptr(uintptr)
328}
329
330// Encoder is a format-agnostic interface for all log entry marshalers. Since
331// log encoders don't need to support the same wide range of use cases as
332// general-purpose marshalers, it's possible to make them faster and
333// lower-allocation.
334//
335// Implementations of the ObjectEncoder interface's methods can, of course,
336// freely modify the receiver. However, the Clone and EncodeEntry methods will
337// be called concurrently and shouldn't modify the receiver.
338type Encoder interface {
339	ObjectEncoder
340
341	// Clone copies the encoder, ensuring that adding fields to the copy doesn't
342	// affect the original.
343	Clone() Encoder
344
345	// EncodeEntry encodes an entry and fields, along with any accumulated
346	// context, into a byte buffer and returns it.
347	EncodeEntry(Entry, []Field) (*buffer.Buffer, error)
348}
349