80 lines
1.6 KiB
Go
80 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/fatih/color"
|
|
)
|
|
|
|
var (
|
|
DefaultLogger = &Logger{
|
|
output: []io.Writer{os.Stdout},
|
|
}
|
|
log = DefaultLogger
|
|
)
|
|
|
|
type Logger struct {
|
|
output []io.Writer
|
|
}
|
|
|
|
func (l *Logger) AddOutput(out io.Writer) {
|
|
l.output = append(l.output, out)
|
|
}
|
|
|
|
func (l *Logger) ResetOutput() {
|
|
l.output = nil
|
|
}
|
|
|
|
// cat stands for category (Example categories: "INFO", "WARN", "FATAL")
|
|
func (l *Logger) Log(cat string, style *color.Color, a ...any) {
|
|
now := time.Now()
|
|
day, month, year := now.Day(), now.Month(), now.Year()
|
|
hour, min, sec := now.Hour(), now.Minute(), now.Second()
|
|
|
|
dayStr := fmt.Sprint(int(day))
|
|
monthStr := fmt.Sprint(int(month))
|
|
hourStr := fmt.Sprint(int(hour))
|
|
minStr := fmt.Sprint(int(min))
|
|
secStr := fmt.Sprint(int(sec))
|
|
|
|
if len(dayStr) < 2 {
|
|
dayStr = "0" + dayStr
|
|
}
|
|
if len(monthStr) < 2 {
|
|
monthStr = "0" + monthStr
|
|
}
|
|
if len(hourStr) < 2 {
|
|
hourStr = "0" + hourStr
|
|
}
|
|
if len(minStr) < 2 {
|
|
minStr = "0" + minStr
|
|
}
|
|
if len(secStr) < 2 {
|
|
secStr = "0" + secStr
|
|
}
|
|
|
|
s := fmt.Sprint(a...)
|
|
data := fmt.Sprintf("[%s/%s/%d - %s:%s:%s] %s - %s\n", monthStr, dayStr, year, hourStr, minStr, secStr, style.Sprint(cat), s)
|
|
for _, out := range l.output {
|
|
out.Write([]byte(data))
|
|
}
|
|
}
|
|
|
|
func (l *Logger) Info(a ...any) {
|
|
style := color.New(color.FgWhite, color.Bold)
|
|
l.Log("INFO", style, a...)
|
|
}
|
|
|
|
func (l *Logger) Warn(a ...any) {
|
|
style := color.New(color.FgYellow, color.Bold)
|
|
l.Log("WARN", style, a...)
|
|
}
|
|
|
|
func (l *Logger) Fatal(a ...any) {
|
|
style := color.New(color.FgRed, color.Bold)
|
|
l.Log("FATAL", style, a...)
|
|
}
|