Select Git revision
-
Christel Loftus authoredChristel Loftus authored
format.go 3.23 KiB
package logger
import (
"bytes"
"encoding/json"
"fmt"
"github.com/fatih/color"
)
var nextFormatID = 1
type IFormatter interface {
Format(Entry) []byte
NextColor() IFormatter
Color() string
}
type formatterJSON struct{}
func (f formatterJSON) Format(entry Entry) []byte {
jsonEntry, err := json.Marshal(entry)
if err != nil {
return []byte(fmt.Sprintf("failed to marshal entry: %v: %+v\n", err, entry))
}
return append(jsonEntry, []byte("\n")...)
}
func (f formatterJSON) NextColor() IFormatter {
return f //do not select colors for JSON (only used in console)
}
func (f formatterJSON) Color() string {
return "default"
}
func NewConsole() IFormatter {
nextFormatID++
return formatterConsole{
id: nextFormatID,
fg: 1, //color.FgWhite,
bg: 0, //color.BgBlack,
}
}
type formatterConsole struct {
id int
fg int //color.Attribute
bg int //color.Attribute
}
func (f formatterConsole) Format(entry Entry) []byte {
source := fmt.Sprintf("%s/%s:%d", entry.Caller.Package, entry.Caller.File, entry.Caller.Line)
if len(source) > 40 {
source = source[len(source)-40:]
}
buffer := bytes.NewBuffer(nil)
red := color.New(color.FgRed).FprintfFunc()
magenta := color.New(color.FgMagenta).FprintfFunc()
yellow := color.New(color.FgYellow).FprintfFunc()
green := color.New(color.FgGreen).FprintfFunc()
cyan := color.New(color.FgCyan).FprintfFunc()
cyan(buffer, entry.Timestamp.Format("2006-01-02 15:04:05"))
levelString := fmt.Sprintf(" %5.5s", entry.Level)
switch entry.Level {
case LevelFatal: