-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add static logger for easier migration of v1 code (#26)
- Loading branch information
1 parent
4c73bbd
commit 5c5e884
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
// Package static provides a simple static logger implementation for easy migration of existing pre-v2 code. | ||
// | ||
// The package is usually imported aliased as "log" to be compatible with the v1 approach. | ||
// | ||
// The static logger instance needs to be initialized during startup of the application using SetLogger. | ||
package static | ||
|
||
import ( | ||
"sync" | ||
|
||
"github.com/ViaQ/logerr/v2/log" | ||
"github.com/go-logr/logr" | ||
) | ||
|
||
var ( | ||
lock sync.RWMutex | ||
logger = log.NewLogger("uninitialized") | ||
) | ||
|
||
// SetLogger sets the static logger instance. | ||
func SetLogger(replacement logr.Logger) { | ||
lock.Lock() | ||
defer lock.Unlock() | ||
|
||
logger = replacement | ||
} | ||
|
||
// WithName returns a logger with name added to the component. | ||
// This uses the static logger instance. | ||
func WithName(name string) logr.Logger { | ||
lock.RLock() | ||
defer lock.RUnlock() | ||
|
||
return logger.WithName(name) | ||
} | ||
|
||
// V returns a logger with the verbosity set to level. | ||
// This uses the static logger instance. | ||
func V(level int) logr.Logger { | ||
lock.RLock() | ||
defer lock.RUnlock() | ||
|
||
return logger.V(level) | ||
} | ||
|
||
// Info logs an informational message with optional key-value pairs. | ||
// This uses the static logger instance. | ||
func Info(msg string, keysAndValues ...interface{}) { | ||
lock.RLock() | ||
defer lock.RUnlock() | ||
|
||
logger.Info(msg, keysAndValues...) | ||
} | ||
|
||
// Error logs an error message with optional key-value pairs. | ||
// This uses the static logger instance. | ||
func Error(err error, msg string, keysAndValues ...interface{}) { | ||
lock.RLock() | ||
defer lock.RUnlock() | ||
|
||
logger.Error(err, msg, keysAndValues...) | ||
} |