feat: add logc package, support AddGlobalFields for both logc and logx. (#2463)
* feat: add logc package * feat: add logc, add AddGlobalFields for both logc and logx * chore: add benchmarks * chore: add more tests * chore: simplify globalFields in logx * chore: remove outdated comments
This commit is contained in:
@@ -1,11 +1,32 @@
|
||||
package logx
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
var fieldsContextKey contextKey
|
||||
var (
|
||||
fieldsContextKey contextKey
|
||||
globalFields atomic.Value
|
||||
globalFieldsLock sync.Mutex
|
||||
)
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
// AddGlobalFields adds global fields.
|
||||
func AddGlobalFields(fields ...LogField) {
|
||||
globalFieldsLock.Lock()
|
||||
defer globalFieldsLock.Unlock()
|
||||
|
||||
old := globalFields.Load()
|
||||
if old == nil {
|
||||
globalFields.Store(append([]LogField(nil), fields...))
|
||||
} else {
|
||||
globalFields.Store(append(old.([]LogField), fields...))
|
||||
}
|
||||
}
|
||||
|
||||
// ContextWithFields returns a new context with the given fields.
|
||||
func ContextWithFields(ctx context.Context, fields ...LogField) context.Context {
|
||||
if val := ctx.Value(fieldsContextKey); val != nil {
|
||||
|
||||
Reference in New Issue
Block a user