loggo/print.go

89 lines
2.8 KiB
Go

package loggo
import (
"os"
"strconv"
"strings"
"time"
)
// debug logging without time difference calculation
func Debug(message string, extras ...string) {
print(DebugLevel, message, -1, extras...)
}
// debug logging with time difference calculation
func DebugTimed(message string, timestamp int64, extras ...string) {
print(DebugLevel, message, timestamp, extras...)
}
// info logging without time difference calculation
func Info(message string, extras ...string) {
print(InfoLevel, message, -1, extras...)
}
// info logging with time difference calculation
func InfoTimed(message string, timestamp int64, extras ...string) {
print(InfoLevel, message, timestamp, extras...)
}
// warning logging without time difference calculation
func Warning(message string, extras ...string) {
print(WarningLevel, message, -1, extras...)
}
// warning logging with time difference calculation
func WarningTimed(message string, timestamp int64, extras ...string) {
print(WarningLevel, message, timestamp, extras...)
}
// error logging without time difference calculation
func Error(message string, extras ...string) {
print(ErrorLevel, message, -1, extras...)
}
// error logging with time difference calculation
func ErrorTimed(message string, timestamp int64, extras ...string) {
print(ErrorLevel, message, timestamp, extras...)
}
// fatal logging without time difference calculation
func Fatal(message string, extras ...string) {
print(FatalLevel, message, -1, extras...)
}
// fatal logging with time difference calculation
func FatalTimed(message string, timestamp int64, extras ...string) {
print(FatalLevel, message, timestamp, extras...)
}
// core logging to console
func print(logLevel logLevel, message string, timestamp int64, extras ...string) {
if len(message) == 0 || logLevel.level < GetLogLevel().level {
return
}
now := time.Now()
formatted := GetLogFormat()
formatted = strings.ReplaceAll(formatted, PLACEHOLDER_TIMESTAMP, now.Format(GetDateFormat()))
formatted = strings.ReplaceAll(formatted, PLACEHOLDER_LOGLEVEL, logLevel.name)
formatted = strings.ReplaceAll(formatted, PLACEHOLDER_MESSAGE, message)
if len(extras) == 0 {
formatted = strings.ReplaceAll(formatted, GetExtrasFormat(), "")
formatted = strings.TrimSpace(formatted)
} else {
format := GetExtrasFormat()
formatted = strings.ReplaceAll(formatted, format, strings.ReplaceAll(format, PLACEHOLDER_EXTRAS, strings.Join(extras, GetExtrasSeparator())))
}
if timestamp <= 0 {
formatted = strings.ReplaceAll(formatted, GetTimediffFormat(), "")
formatted = strings.TrimSpace(formatted)
} else {
format := GetTimediffFormat()
formatted = strings.ReplaceAll(formatted, format, strings.ReplaceAll(format, PLACEHOLDER_TIMEDIFF, strconv.FormatInt(now.UnixMilli()-timestamp, 10)+"ms"))
}
logLevel.color.Println(strings.TrimSpace(formatted))
if logLevel.level == FatalLevel.level {
os.Exit(1)
}
}