-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgologger.go
376 lines (313 loc) · 8.06 KB
/
gologger.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
gologger is Golang logger.
gologger shows multiple types of attributes in log.
See https://github.com/suganoo/gologger
*/
package gologger
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"os/user"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
type KeyId int
const (
KeyTimestamp KeyId = iota
KeyLogLevel
KeyHostName
KeyProcessId
KeyGoroutineId
KeyUserName
KeyVersion
KeyMessage
KeyFunc
KeyFileName
)
// these are keys for json format.
var knm map[KeyId]string = map[KeyId]string{}
const (
KeyNameTimestamp = "timestamp"
KeyNameLogLevel = "loglevel"
KeyNameHostName = "hostname"
KeyNameProcessId = "pid"
KeyNameGoroutineId = "gid"
KeyNameUserName = "username"
KeyNameVersion = "version"
KeyNameMessage = "msg"
KeyNameFunc = "func"
KeyNameFileName = "filename"
)
type OutputFmtType int
const (
FmtDefault OutputFmtType = iota
FmtJSON
)
type Statement struct {
hostname string
username string
}
type Configuration struct {
Logfile string
ShowDebug bool
st Statement
Version string
Separator string
TimeFormat string
LogItems []KeyId
}
type Gologger struct {
Config Configuration
FormatterInterface
}
var f *(os.File)
var err error
var lock sync.Mutex
func init() {
// these map are for json format.
knm[KeyTimestamp] = KeyNameTimestamp
knm[KeyLogLevel] = KeyNameLogLevel
knm[KeyHostName] = KeyNameHostName
knm[KeyProcessId] = KeyNameProcessId
knm[KeyGoroutineId] = KeyNameGoroutineId
knm[KeyUserName] = KeyNameUserName
knm[KeyVersion] = KeyNameVersion
knm[KeyMessage] = KeyNameMessage
knm[KeyFunc] = KeyNameFunc
knm[KeyFileName] = KeyNameFileName
}
// Write logs as output.
func (g Gologger) Write(bytes []byte) (int, error) {
lock.Lock()
defer lock.Unlock()
msg := string(bytes)
return f.Write(([]byte)(msg))
}
func (g *Gologger) getHostname() string {
return g.Config.st.hostname
}
func (g *Gologger) getUsername() string {
return g.Config.st.username
}
func (g *Gologger) getVersion() string {
return g.Config.Version
}
// SetVersion changes the version.
func (g *Gologger) SetVersion(vers string) {
g.Config.Version = vers
}
// SetSeparator changes the separator of log.
func (g *Gologger) SetSeparator(sep string) {
g.Config.Separator = sep
}
// SetTimeFormat defines the time format.
func (g *Gologger) SetTimeFormat(tf string) {
g.Config.TimeFormat = tf
}
// SetItemsList defines what items should be shown in log.
func (g *Gologger) SetItemsList(itemsList []KeyId) {
g.Config.LogItems = itemsList
}
// SetOutputFormat defines log output format.
func (g *Gologger) SetOutputFormat(typeId OutputFmtType) {
switch typeId {
case FmtDefault:
g.FormatterInterface = MarshallFunc(defaultFormat)
case FmtJSON:
g.FormatterInterface = MarshallFunc(jsonFormat)
default:
g.FormatterInterface = MarshallFunc(defaultFormat)
}
}
// Log Format
type FormatterInterface interface {
marshall(*Gologger, string, string) string
}
type MarshallFunc func(*Gologger, string, string) string
func (m MarshallFunc) marshall(g *Gologger, logLevel string, msg string) (logMsg string) {
return m(g, logLevel, msg)
}
func defaultFormat(g *Gologger, logLevel string, msg string) (logMsg string) {
for _, item := range g.Config.LogItems {
switch item {
case KeyLogLevel:
// set log level
logMsg = logMsg + logLevel + g.Config.Separator
case KeyMessage:
// set log message
logMsg = logMsg + msg + g.Config.Separator
default:
logMsg = logMsg + g.getItem(item) + g.Config.Separator
}
}
return
}
func jsonFormat(g *Gologger, logLevel string, msg string) (logMsg string) {
logMap := map[string]string{}
for _, item := range g.Config.LogItems {
switch item {
case KeyLogLevel:
// set log level
logMap[knm[item]] = logLevel
case KeyMessage:
// set log message
logMap[knm[item]] = msg
case KeyGoroutineId:
// split goroutine id, ex. gid:1 -> 1
logMap[knm[item]] = strings.Split(g.getItem(item), ":")[1]
default:
logMap[knm[item]] = g.getItem(item)
}
}
str, _ := json.Marshal(logMap)
logMsg = string(str)
return
}
func (g *Gologger) getItem(logType KeyId) string {
switch logType {
case KeyTimestamp:
// set timestamp
timestamp := time.Now().Format(g.Config.TimeFormat)
return timestamp
case KeyHostName:
// set hostname
//return st.getHostname()
return g.getHostname()
case KeyProcessId:
// set process id
pid := os.Getpid()
return strconv.Itoa(pid)
case KeyGoroutineId:
// get and set goroutine id
rsb := make([]byte, 64)
// the content of runtime stack is like this.
// ----------------------------
// goroutine 1 [running]:
// main.main()
// C:/.....
runtime.Stack(rsb, false)
// so get goroutine id
// "goroutine 1 [running]:" --> "1"
return KeyNameGoroutineId + ":" + strings.Split(string(rsb), " ")[1]
case KeyUserName:
// set user name
//return st.getUsername()
return g.getUsername()
case KeyVersion:
// set version
return g.getVersion()
case KeyFunc, KeyFileName:
// call file statement
programCounter, filePath, fileLineNum, _ := runtime.Caller(4)
filePathArry := strings.Split(fmt.Sprintf("%v", filePath), "/")
if logType == KeyFunc {
// set called function name
fn := runtime.FuncForPC(programCounter)
fnNameArry := strings.Split(fn.Name(), ".")
return fnNameArry[1]
}
if logType == KeyFileName {
// set filename with line number
return "[" + filePathArry[len(filePathArry)-1] + ":" + strconv.Itoa(fileLineNum) + "]"
}
default:
return ""
}
return ""
}
// NewGologger returns Gologger object.
func NewGologger(conf Configuration) *Gologger {
gl := &Gologger{
Config: conf,
}
if gl.Config.Logfile == "" {
f = os.Stdout
} else {
f, err = os.OpenFile(gl.Config.Logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
errors.New("Error opening log file!" + err.Error())
os.Exit(1)
}
}
// set Formatter
gl.FormatterInterface = MarshallFunc(defaultFormat)
// set hostname, username ....
hostname, _ := os.Hostname()
gl.Config.st.hostname = hostname
user, _ := user.Current()
gl.Config.st.username = user.Username
// version
if gl.Config.Version == "" {
gl.Config.Version = "1.0.0"
}
// separator
if gl.Config.Separator == "" {
gl.Config.Separator = "\t"
}
// time format
if gl.Config.TimeFormat == "" {
gl.Config.TimeFormat = "2006-01-02T15:04:05.000-07:00"
}
// set log item
if gl.Config.LogItems == nil {
gl.Config.LogItems = append(gl.Config.LogItems, KeyTimestamp)
gl.Config.LogItems = append(gl.Config.LogItems, KeyLogLevel)
gl.Config.LogItems = append(gl.Config.LogItems, KeyHostName)
gl.Config.LogItems = append(gl.Config.LogItems, KeyProcessId)
gl.Config.LogItems = append(gl.Config.LogItems, KeyGoroutineId)
gl.Config.LogItems = append(gl.Config.LogItems, KeyUserName)
gl.Config.LogItems = append(gl.Config.LogItems, KeyVersion)
gl.Config.LogItems = append(gl.Config.LogItems, KeyMessage)
gl.Config.LogItems = append(gl.Config.LogItems, KeyFunc)
gl.Config.LogItems = append(gl.Config.LogItems, KeyFileName)
}
// log settings
log.SetFlags(0)
log.SetOutput(gl)
return gl
}
// MuteDebug mutes debug log.
func (g *Gologger) MuteDebug() {
g.Config.ShowDebug = false
}
// UnmuteDebug unmutes debug log.
func (g *Gologger) UnmuteDebug() {
g.Config.ShowDebug = true
}
// CloseFile close the output file.
func (g *Gologger) CloseFile() {
f.Close()
}
// Debug writes log as Debug level.
func (g *Gologger) Debug(v ...interface{}) {
if !g.Config.ShowDebug {
return
}
msg := fmt.Sprintf("%v", v)
logMsg := g.marshall(g, "DEBUG", msg[1:len(msg)-1])
log.Println(logMsg)
}
// Info writes log as Info level.
func (g *Gologger) Info(v ...interface{}) {
msg := fmt.Sprintf("%v", v)
logMsg := g.marshall(g, "INFO", msg[1:len(msg)-1])
log.Println(logMsg)
}
// Warning writes log as Warning level.
func (g *Gologger) Warning(v ...interface{}) {
msg := fmt.Sprintf("%v", v)
logMsg := g.marshall(g, "WARNING", msg[1:len(msg)-1])
log.Println(logMsg)
}
// Error writes log as Error level.
func (g *Gologger) Error(v ...interface{}) {
msg := fmt.Sprintf("%v", v)
logMsg := g.marshall(g, "ERROR", msg[1:len(msg)-1])
log.Println(logMsg)
}