| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package global // import "go.opentelemetry.io/otel/internal/global" |
| 5 |
|
| 6 |
import ( |
| 7 |
"log" |
| 8 |
"os" |
| 9 |
"sync/atomic" |
| 10 |
|
| 11 |
"github.com/go-logr/logr" |
| 12 |
"github.com/go-logr/stdr" |
| 13 |
) |
| 14 |
|
| 15 |
// globalLogger holds a reference to the [logr.Logger] used within |
| 16 |
// go.opentelemetry.io/otel. |
| 17 |
// |
| 18 |
// The default logger uses stdr which is backed by the standard `log.Logger` |
| 19 |
// interface. This logger will only show messages at the Error Level. |
| 20 |
var globalLogger = func() *atomic.Pointer[logr.Logger] { |
| 21 |
l := stdr.New(log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile)) |
| 22 |
|
| 23 |
p := new(atomic.Pointer[logr.Logger]) |
| 24 |
p.Store(&l) |
| 25 |
return p |
| 26 |
}() |
| 27 |
|
| 28 |
// SetLogger sets the global Logger to l. |
| 29 |
// |
| 30 |
// To see Warn messages use a logger with `l.V(1).Enabled() == true` |
| 31 |
// To see Info messages use a logger with `l.V(4).Enabled() == true` |
| 32 |
// To see Debug messages use a logger with `l.V(8).Enabled() == true`. |
| 33 |
func SetLogger(l logr.Logger) { |
| 34 |
globalLogger.Store(&l) |
| 35 |
} |
| 36 |
|
| 37 |
// GetLogger returns the global logger. |
| 38 |
func GetLogger() logr.Logger { |
| 39 |
return *globalLogger.Load() |
| 40 |
} |
| 41 |
|
| 42 |
// Info prints messages about the general state of the API or SDK. |
| 43 |
// This should usually be less than 5 messages a minute. |
| 44 |
func Info(msg string, keysAndValues ...any) { |
| 45 |
GetLogger().V(4).Info(msg, keysAndValues...) |
| 46 |
} |
| 47 |
|
| 48 |
// Error prints messages about exceptional states of the API or SDK. |
| 49 |
func Error(err error, msg string, keysAndValues ...any) { |
| 50 |
GetLogger().Error(err, msg, keysAndValues...) |
| 51 |
} |
| 52 |
|
| 53 |
// Debug prints messages about all internal changes in the API or SDK. |
| 54 |
func Debug(msg string, keysAndValues ...any) { |
| 55 |
GetLogger().V(8).Info(msg, keysAndValues...) |
| 56 |
} |
| 57 |
|
| 58 |
// Warn prints messages about warnings in the API or SDK. |
| 59 |
// Not an error but is likely more important than an informational event. |
| 60 |
func Warn(msg string, keysAndValues ...any) { |
| 61 |
GetLogger().V(1).Info(msg, keysAndValues...) |
| 62 |
} |