Add log.IsGreaterOrEqualTo, that take into consideration path-scoped log levels

This commit is contained in:
Deluan 2023-12-25 16:29:59 -05:00
parent 03119e5ccf
commit 51e07d4cb5
13 changed files with 60 additions and 19 deletions

View File

@ -205,7 +205,7 @@ func Load() {
}
// Print current configuration if log level is Debug
if log.CurrentLevel() >= log.LevelDebug {
if log.IsGreaterOrEqualTo(log.LevelDebug) {
prettyConf := pretty.Sprintf("Loaded configuration from '%s': %# v", Server.ConfigFile, Server)
if Server.EnableLogRedacting {
prettyConf = log.Redact(prettyConf)

View File

@ -134,7 +134,7 @@ func (a *Agents) GetSimilarArtists(ctx context.Context, id, name, mbid string, l
}
similar, err := agent.GetSimilarArtists(ctx, id, name, mbid, limit)
if len(similar) > 0 && err == nil {
if log.CurrentLevel() >= log.LevelTrace {
if log.IsGreaterOrEqualTo(log.LevelTrace) {
log.Debug(ctx, "Got Similar Artists", "agent", ag.AgentName(), "artist", name, "similar", similar, "elapsed", time.Since(start))
} else {
log.Debug(ctx, "Got Similar Artists", "agent", ag.AgentName(), "artist", name, "similarReceived", len(similar), "elapsed", time.Since(start))

View File

@ -160,7 +160,7 @@ func (a *archiver) addFileToZip(ctx context.Context, z *zip.Writer, mf model.Med
}
defer func() {
if err := r.Close(); err != nil && log.CurrentLevel() >= log.LevelDebug {
if err := r.Close(); err != nil && log.IsGreaterOrEqualTo(log.LevelDebug) {
log.Error(ctx, "Error closing stream", "id", mf.ID, "file", mf.Path, err)
}
}()

View File

@ -100,7 +100,7 @@ type ffCmd struct {
func (j *ffCmd) start() error {
cmd := exec.Command(j.args[0], j.args[1:]...) // #nosec
cmd.Stdout = j.out
if log.CurrentLevel() >= log.LevelTrace {
if log.IsGreaterOrEqualTo(log.LevelTrace) {
cmd.Stderr = os.Stderr
} else {
cmd.Stderr = io.Discard

View File

@ -54,7 +54,7 @@ func (j *Executor) start() error {
j.ctx = ctx
cmd := exec.CommandContext(ctx, j.args[0], j.args[1:]...) // #nosec
cmd.Stdout = j.out
if log.CurrentLevel() >= log.LevelTrace {
if log.IsGreaterOrEqualTo(log.LevelTrace) {
cmd.Stderr = os.Stderr
} else {
cmd.Stderr = io.Discard

View File

@ -106,6 +106,7 @@ func levelFromString(l string) Level {
return level
}
// SetLogLevels sets the log levels for specific paths in the codebase.
func SetLogLevels(levels map[string]string) {
for k, v := range levels {
logLevels = append(logLevels, levelPath{path: k, level: levelFromString(v)})
@ -154,6 +155,11 @@ func CurrentLevel() Level {
return currentLevel
}
// IsGreaterOrEqualTo returns true if the caller's current log level is equal or greater than the provided level.
func IsGreaterOrEqualTo(level Level) bool {
return shouldLog(level)
}
func Fatal(args ...interface{}) {
log(LevelFatal, args...)
os.Exit(1)

View File

@ -137,6 +137,37 @@ var _ = Describe("Logger", func() {
})
})
Describe("IsGreaterOrEqualTo", func() {
It("returns false if log level is below provided level", func() {
SetLevel(LevelError)
Expect(IsGreaterOrEqualTo(LevelWarn)).To(BeFalse())
})
It("returns true if log level is equal to provided level", func() {
SetLevel(LevelWarn)
Expect(IsGreaterOrEqualTo(LevelWarn)).To(BeTrue())
})
It("returns true if log level is above provided level", func() {
SetLevel(LevelTrace)
Expect(IsGreaterOrEqualTo(LevelDebug)).To(BeTrue())
})
It("returns true if log level for the current code path is equal provided level", func() {
SetLevel(LevelError)
SetLogLevels(map[string]string{
"log/log_test": "debug",
})
// Need to nest it in a function to get the correct code path
var result = func() bool {
return IsGreaterOrEqualTo(LevelDebug)
}()
Expect(result).To(BeTrue())
})
})
Describe("extractLogger", func() {
It("returns an error if the context is nil", func() {
_, err := extractLogger(nil)

View File

@ -58,7 +58,7 @@ func Read(filename string) (tags map[string][]string, err error) {
case C.TAGLIB_ERR_AUDIO_PROPS:
return nil, fmt.Errorf("can't get audio properties from file")
}
if log.CurrentLevel() >= log.LevelDebug {
if log.IsGreaterOrEqualTo(log.LevelDebug) {
j, _ := json.Marshal(m)
log.Trace("TagLib: read tags", "tags", string(j), "filename", filename, "id", id)
} else {

View File

@ -42,15 +42,13 @@ type (
username string
userAgent string
clientUniqueId string
displayString string
msgC chan message
}
)
func (c client) String() string {
if log.CurrentLevel() >= log.LevelTrace {
return fmt.Sprintf("%s (%s - %s - %s - %s)", c.id, c.username, c.address, c.clientUniqueId, c.userAgent)
}
return fmt.Sprintf("%s (%s - %s - %s)", c.id, c.username, c.address, c.clientUniqueId)
return c.displayString
}
type broker struct {
@ -172,6 +170,12 @@ func (b *broker) subscribe(r *http.Request) client {
userAgent: r.UserAgent(),
clientUniqueId: clientUniqueId,
}
if log.IsGreaterOrEqualTo(log.LevelTrace) {
c.displayString = fmt.Sprintf("%s (%s - %s - %s - %s)", c.id, c.username, c.address, c.clientUniqueId, c.userAgent)
} else {
c.displayString = fmt.Sprintf("%s (%s - %s - %s)", c.id, c.username, c.address, c.clientUniqueId)
}
c.msgC = make(chan message, bufferSize)
// Signal the broker that we have a new client
@ -260,7 +264,7 @@ func sendOrDrop(client client, msg message) {
select {
case client.msgC <- msg:
default:
if log.CurrentLevel() >= log.LevelTrace {
if log.IsGreaterOrEqualTo(log.LevelTrace) {
log.Trace("Event dropped because client's channel is full", "event", msg, "client", client.String())
}
}

View File

@ -42,7 +42,7 @@ func requestLogger(next http.Handler) http.Handler {
"httpStatus", ww.Status(),
"responseSize", ww.BytesWritten(),
}
if log.CurrentLevel() >= log.LevelDebug {
if log.IsGreaterOrEqualTo(log.LevelDebug) {
logArgs = append(logArgs, "userAgent", r.UserAgent())
}

View File

@ -32,7 +32,7 @@ func (pub *Router) handleStream(w http.ResponseWriter, r *http.Request) {
// Make sure the stream will be closed at the end, to avoid leakage
defer func() {
if err := stream.Close(); err != nil && log.CurrentLevel() >= log.LevelDebug {
if err := stream.Close(); err != nil && log.IsGreaterOrEqualTo(log.LevelDebug) {
log.Error("Error closing shared stream", "id", info.id, "file", stream.Name(), err)
}
}()
@ -60,7 +60,7 @@ func (pub *Router) handleStream(w http.ResponseWriter, r *http.Request) {
go func() { _, _ = io.Copy(io.Discard, stream) }()
} else {
c, err := io.Copy(w, stream)
if log.CurrentLevel() >= log.LevelDebug {
if log.IsGreaterOrEqualTo(log.LevelDebug) {
if err != nil {
log.Error(ctx, "Error sending shared transcoded file", "id", info.id, err)
} else {

View File

@ -215,7 +215,7 @@ func hr(r chi.Router, path string, f handlerRaw) {
return
}
if r.Context().Err() != nil {
if log.CurrentLevel() >= log.LevelDebug {
if log.IsGreaterOrEqualTo(log.LevelDebug) {
log.Warn(r.Context(), "Request was interrupted", "endpoint", r.URL.Path, r.Context().Err())
}
return
@ -301,7 +301,7 @@ func sendResponse(w http.ResponseWriter, r *http.Request, payload *responses.Sub
response, _ = xml.Marshal(payload)
}
if payload.Status == "ok" {
if log.CurrentLevel() >= log.LevelTrace {
if log.IsGreaterOrEqualTo(log.LevelTrace) {
log.Debug(r.Context(), "API: Successful response", "endpoint", r.URL.Path, "status", "OK", "body", string(response))
} else {
log.Debug(r.Context(), "API: Successful response", "endpoint", r.URL.Path, "status", "OK")

View File

@ -38,7 +38,7 @@ func (api *Router) serveStream(ctx context.Context, w http.ResponseWriter, r *ht
go func() { _, _ = io.Copy(io.Discard, stream) }()
} else {
c, err := io.Copy(w, stream)
if log.CurrentLevel() >= log.LevelDebug {
if log.IsGreaterOrEqualTo(log.LevelDebug) {
if err != nil {
log.Error(ctx, "Error sending transcoded file", "id", id, err)
} else {
@ -67,7 +67,7 @@ func (api *Router) Stream(w http.ResponseWriter, r *http.Request) (*responses.Su
// Make sure the stream will be closed at the end, to avoid leakage
defer func() {
if err := stream.Close(); err != nil && log.CurrentLevel() >= log.LevelDebug {
if err := stream.Close(); err != nil && log.IsGreaterOrEqualTo(log.LevelDebug) {
log.Error("Error closing stream", "id", id, "file", stream.Name(), err)
}
}()
@ -136,7 +136,7 @@ func (api *Router) Download(w http.ResponseWriter, r *http.Request) (*responses.
// Make sure the stream will be closed at the end, to avoid leakage
defer func() {
if err := stream.Close(); err != nil && log.CurrentLevel() >= log.LevelDebug {
if err := stream.Close(); err != nil && log.IsGreaterOrEqualTo(log.LevelDebug) {
log.Error("Error closing stream", "id", id, "file", stream.Name(), err)
}
}()