logmania/log/hook/output/main.go

93 lines
1.7 KiB
Go
Raw Normal View History

2017-06-13 00:21:19 +02:00
// logger to print log entry (with color)
// this logger would be bind by importing
2017-06-11 03:34:11 +02:00
package output
import (
"fmt"
"os"
"time"
2017-06-12 22:32:27 +02:00
"github.com/bclicn/color"
2017-06-11 03:34:11 +02:00
"github.com/genofire/logmania/log"
)
var (
TimeFormat = "2006-01-02 15:04:05"
ShowTime = true
AboveLevel = log.InfoLevel
)
2017-06-13 00:21:19 +02:00
// logger for output
2017-06-12 22:32:27 +02:00
type Logger struct {
log.Logger
TimeFormat string
ShowTime bool
AboveLevel log.LogLevel
}
2017-06-13 00:21:19 +02:00
// CurrentLogger (for override settings e.g. AboveLevel,ShowTime or TimeFormat)
2017-06-12 22:32:27 +02:00
var CurrentLogger *Logger
2017-06-13 00:21:19 +02:00
// create a new output logger
2017-06-12 22:32:27 +02:00
func NewLogger() *Logger {
return &Logger{
TimeFormat: "2006-01-02 15:04:05",
ShowTime: true,
AboveLevel: log.InfoLevel,
}
}
2017-06-13 00:21:19 +02:00
// handle a log entry (print it on the terminal with color)
2017-06-12 22:32:27 +02:00
func (l *Logger) Hook(e *log.Entry) {
2017-06-11 03:34:11 +02:00
if e.Level < AboveLevel {
return
}
v := []interface{}{}
format := "[%s] %s"
if ShowTime {
format = "%s [%s] %s"
2017-06-12 22:32:27 +02:00
v = append(v, color.LightBlue(time.Now().Format(TimeFormat)))
}
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-11 03:34:11 +02:00
os.Stderr.WriteString(text)
} else {
os.Stdout.WriteString(text)
}
}
2017-06-13 00:21:19 +02:00
// do nothing - terminal did not need something to close
2017-06-12 22:32:27 +02:00
func (l *Logger) Close() {
}
2017-06-11 03:34:11 +02:00
func init() {
2017-06-12 22:32:27 +02:00
CurrentLogger = NewLogger()
log.AddLogger(CurrentLogger)
2017-06-11 03:34:11 +02:00
}