loggo/print.go
2023-11-02 12:07:38 +01:00

85 lines
2.5 KiB
Go

package loggo
import (
"fmt"
"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)
tmp := ""
if len(extras) > 0 {
tmp = strings.Join(extras, GetExtrasSeparator())
}
formatted = strings.ReplaceAll(formatted, GetExtrasFormat(), tmp)
tmp = ""
if timestamp >= 0 {
tmp = strconv.FormatInt(now.UnixMilli()-timestamp, 10) + "ms"
}
formatted = strings.ReplaceAll(formatted, GetTimediffFormat(), tmp)
fmt.Println(formatted)
if logLevel.level == FatalLevel.level {
os.Exit(1)
}
}