1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2024-12-23 18:23:27 +01:00
ntfy/log/event.go

232 lines
5.6 KiB
Go
Raw Normal View History

2023-02-04 04:21:50 +01:00
package log
import (
"encoding/json"
"fmt"
"log"
"os"
"sort"
"strings"
"time"
)
const (
2023-02-07 18:02:25 +01:00
tagField = "tag"
errorField = "error"
2023-02-09 21:24:12 +01:00
timeTakenField = "time_taken_ms"
2023-02-08 04:10:51 +01:00
exitCodeField = "exit_code"
2023-02-07 18:02:25 +01:00
timestampFormat = "2006-01-02T15:04:05.999Z07:00"
2023-02-04 04:21:50 +01:00
)
2023-02-06 05:34:27 +01:00
// Event represents a single log event
2023-02-04 04:21:50 +01:00
type Event struct {
2023-02-08 04:10:51 +01:00
Timestamp string `json:"time"`
Level Level `json:"level"`
Message string `json:"message"`
time time.Time
contexters []Contexter
fields Context
2023-02-04 04:21:50 +01:00
}
2023-02-06 05:34:27 +01:00
// newEvent creates a new log event
2023-02-08 04:10:51 +01:00
//
// We delay allocations and processing for efficiency, because most log events
// are never actually rendered, so we don't format the time, or allocate a fields map.
2023-02-04 04:21:50 +01:00
func newEvent() *Event {
return &Event{
2023-02-08 04:10:51 +01:00
time: time.Now(),
2023-02-04 04:21:50 +01:00
}
}
2023-02-06 05:34:27 +01:00
// Fatal logs the event as FATAL, and exits the program with exit code 1
2023-02-04 04:21:50 +01:00
func (e *Event) Fatal(message string, v ...any) {
2023-02-08 04:10:51 +01:00
e.Field(exitCodeField, 1).maybeLog(FatalLevel, message, v...)
2023-02-06 05:53:24 +01:00
fmt.Fprintf(os.Stderr, message+"\n", v...) // Always output error to stderr
2023-02-04 04:21:50 +01:00
os.Exit(1)
}
2023-02-06 05:34:27 +01:00
// Error logs the event with log level error
2023-02-04 04:21:50 +01:00
func (e *Event) Error(message string, v ...any) {
2023-02-08 04:10:51 +01:00
e.maybeLog(ErrorLevel, message, v...)
2023-02-04 04:21:50 +01:00
}
2023-02-06 05:34:27 +01:00
// Warn logs the event with log level warn
2023-02-04 04:21:50 +01:00
func (e *Event) Warn(message string, v ...any) {
2023-02-08 04:10:51 +01:00
e.maybeLog(WarnLevel, message, v...)
2023-02-04 04:21:50 +01:00
}
2023-02-06 05:34:27 +01:00
// Info logs the event with log level info
2023-02-04 04:21:50 +01:00
func (e *Event) Info(message string, v ...any) {
2023-02-08 04:10:51 +01:00
e.maybeLog(InfoLevel, message, v...)
2023-02-04 04:21:50 +01:00
}
2023-02-06 05:34:27 +01:00
// Debug logs the event with log level debug
2023-02-04 04:21:50 +01:00
func (e *Event) Debug(message string, v ...any) {
2023-02-08 04:10:51 +01:00
e.maybeLog(DebugLevel, message, v...)
2023-02-04 04:21:50 +01:00
}
2023-02-06 05:34:27 +01:00
// Trace logs the event with log level trace
2023-02-04 04:21:50 +01:00
func (e *Event) Trace(message string, v ...any) {
2023-02-08 04:10:51 +01:00
e.maybeLog(TraceLevel, message, v...)
2023-02-04 04:21:50 +01:00
}
2023-02-06 05:34:27 +01:00
// Tag adds a "tag" field to the log event
2023-02-04 04:21:50 +01:00
func (e *Event) Tag(tag string) *Event {
2023-02-08 04:10:51 +01:00
return e.Field(tagField, tag)
2023-02-04 04:21:50 +01:00
}
2023-02-06 05:34:27 +01:00
// Time sets the time field
2023-02-07 18:02:25 +01:00
func (e *Event) Time(t time.Time) *Event {
2023-02-08 04:10:51 +01:00
e.time = t
2023-02-06 05:34:27 +01:00
return e
}
2023-02-09 21:24:12 +01:00
// Timing runs f and records the time if took to execute it in "time_taken_ms"
func (e *Event) Timing(f func()) *Event {
start := time.Now()
f()
return e.Field(timeTakenField, time.Since(start).Milliseconds())
}
2023-02-06 05:34:27 +01:00
// Err adds an "error" field to the log event
2023-02-04 04:21:50 +01:00
func (e *Event) Err(err error) *Event {
2023-02-08 21:20:44 +01:00
if err == nil {
return e
} else if c, ok := err.(Contexter); ok {
return e.With(c)
2023-02-06 22:01:32 +01:00
}
2023-02-08 04:10:51 +01:00
return e.Field(errorField, err.Error())
2023-02-04 04:21:50 +01:00
}
2023-02-06 05:34:27 +01:00
// Field adds a custom field and value to the log event
2023-02-04 04:21:50 +01:00
func (e *Event) Field(key string, value any) *Event {
2023-02-08 04:10:51 +01:00
if e.fields == nil {
e.fields = make(Context)
}
2023-02-04 04:21:50 +01:00
e.fields[key] = value
return e
}
2023-02-06 05:34:27 +01:00
// Fields adds a map of fields to the log event
func (e *Event) Fields(fields Context) *Event {
2023-02-08 04:10:51 +01:00
if e.fields == nil {
e.fields = make(Context)
}
2023-02-04 04:21:50 +01:00
for k, v := range fields {
e.fields[k] = v
}
return e
}
2023-02-06 05:34:27 +01:00
// With adds the fields of the given Contexter structs to the log event by calling their With method
func (e *Event) With(contexts ...Contexter) *Event {
2023-02-08 04:10:51 +01:00
if e.contexters == nil {
e.contexters = contexts
} else {
e.contexters = append(e.contexters, contexts...)
2023-02-04 04:21:50 +01:00
}
return e
}
2023-02-08 04:10:51 +01:00
// maybeLog logs the event to the defined output. The event is only logged, if
// either the global log level is >= l, or if the log level in one of the overrides matches
// the level.
//
// If no overrides are defined (default), the Contexter array is not applied unless the event
// is actually logged. If overrides are defined, then Contexters have to be applied in any case
// to determine if they match. This is super complicated, but required for efficiency.
func (e *Event) maybeLog(l Level, message string, v ...any) {
appliedContexters := e.maybeApplyContexters()
if !e.shouldLog(l) {
return
}
2023-02-04 04:21:50 +01:00
e.Message = fmt.Sprintf(message, v...)
e.Level = l
2023-02-08 04:10:51 +01:00
e.Timestamp = e.time.Format(timestampFormat)
if !appliedContexters {
e.applyContexters()
}
if CurrentFormat() == JSONFormat {
log.Println(e.JSON())
} else {
log.Println(e.String())
2023-02-04 04:21:50 +01:00
}
}
// Loggable returns true if the given log level is lower or equal to the current log level
func (e *Event) Loggable(l Level) bool {
return e.globalLevelWithOverride() <= l
}
// IsTrace returns true if the current log level is TraceLevel
func (e *Event) IsTrace() bool {
return e.Loggable(TraceLevel)
}
// IsDebug returns true if the current log level is DebugLevel or below
func (e *Event) IsDebug() bool {
return e.Loggable(DebugLevel)
}
2023-02-06 05:34:27 +01:00
// JSON returns the event as a JSON representation
2023-02-04 04:21:50 +01:00
func (e *Event) JSON() string {
b, _ := json.Marshal(e)
s := string(b)
if len(e.fields) > 0 {
b, _ := json.Marshal(e.fields)
s = fmt.Sprintf("{%s,%s}", s[1:len(s)-1], string(b[1:len(b)-1]))
}
return s
}
2023-02-06 05:34:27 +01:00
// String returns the event as a string
2023-02-04 04:21:50 +01:00
func (e *Event) String() string {
if len(e.fields) == 0 {
return fmt.Sprintf("%s %s", e.Level.String(), e.Message)
}
fields := make([]string, 0)
for k, v := range e.fields {
fields = append(fields, fmt.Sprintf("%s=%v", k, v))
}
sort.Strings(fields)
return fmt.Sprintf("%s %s (%s)", e.Level.String(), e.Message, strings.Join(fields, ", "))
}
2023-02-08 04:10:51 +01:00
func (e *Event) shouldLog(l Level) bool {
return e.globalLevelWithOverride() <= l
2023-02-04 04:21:50 +01:00
}
func (e *Event) globalLevelWithOverride() Level {
2023-02-10 01:45:02 +01:00
mu.RLock()
2023-02-04 04:21:50 +01:00
l, ov := level, overrides
2023-02-10 01:45:02 +01:00
mu.RUnlock()
2023-02-08 04:10:51 +01:00
if e.fields == nil {
return l
}
2023-02-04 04:21:50 +01:00
for field, override := range ov {
value, exists := e.fields[field]
2023-02-09 04:57:10 +01:00
if exists {
2023-02-10 02:49:45 +01:00
if override.value == "" || override.value == value || override.value == fmt.Sprintf("%v", value) {
2023-02-09 04:57:10 +01:00
return override.level
}
2023-02-04 04:21:50 +01:00
}
}
return l
}
2023-02-08 04:10:51 +01:00
func (e *Event) maybeApplyContexters() bool {
2023-02-10 01:45:02 +01:00
mu.RLock()
2023-02-08 04:10:51 +01:00
hasOverrides := len(overrides) > 0
2023-02-10 01:45:02 +01:00
mu.RUnlock()
2023-02-08 04:10:51 +01:00
if hasOverrides {
e.applyContexters()
}
return hasOverrides // = applied
}
func (e *Event) applyContexters() {
for _, c := range e.contexters {
e.Fields(c.Context())
}
}