This repository has been archived on 2024-04-10. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
elektron/elektronLogging/ElektronFormatter.go

52 lines
1.3 KiB
Go
Raw Normal View History

2019-11-13 11:19:04 -05:00
package elektronLogging
import (
"bytes"
2019-11-20 13:33:46 -05:00
"github.com/fatih/color"
2019-11-21 14:02:47 -05:00
elekLog "github.com/sirupsen/logrus"
2019-11-13 11:19:04 -05:00
"strings"
)
type ElektronFormatter struct {
TimestampFormat string
}
2019-11-21 14:02:47 -05:00
func (f ElektronFormatter) getColor(entry *elekLog.Entry) *color.Color {
2019-11-20 13:33:46 -05:00
switch entry.Level {
2019-11-21 14:02:47 -05:00
case elekLog.InfoLevel:
2019-11-20 13:33:46 -05:00
return color.New(color.FgGreen, color.Bold)
2019-11-21 14:02:47 -05:00
case elekLog.WarnLevel:
2019-11-20 13:33:46 -05:00
return color.New(color.FgYellow, color.Bold)
2019-11-21 14:02:47 -05:00
case elekLog.ErrorLevel:
2019-11-20 13:33:46 -05:00
return color.New(color.FgRed, color.Bold)
2019-11-21 14:02:47 -05:00
case elekLog.FatalLevel:
2019-11-20 13:33:46 -05:00
return color.New(color.FgRed, color.Bold)
default:
return color.New(color.FgWhite, color.Bold)
}
2019-11-13 11:19:04 -05:00
}
2019-11-21 14:02:47 -05:00
func (f ElektronFormatter) Format(entry *elekLog.Entry) ([]byte, error) {
2019-11-13 11:19:04 -05:00
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
2019-11-20 13:33:46 -05:00
levelColor := f.getColor(entry)
level := levelColor.Sprintf("[%s]:", strings.ToUpper(entry.Level.String()))
message := strings.Join([]string{level, entry.Time.Format(f.TimestampFormat), entry.Message, " "}, " ")
2019-11-13 11:19:04 -05:00
var formattedFields []string
for key, value := range entry.Data {
2019-11-20 13:33:46 -05:00
formattedFields = append(formattedFields,
strings.Join([]string{key, value.(string)}, "="))
2019-11-13 11:19:04 -05:00
}
2019-11-20 13:33:46 -05:00
2019-11-13 11:19:04 -05:00
b.WriteString(message)
b.WriteString(strings.Join(formattedFields, ", "))
b.WriteByte('\n')
return b.Bytes(), nil
}