logmania/notify/console/main.go

81 lines
1.4 KiB
Go
Raw Normal View History

2017-08-09 08:45:45 +02:00
package console
2017-06-11 03:34:11 +02:00
import (
"fmt"
2017-06-14 23:52:38 +02:00
"io"
2017-06-11 03:34:11 +02:00
"os"
"time"
2017-06-12 22:32:27 +02:00
"github.com/bclicn/color"
2017-08-09 08:45:45 +02:00
"github.com/genofire/logmania/lib"
2017-06-11 03:34:11 +02:00
"github.com/genofire/logmania/log"
2017-08-09 08:45:45 +02:00
"github.com/genofire/logmania/notify"
2017-06-11 03:34:11 +02:00
)
var (
2017-08-09 08:45:45 +02:00
errOutput io.Writer = os.Stderr
output io.Writer = os.Stdout
2017-06-11 03:34:11 +02:00
)
2017-06-13 00:21:19 +02:00
// logger for output
2017-08-09 08:45:45 +02:00
type Notifier struct {
notify.Notifier
2017-06-12 22:32:27 +02:00
TimeFormat string
ShowTime bool
}
2017-08-09 08:45:45 +02:00
func Init(config *lib.NotifyConfig) notify.Notifier {
return &Notifier{
2017-06-12 22:32:27 +02:00
TimeFormat: "2006-01-02 15:04:05",
ShowTime: true,
}
}
2017-06-13 00:21:19 +02:00
// handle a log entry (print it on the terminal with color)
2017-08-09 08:45:45 +02:00
func (n *Notifier) Send(e *log.Entry) {
2017-06-11 03:34:11 +02:00
v := []interface{}{}
format := "[%s] %s"
2017-08-09 08:45:45 +02:00
if n.ShowTime {
2017-06-11 03:34:11 +02:00
format = "%s [%s] %s"
2017-08-09 08:45:45 +02:00
v = append(v, color.LightBlue(time.Now().Format(n.TimeFormat)))
2017-06-12 22:32:27 +02:00
}
lvl := e.Level.String()
switch e.Level {
case log.DebugLevel:
lvl = color.DarkGray(lvl)
case log.InfoLevel:
lvl = color.Green(lvl)
case log.WarnLevel:
lvl = color.Yellow(lvl)
case log.ErrorLevel:
lvl = color.Red(lvl)
case log.PanicLevel:
lvl = color.BRed(lvl)
2017-06-11 03:34:11 +02:00
}
2017-06-12 22:32:27 +02:00
v = append(v, lvl, e.Text)
2017-06-11 03:34:11 +02:00
if len(e.Fields) > 0 {
2017-06-12 22:32:27 +02:00
v = append(v, color.Purple(e.FieldString()))
2017-06-11 03:34:11 +02:00
format = fmt.Sprintf("%s (%%s)\n", format)
} else {
format = fmt.Sprintf("%s\n", format)
}
text := fmt.Sprintf(format, v...)
2017-06-12 22:32:27 +02:00
if e.Level > log.WarnLevel {
2017-06-14 23:52:38 +02:00
errOutput.Write([]byte(text))
2017-06-11 03:34:11 +02:00
} else {
2017-06-14 23:52:38 +02:00
output.Write([]byte(text))
2017-06-11 03:34:11 +02:00
}
}
2017-08-09 08:45:45 +02:00
func (n *Notifier) Close() {}
2017-06-12 22:32:27 +02:00
2017-06-11 03:34:11 +02:00
func init() {
2017-08-09 08:45:45 +02:00
notify.AddNotifier(Init)
2017-06-11 03:34:11 +02:00
}