| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package logger |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "log/slog" |
| 8 | ) |
| 9 | |
| 10 | type ConditionalLogger struct { |
| 11 | l *Logger |
| 12 | cond bool |
| 13 | allowElse bool |
| 14 | } |
| 15 | |
| 16 | type ElseBranch struct { |
| 17 | l *Logger |
| 18 | cond bool |
| 19 | } |
| 20 | |
| 21 | func (l *Logger) When(cond bool) ConditionalLogger { |
| 22 | return ConditionalLogger{l: l, cond: cond, allowElse: true} |
| 23 | } |
| 24 | |
| 25 | func (b ElseBranch) Else() ConditionalLogger { |
| 26 | return ConditionalLogger{l: b.l, cond: b.cond} |
| 27 | } |
| 28 | |
| 29 | func (c ConditionalLogger) Error(a ...any) ElseBranch { |
| 30 | return c.logArgs(slog.LevelError, a...) |
| 31 | } |
| 32 | |
| 33 | func (c ConditionalLogger) Warning(a ...any) ElseBranch { |
| 34 | return c.logArgs(slog.LevelWarn, a...) |
| 35 | } |
| 36 | |
| 37 | func (c ConditionalLogger) Notice(a ...any) ElseBranch { |
| 38 | return c.logArgs(levelNotice, a...) |
| 39 | } |
| 40 | |
| 41 | func (c ConditionalLogger) Info(a ...any) ElseBranch { |
| 42 | return c.logArgs(slog.LevelInfo, a...) |
| 43 | } |
| 44 | |
| 45 | func (c ConditionalLogger) Debug(a ...any) ElseBranch { |
| 46 | return c.logArgs(slog.LevelDebug, a...) |
| 47 | } |
| 48 | |
| 49 | func (c ConditionalLogger) Errorf(format string, a ...any) ElseBranch { |
| 50 | return c.logf(slog.LevelError, format, a...) |
| 51 | } |
| 52 | |
| 53 | func (c ConditionalLogger) Warningf(format string, a ...any) ElseBranch { |
| 54 | return c.logf(slog.LevelWarn, format, a...) |
| 55 | } |
| 56 | |
| 57 | func (c ConditionalLogger) Noticef(format string, a ...any) ElseBranch { |
| 58 | return c.logf(levelNotice, format, a...) |
| 59 | } |
| 60 | |
| 61 | func (c ConditionalLogger) Infof(format string, a ...any) ElseBranch { |
| 62 | return c.logf(slog.LevelInfo, format, a...) |
| 63 | } |
| 64 | |
| 65 | func (c ConditionalLogger) Debugf(format string, a ...any) ElseBranch { |
| 66 | return c.logf(slog.LevelDebug, format, a...) |
| 67 | } |
| 68 | |
| 69 | func (c ConditionalLogger) logArgs(level slog.Level, a ...any) ElseBranch { |
| 70 | if c.cond && c.l.canLog(level) { |
| 71 | c.l.log(level, fmt.Sprint(a...)) |
| 72 | } |
| 73 | return c.next() |
| 74 | } |
| 75 | |
| 76 | func (c ConditionalLogger) logf(level slog.Level, format string, a ...any) ElseBranch { |
| 77 | if c.cond && c.l.canLog(level) { |
| 78 | c.l.log(level, fmt.Sprintf(format, a...)) |
| 79 | } |
| 80 | return c.next() |
| 81 | } |
| 82 | |
| 83 | func (c ConditionalLogger) next() ElseBranch { |
| 84 | cond := false |
| 85 | if c.allowElse { |
| 86 | cond = !c.cond |
| 87 | } |
| 88 | return ElseBranch{l: c.l, cond: cond} |
| 89 | } |