|
|
|
@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
|
|
|
|
|
limitations under the License.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
package cli
|
|
|
|
|
package logging
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
@ -22,16 +22,20 @@ import (
|
|
|
|
|
"os"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// DebugEnabledFunc is a function type that determines if debug logging is enabled
|
|
|
|
|
// We use a function because we want to check the setting at log time, not when the logger is created
|
|
|
|
|
type DebugEnabledFunc func() bool
|
|
|
|
|
|
|
|
|
|
// DebugCheckHandler checks settings.Debug at log time
|
|
|
|
|
type DebugCheckHandler struct {
|
|
|
|
|
handler slog.Handler
|
|
|
|
|
settings *EnvSettings
|
|
|
|
|
handler slog.Handler
|
|
|
|
|
debugEnabled DebugEnabledFunc
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Enabled implements slog.Handler.Enabled
|
|
|
|
|
func (h *DebugCheckHandler) Enabled(_ context.Context, level slog.Level) bool {
|
|
|
|
|
if level == slog.LevelDebug {
|
|
|
|
|
return h.settings.Debug // Check settings.Debug at log time
|
|
|
|
|
return h.debugEnabled()
|
|
|
|
|
}
|
|
|
|
|
return true // Always log other levels
|
|
|
|
|
}
|
|
|
|
@ -44,21 +48,21 @@ func (h *DebugCheckHandler) Handle(ctx context.Context, r slog.Record) error {
|
|
|
|
|
// WithAttrs implements slog.Handler.WithAttrs
|
|
|
|
|
func (h *DebugCheckHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
|
|
|
|
return &DebugCheckHandler{
|
|
|
|
|
handler: h.handler.WithAttrs(attrs),
|
|
|
|
|
settings: h.settings,
|
|
|
|
|
handler: h.handler.WithAttrs(attrs),
|
|
|
|
|
debugEnabled: h.debugEnabled,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// WithGroup implements slog.Handler.WithGroup
|
|
|
|
|
func (h *DebugCheckHandler) WithGroup(name string) slog.Handler {
|
|
|
|
|
return &DebugCheckHandler{
|
|
|
|
|
handler: h.handler.WithGroup(name),
|
|
|
|
|
settings: h.settings,
|
|
|
|
|
handler: h.handler.WithGroup(name),
|
|
|
|
|
debugEnabled: h.debugEnabled,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NewLogger creates a new logger with dynamic debug checking
|
|
|
|
|
func NewLogger(settings *EnvSettings) *slog.Logger {
|
|
|
|
|
func NewLogger(debugEnabled DebugEnabledFunc) *slog.Logger {
|
|
|
|
|
// Create base handler that removes timestamps
|
|
|
|
|
baseHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
|
|
|
|
|
// Always use LevelDebug here to allow all messages through
|
|
|
|
@ -75,8 +79,8 @@ func NewLogger(settings *EnvSettings) *slog.Logger {
|
|
|
|
|
|
|
|
|
|
// Wrap with our dynamic debug-checking handler
|
|
|
|
|
dynamicHandler := &DebugCheckHandler{
|
|
|
|
|
handler: baseHandler,
|
|
|
|
|
settings: settings,
|
|
|
|
|
handler: baseHandler,
|
|
|
|
|
debugEnabled: debugEnabled,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return slog.New(dynamicHandler)
|