1//  Copyright (c) 2016 Couchbase, Inc.
2//  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
3//  except in compliance with the License. You may obtain a copy of the License at
4//    http://www.apache.org/licenses/LICENSE-2.0
5//  Unless required by applicable law or agreed to in writing, software distributed under the
6//  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
7//  either express or implied. See the License for the specific language governing permissions
8//  and limitations under the License.
9
10package logging
11
12import (
13	"bytes"
14	"encoding/json"
15	"fmt"
16	"io"
17	"log"
18	"time"
19)
20
21type goLogger struct {
22	logger         *log.Logger
23	level          Level
24	entryFormatter formatter
25}
26
27const (
28	_LEVEL  = "_level"
29	_MSG    = "_msg"
30	_TIME   = "_time"
31	_RLEVEL = "_rlevel"
32)
33
34func NewLogger(out io.Writer, lvl Level, fmtLogging LogEntryFormatter) *goLogger {
35	logger := &goLogger{
36		logger: log.New(out, "", 0),
37		level:  lvl,
38	}
39	if fmtLogging == JSONFORMATTER {
40		logger.entryFormatter = &jsonFormatter{}
41	} else if fmtLogging == KVFORMATTER {
42		logger.entryFormatter = &keyvalueFormatter{}
43	} else {
44		logger.entryFormatter = &textFormatter{}
45	}
46	return logger
47}
48
49func (gl *goLogger) Logp(level Level, msg string, kv ...Pair) {
50	if gl.logger == nil {
51		return
52	}
53	if level <= gl.level {
54		e := newLogEntry(msg, level)
55		copyPairs(e, kv)
56		gl.log(e)
57	}
58}
59
60func (gl *goLogger) Debugp(msg string, kv ...Pair) {
61	gl.Logp(DEBUG, msg, kv...)
62}
63
64func (gl *goLogger) Tracep(msg string, kv ...Pair) {
65	gl.Logp(TRACE, msg, kv...)
66}
67
68func (gl *goLogger) Requestp(rlevel Level, msg string, kv ...Pair) {
69	if gl.logger == nil {
70		return
71	}
72	if REQUEST <= gl.level {
73		e := newLogEntry(msg, REQUEST)
74		e.Rlevel = rlevel
75		copyPairs(e, kv)
76		gl.log(e)
77	}
78}
79
80func (gl *goLogger) Infop(msg string, kv ...Pair) {
81	gl.Logp(INFO, msg, kv...)
82}
83
84func (gl *goLogger) Warnp(msg string, kv ...Pair) {
85	gl.Logp(WARN, msg, kv...)
86}
87
88func (gl *goLogger) Errorp(msg string, kv ...Pair) {
89	gl.Logp(ERROR, msg, kv...)
90}
91
92func (gl *goLogger) Severep(msg string, kv ...Pair) {
93	gl.Logp(SEVERE, msg, kv...)
94}
95
96func (gl *goLogger) Fatalp(msg string, kv ...Pair) {
97	gl.Logp(FATAL, msg, kv...)
98}
99
100func (gl *goLogger) Logm(level Level, msg string, kv Map) {
101	if gl.logger == nil {
102		return
103	}
104	if level <= gl.level {
105		e := newLogEntry(msg, level)
106		e.Data = kv
107		gl.log(e)
108	}
109}
110
111func (gl *goLogger) Debugm(msg string, kv Map) {
112	gl.Logm(DEBUG, msg, kv)
113}
114
115func (gl *goLogger) Tracem(msg string, kv Map) {
116	gl.Logm(TRACE, msg, kv)
117}
118
119func (gl *goLogger) Requestm(rlevel Level, msg string, kv Map) {
120	if gl.logger == nil {
121		return
122	}
123	if REQUEST <= gl.level {
124		e := newLogEntry(msg, REQUEST)
125		e.Rlevel = rlevel
126		e.Data = kv
127		gl.log(e)
128	}
129}
130
131func (gl *goLogger) Infom(msg string, kv Map) {
132	gl.Logm(INFO, msg, kv)
133}
134
135func (gl *goLogger) Warnm(msg string, kv Map) {
136	gl.Logm(WARN, msg, kv)
137}
138
139func (gl *goLogger) Errorm(msg string, kv Map) {
140	gl.Logm(ERROR, msg, kv)
141}
142
143func (gl *goLogger) Severem(msg string, kv Map) {
144	gl.Logm(SEVERE, msg, kv)
145}
146
147func (gl *goLogger) Fatalm(msg string, kv Map) {
148	gl.Logm(FATAL, msg, kv)
149}
150
151func (gl *goLogger) Logf(level Level, format string, args ...interface{}) {
152	if gl.logger == nil {
153		return
154	}
155	if level <= gl.level {
156		e := newLogEntry(fmt.Sprintf(format, args...), level)
157		gl.log(e)
158	}
159}
160
161func (gl *goLogger) Debugf(format string, args ...interface{}) {
162	gl.Logf(DEBUG, format, args...)
163}
164
165func (gl *goLogger) Tracef(format string, args ...interface{}) {
166	gl.Logf(TRACE, format, args...)
167}
168
169func (gl *goLogger) Requestf(rlevel Level, format string, args ...interface{}) {
170	if gl.logger == nil {
171		return
172	}
173	if REQUEST <= gl.level {
174		e := newLogEntry(fmt.Sprintf(format, args...), REQUEST)
175		e.Rlevel = rlevel
176		gl.log(e)
177	}
178}
179
180func (gl *goLogger) Infof(format string, args ...interface{}) {
181	gl.Logf(INFO, format, args...)
182}
183
184func (gl *goLogger) Warnf(format string, args ...interface{}) {
185	gl.Logf(WARN, format, args...)
186}
187
188func (gl *goLogger) Errorf(format string, args ...interface{}) {
189	gl.Logf(ERROR, format, args...)
190}
191
192func (gl *goLogger) Severef(format string, args ...interface{}) {
193	gl.Logf(SEVERE, format, args...)
194}
195
196func (gl *goLogger) Fatalf(format string, args ...interface{}) {
197	gl.Logf(FATAL, format, args...)
198}
199
200func (gl *goLogger) Level() Level {
201	return gl.level
202}
203
204func (gl *goLogger) SetLevel(level Level) {
205	gl.level = level
206}
207
208func (gl *goLogger) log(newEntry *logEntry) {
209	s := gl.entryFormatter.format(newEntry)
210	gl.logger.Print(s)
211}
212
213type logEntry struct {
214	Time    string
215	Level   Level
216	Rlevel  Level
217	Message string
218	Data    Map
219}
220
221func newLogEntry(msg string, level Level) *logEntry {
222	return &logEntry{
223		Time:    time.Now().Format("2006-01-02T15:04:05.000-07:00"), // time.RFC3339 with milliseconds
224		Level:   level,
225		Rlevel:  NONE,
226		Message: msg,
227	}
228}
229
230func copyPairs(newEntry *logEntry, pairs []Pair) {
231	newEntry.Data = make(Map, len(pairs))
232	for _, p := range pairs {
233		newEntry.Data[p.Name] = p.Value
234	}
235}
236
237type formatter interface {
238	format(*logEntry) string
239}
240
241type textFormatter struct {
242}
243
244// ex. 2016-02-10T09:15:25.498-08:00 [INFO] This is a message from test in text format
245
246func (*textFormatter) format(newEntry *logEntry) string {
247	b := &bytes.Buffer{}
248	appendValue(b, newEntry.Time)
249	if newEntry.Rlevel != NONE {
250		fmt.Fprintf(b, "[%s,%s] ", newEntry.Level.String(), newEntry.Rlevel.String())
251	} else {
252		fmt.Fprintf(b, "[%s] ", newEntry.Level.String())
253	}
254	appendValue(b, newEntry.Message)
255	for key, value := range newEntry.Data {
256		appendKeyValue(b, key, value)
257	}
258	b.WriteByte('\n')
259	s := bytes.NewBuffer(b.Bytes())
260	return s.String()
261}
262
263func appendValue(b *bytes.Buffer, value interface{}) {
264	if _, ok := value.(string); ok {
265		fmt.Fprintf(b, "%s ", value)
266	} else {
267		fmt.Fprintf(b, "%v ", value)
268	}
269}
270
271type keyvalueFormatter struct {
272}
273
274// ex. _time=2016-02-10T09:15:25.498-08:00 _level=INFO _msg=This is a message from test in key-value format
275
276func (*keyvalueFormatter) format(newEntry *logEntry) string {
277	b := &bytes.Buffer{}
278	appendKeyValue(b, _TIME, newEntry.Time)
279	appendKeyValue(b, _LEVEL, newEntry.Level.String())
280	if newEntry.Rlevel != NONE {
281		appendKeyValue(b, _RLEVEL, newEntry.Rlevel.String())
282	}
283	appendKeyValue(b, _MSG, newEntry.Message)
284	for key, value := range newEntry.Data {
285		appendKeyValue(b, key, value)
286	}
287	b.WriteByte('\n')
288	s := bytes.NewBuffer(b.Bytes())
289	return s.String()
290}
291
292func appendKeyValue(b *bytes.Buffer, key, value interface{}) {
293	if _, ok := value.(string); ok {
294		fmt.Fprintf(b, "%v=%s ", key, value)
295	} else {
296		fmt.Fprintf(b, "%v=%v ", key, value)
297	}
298}
299
300type jsonFormatter struct {
301}
302
303// ex. {"_level":"INFO","_msg":"This is a message from test in json format","_time":"2016-02-10T09:12:59.518-08:00"}
304
305func (*jsonFormatter) format(newEntry *logEntry) string {
306	if newEntry.Data == nil {
307		newEntry.Data = make(Map, 5)
308	}
309	newEntry.Data[_TIME] = newEntry.Time
310	newEntry.Data[_LEVEL] = newEntry.Level.String()
311	if newEntry.Rlevel != NONE {
312		newEntry.Data[_RLEVEL] = newEntry.Rlevel.String()
313	}
314	newEntry.Data[_MSG] = newEntry.Message
315	serialized, _ := json.Marshal(newEntry.Data)
316	s := bytes.NewBuffer(append(serialized, '\n'))
317	return s.String()
318}
319