-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjournal.go
118 lines (93 loc) · 2.24 KB
/
journal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package journal
import (
"encoding/json"
"fmt"
"runtime"
"time"
uuid "github.com./satori/go.uuid"
)
type Journal interface {
// Sometimes log need tags to be grouped or just easier search in log architecture
SetTags(tags ...string) Journal
// Add custom field
AddField(field string, value interface{}) Journal
// Set track id of a log
SetTrackId(trackId interface{}) Journal
// Print the log
Log()
// Get raw json string to be logged
Raw() string
}
type journalLogger struct {
msg string
level string
errRaw error
tags []string
trackId interface{}
fields map[string]interface{}
}
func baseJournal(msg, level string) *journalLogger {
return &journalLogger{msg: msg, level: level, fields: map[string]interface{}{}}
}
// New Journal info interface
func Info(msg string) Journal {
return baseJournal(msg, "info")
}
// New Journal warning interface
func Warning(msg string) Journal {
return baseJournal(msg, "warning")
}
// New Journal error interface
func Error(msg string, err error) Journal {
base := baseJournal(msg, "error")
base.errRaw = err
return base
}
func (j *journalLogger) SetTags(tags ...string) Journal {
j.tags = append(j.tags, tags...)
return j
}
func (j *journalLogger) SetTrackId(trackId interface{}) Journal {
j.trackId = trackId
return j
}
func (j *journalLogger) AddField(field string, value interface{}) Journal {
j.fields[field] = value
return j
}
func (j *journalLogger) Raw() string {
return string(j.compileLog())
}
func (j *journalLogger) Log() {
fmt.Println(string(j.compileLog()))
}
func (j *journalLogger) compileLog() []byte {
j.appendAll()
if j.level == "error" {
_, file, no, ok := runtime.Caller(2)
if ok {
j.fields["caller"] = fmt.Sprintf("%s:%d", file, no)
}
switch j.errRaw.(type) {
case error:
j.fields["error"] = j.errRaw.Error()
default:
j.fields["error"] = j.errRaw
}
}
jsonEncodedString, _ := json.Marshal(j.fields)
return jsonEncodedString
}
func (j *journalLogger) appendAll() {
if j.trackId == nil {
var trackId, _ = uuid.NewV4()
j.trackId = trackId.String()
}
j.fields["track_id"] = j.trackId
j.fields["message"] = j.msg
j.fields["level"] = j.level
if len(j.tags) > 0 {
j.fields["tags"] = j.tags
}
j.fields["timestamp"] = time.Now()
}