2023-02-27 12:20:07 +01:00
|
|
|
package formatter
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
// TextFormatter formats logs into text with included source code's path
|
|
|
|
type TextFormatter struct {
|
2023-03-17 10:37:27 +01:00
|
|
|
timestampFormat string
|
|
|
|
levelDesc []string
|
2023-02-27 12:20:07 +01:00
|
|
|
}
|
|
|
|
|
2024-08-01 18:22:02 +02:00
|
|
|
// SyslogFormatter formats logs into text
|
|
|
|
type SyslogFormatter struct {
|
|
|
|
levelDesc []string
|
|
|
|
}
|
|
|
|
|
|
|
|
var validLevelDesc = []string{"PANC", "FATL", "ERRO", "WARN", "INFO", "DEBG", "TRAC"}
|
|
|
|
|
|
|
|
|
2023-02-27 12:20:07 +01:00
|
|
|
// NewTextFormatter create new MyTextFormatter instance
|
|
|
|
func NewTextFormatter() *TextFormatter {
|
|
|
|
return &TextFormatter{
|
2024-08-01 18:22:02 +02:00
|
|
|
levelDesc: validLevelDesc,
|
2023-03-17 10:37:27 +01:00
|
|
|
timestampFormat: time.RFC3339, // or RFC3339
|
2023-02-27 12:20:07 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-01 18:22:02 +02:00
|
|
|
// NewSyslogFormatter create new MySyslogFormatter instance
|
|
|
|
func NewSyslogFormatter() *SyslogFormatter {
|
|
|
|
return &SyslogFormatter{
|
|
|
|
levelDesc: validLevelDesc,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-27 12:20:07 +01:00
|
|
|
// Format renders a single log entry
|
|
|
|
func (f *TextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
|
|
|
|
var fields string
|
|
|
|
keys := make([]string, 0, len(entry.Data))
|
|
|
|
for k, v := range entry.Data {
|
|
|
|
if k == "source" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
keys = append(keys, fmt.Sprintf("%s: %v", k, v))
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(keys) > 0 {
|
|
|
|
fields = fmt.Sprintf("[%s] ", strings.Join(keys, ", "))
|
|
|
|
}
|
|
|
|
|
|
|
|
level := f.parseLevel(entry.Level)
|
|
|
|
|
2023-03-17 10:37:27 +01:00
|
|
|
return []byte(fmt.Sprintf("%s %s %s%s: %s\n", entry.Time.Format(f.timestampFormat), level, fields, entry.Data["source"], entry.Message)), nil
|
2023-02-27 12:20:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (f *TextFormatter) parseLevel(level logrus.Level) string {
|
2023-03-17 10:37:27 +01:00
|
|
|
if len(f.levelDesc) < int(level) {
|
2023-02-27 12:20:07 +01:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2023-03-17 10:37:27 +01:00
|
|
|
return f.levelDesc[level]
|
2023-02-27 12:20:07 +01:00
|
|
|
}
|
2024-08-01 18:22:02 +02:00
|
|
|
|
|
|
|
// Format renders a single log entry
|
|
|
|
func (f *SyslogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
|
|
|
|
var fields string
|
|
|
|
keys := make([]string, 0, len(entry.Data))
|
|
|
|
for k, v := range entry.Data {
|
|
|
|
if k == "source" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
keys = append(keys, fmt.Sprintf("%s: %v", k, v))
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(keys) > 0 {
|
|
|
|
fields = fmt.Sprintf("[%s] ", strings.Join(keys, ", "))
|
|
|
|
}
|
|
|
|
return []byte(fmt.Sprintf("%s%s\n", fields, entry.Message)), nil
|
|
|
|
}
|