2024-08-13 03:07:45 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
|
|
|
|
|
|
|
// Package loggerx provides logging functions to the rest of the syspolicy packages.
|
|
|
|
package loggerx
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
2024-10-08 18:59:50 +00:00
|
|
|
"sync/atomic"
|
2024-08-13 03:07:45 +00:00
|
|
|
|
|
|
|
"tailscale.com/types/lazy"
|
|
|
|
"tailscale.com/types/logger"
|
|
|
|
"tailscale.com/util/syspolicy/internal"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2024-10-08 18:59:50 +00:00
|
|
|
normalPrefix = "syspolicy: "
|
2024-08-13 03:07:45 +00:00
|
|
|
verbosePrefix = "syspolicy: [v2] "
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2024-10-08 18:59:50 +00:00
|
|
|
debugLogging atomic.Bool // whether debugging logging is enabled
|
|
|
|
|
|
|
|
lazyPrintf lazy.SyncValue[logger.Logf]
|
2024-08-13 03:07:45 +00:00
|
|
|
lazyVerbosef lazy.SyncValue[logger.Logf]
|
|
|
|
)
|
|
|
|
|
2024-10-08 18:59:50 +00:00
|
|
|
// SetDebugLoggingEnabled controls whether spammy debug logging is enabled.
|
|
|
|
func SetDebugLoggingEnabled(v bool) {
|
|
|
|
debugLogging.Store(v)
|
|
|
|
}
|
|
|
|
|
2024-08-13 03:07:45 +00:00
|
|
|
// Errorf formats and writes an error message to the log.
|
|
|
|
func Errorf(format string, args ...any) {
|
2024-10-08 18:59:50 +00:00
|
|
|
printf(format, args...)
|
2024-08-13 03:07:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Verbosef formats and writes an optional, verbose message to the log.
|
|
|
|
func Verbosef(format string, args ...any) {
|
2024-10-08 18:59:50 +00:00
|
|
|
if debugLogging.Load() {
|
|
|
|
printf(format, args...)
|
|
|
|
} else {
|
|
|
|
verbosef(format, args...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func printf(format string, args ...any) {
|
|
|
|
lazyPrintf.Get(func() logger.Logf {
|
|
|
|
return logger.WithPrefix(log.Printf, normalPrefix)
|
|
|
|
})(format, args...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func verbosef(format string, args ...any) {
|
|
|
|
lazyVerbosef.Get(func() logger.Logf {
|
2024-08-13 03:07:45 +00:00
|
|
|
return logger.WithPrefix(log.Printf, verbosePrefix)
|
2024-10-08 18:59:50 +00:00
|
|
|
})(format, args...)
|
2024-08-13 03:07:45 +00:00
|
|
|
}
|
|
|
|
|
2024-10-08 18:59:50 +00:00
|
|
|
// SetForTest sets the specified printf and verbosef functions for the duration
|
2024-08-13 03:07:45 +00:00
|
|
|
// of tb and its subtests.
|
2024-10-08 18:59:50 +00:00
|
|
|
func SetForTest(tb internal.TB, printf, verbosef logger.Logf) {
|
|
|
|
lazyPrintf.SetForTest(tb, printf, nil)
|
2024-08-13 03:07:45 +00:00
|
|
|
lazyVerbosef.SetForTest(tb, verbosef, nil)
|
|
|
|
}
|