ntfy/log/log.go

100 lines
1.9 KiB
Go
Raw Normal View History

2022-05-30 04:14:14 +02:00
package log
import (
"log"
"strings"
2022-06-01 22:57:35 +02:00
"sync"
2022-05-30 04:14:14 +02:00
)
2022-06-01 22:57:35 +02:00
// Level is a well-known log level, as defined below
2022-05-30 04:14:14 +02:00
type Level int
2022-06-01 22:57:35 +02:00
// Well known log levels
2022-05-30 04:14:14 +02:00
const (
DebugLevel Level = iota
InfoLevel
WarnLevel
ErrorLevel
)
func (l Level) String() string {
switch l {
case DebugLevel:
return "DEBUG"
case InfoLevel:
return "INFO"
case WarnLevel:
return "WARN"
case ErrorLevel:
return "ERROR"
}
return "unknown"
}
var (
level = InfoLevel
2022-06-01 22:57:35 +02:00
mu = &sync.Mutex{}
2022-05-30 04:14:14 +02:00
)
2022-06-01 22:57:35 +02:00
// Debug prints the given message, if the current log level is DEBUG
2022-05-30 04:14:14 +02:00
func Debug(message string, v ...interface{}) {
logIf(DebugLevel, message, v...)
}
2022-06-01 22:57:35 +02:00
// Info prints the given message, if the current log level is INFO or lower
2022-05-30 04:14:14 +02:00
func Info(message string, v ...interface{}) {
logIf(InfoLevel, message, v...)
}
2022-06-01 22:57:35 +02:00
// Warn prints the given message, if the current log level is WARN or lower
2022-05-30 04:14:14 +02:00
func Warn(message string, v ...interface{}) {
logIf(WarnLevel, message, v...)
}
2022-06-01 22:57:35 +02:00
// Error prints the given message, if the current log level is ERROR or lower
2022-05-30 04:14:14 +02:00
func Error(message string, v ...interface{}) {
logIf(ErrorLevel, message, v...)
}
2022-06-01 22:57:35 +02:00
// Fatal prints the given message, and exits the program
2022-05-30 04:14:14 +02:00
func Fatal(v ...interface{}) {
log.Fatalln(v...)
}
2022-06-01 22:57:35 +02:00
// CurrentLevel returns the current log level
func CurrentLevel() Level {
mu.Lock()
defer mu.Unlock()
return level
}
// SetLevel sets a new log level
2022-05-30 04:14:14 +02:00
func SetLevel(newLevel Level) {
2022-06-01 22:57:35 +02:00
mu.Lock()
defer mu.Unlock()
2022-05-30 04:14:14 +02:00
level = newLevel
}
2022-06-01 22:57:35 +02:00
// ToLevel converts a string to a Level. It returns InfoLevel if the string
// does not match any known log levels.
2022-05-30 04:14:14 +02:00
func ToLevel(s string) Level {
switch strings.ToLower(s) {
case "debug":
return DebugLevel
case "info":
return InfoLevel
case "warn", "warning":
return WarnLevel
case "error":
return ErrorLevel
default:
2022-06-01 22:57:35 +02:00
return InfoLevel
2022-05-30 04:14:14 +02:00
}
}
func logIf(l Level, message string, v ...interface{}) {
2022-06-01 22:57:35 +02:00
if CurrentLevel() <= l {
2022-05-30 04:14:14 +02:00
log.Printf(l.String()+" "+message, v...)
}
}