chinampa/pkg/logger/formatter.go

89 lines
2.2 KiB
Go
Raw Normal View History

// Copyright © 2022 Roberto Hidalgo <chinampa@un.rob.mx>
// SPDX-License-Identifier: Apache-2.0
2023-03-20 06:15:53 +00:00
package logger
import (
"strings"
"time"
"git.rob.mx/nidito/chinampa/pkg/runtime"
"github.com/fatih/color"
2023-03-20 06:15:53 +00:00
"github.com/sirupsen/logrus"
)
var bold *color.Color
var boldRedBG *color.Color
var boldRed *color.Color
var boldYellowBG *color.Color
var boldYellow *color.Color
var dimmed *color.Color
func init() {
bold = color.New(color.Bold)
bold.EnableColor()
2023-03-22 05:12:12 +00:00
boldRedBG = color.New(color.Bold, color.BgRed, 225)
boldRedBG.EnableColor()
boldRed = color.New(color.Bold, color.FgHiRed)
boldRed.EnableColor()
boldYellowBG = color.New(color.Bold, color.BgYellow, color.FgBlack)
boldYellowBG.EnableColor()
boldYellow = color.New(color.Bold, color.FgHiYellow)
boldYellow.EnableColor()
dimmed = color.New(color.Faint)
dimmed.EnableColor()
}
type ttyFormatter struct {
2023-03-20 06:15:53 +00:00
}
func (f *ttyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
2023-03-20 06:15:53 +00:00
prefix := ""
colorEnabled := runtime.ColorEnabled()
2023-03-20 06:34:09 +00:00
message := entry.Message
switch {
case runtime.VerboseEnabled():
2023-03-20 06:15:53 +00:00
date := strings.Replace(entry.Time.Local().Format(time.DateTime), " ", "T", 1)
component := ""
if c, ok := entry.Data[componentKey]; ok {
component = " " + c.(string)
}
2023-03-20 06:34:09 +00:00
level := entry.Level.String()
if colorEnabled {
switch {
case entry.Level <= logrus.ErrorLevel:
level = boldRed.Sprint(level)
case entry.Level == logrus.WarnLevel:
level = boldYellow.Sprint(level)
case entry.Level >= logrus.DebugLevel:
level = dimmed.Sprint(level)
message = dimmed.Sprint(message)
default:
level = dimmed.Sprint(level)
2023-03-20 06:34:09 +00:00
}
}
prefix = dimmed.Sprint(date) + " " + level + dimmed.Sprint(component) + "\t"
case entry.Level == logrus.ErrorLevel:
2023-03-20 06:15:53 +00:00
if colorEnabled {
prefix = boldRedBG.Sprint(" ERROR ") + " "
2023-03-20 06:15:53 +00:00
} else {
prefix = "ERROR: "
}
case entry.Level == logrus.WarnLevel:
2023-03-20 06:15:53 +00:00
if colorEnabled {
prefix = boldYellowBG.Sprint(" WARNING ") + " "
2023-03-20 06:15:53 +00:00
} else {
prefix = "WARNING: "
}
case entry.Level >= logrus.DebugLevel:
2023-03-20 06:34:09 +00:00
if colorEnabled {
prefix = dimmed.Sprintf("%s: ", strings.ToUpper(entry.Level.String()))
message = dimmed.Sprint(message)
2023-03-20 06:34:09 +00:00
} else {
prefix = strings.ToUpper(entry.Level.String()) + ": "
}
2023-03-20 06:15:53 +00:00
}
2023-03-20 06:34:09 +00:00
return []byte(prefix + message + "\n"), nil
2023-03-20 06:15:53 +00:00
}