logmania/log/main.go

54 lines
1.3 KiB
Go
Raw Normal View History

2017-06-13 00:21:19 +02:00
// log package with entry as a lib in other go applications
2017-06-11 03:34:11 +02:00
package log
2017-06-11 01:33:35 +02:00
import "fmt"
2017-06-13 00:21:19 +02:00
// a struct with all information of a log entry
2017-06-11 01:33:35 +02:00
type Entry struct {
2017-06-11 03:34:11 +02:00
Level LogLevel `json:"level"`
2017-06-11 01:33:35 +02:00
Fields map[string]interface{} `json:"fields"`
Text string `json:"text"`
}
2017-06-13 00:21:19 +02:00
// save/out current state of log entry
2017-06-11 03:34:11 +02:00
func (e *Entry) Log(level LogLevel, v ...interface{}) {
2017-06-11 01:33:35 +02:00
e.Text = fmt.Sprint(v...)
e.Level = level
save(e)
}
2017-06-13 00:21:19 +02:00
// save/out current state of log entry with formation
2017-06-11 03:34:11 +02:00
func (e *Entry) Logf(level LogLevel, format string, v ...interface{}) {
2017-06-11 01:33:35 +02:00
e.Text = fmt.Sprintf(format, v...)
e.Level = level
save(e)
}
2017-06-13 00:21:19 +02:00
// init new log entry
2017-06-11 01:33:35 +02:00
func New() *Entry {
return &Entry{Fields: make(map[string]interface{})}
}
2017-06-13 00:21:19 +02:00
// add extra value to entry (log entry with context)
2017-06-11 01:33:35 +02:00
func (e *Entry) AddField(key string, value interface{}) *Entry {
e.Fields[key] = value
return e
}
2017-06-13 00:21:19 +02:00
// add multi extra values to entry (log entry with context)
2017-06-11 01:33:35 +02:00
func (e *Entry) AddFields(fields map[string]interface{}) *Entry {
for key, value := range fields {
e.Fields[key] = value
}
return e
}
2017-06-13 00:21:19 +02:00
// create a readable string of extra values (log entry with context)
2017-06-11 01:33:35 +02:00
func (e *Entry) FieldString() string {
2017-06-11 03:34:11 +02:00
text := ""
for key, value := range e.Fields {
text = fmt.Sprintf("%s %s=%v", text, key, value)
}
return text[1:]
2017-06-11 01:33:35 +02:00
}