package log
import (
"context"
"errors"
"sync"
"sync/atomic"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/internal/global"
"go.opentelemetry.io/otel/log"
"go.opentelemetry.io/otel/log/embedded"
"go.opentelemetry.io/otel/log/noop"
"go.opentelemetry.io/otel/sdk/instrumentation"
"go.opentelemetry.io/otel/sdk/log/internal/attrnorm"
"go.opentelemetry.io/otel/sdk/resource"
)
const (
defaultAttrCntLim = 128
defaultAttrValLenLim = -1
defaultAttrValDepthLim = 64
envarAttrCntLim = "OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT"
envarAttrValLenLim = "OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT"
)
type providerConfig struct {
resource *resource .Resource
processors []Processor
attrCntLim setting [int ]
attrValLenLim setting [int ]
attrValDepthLim setting [int ]
allowDupKeys setting [bool ]
}
type experimentalOption interface {
Experimental()
}
func newProviderConfig(opts []LoggerProviderOption ) providerConfig {
var c providerConfig
for _ , opt := range opts {
if _ , ok := opt .(experimentalOption ); ok {
continue
}
c = opt .apply (c )
}
if c .resource == nil {
c .resource = resource .Default ()
}
c .attrCntLim = c .attrCntLim .Resolve (
getenv [int ](envarAttrCntLim ),
fallback [int ](defaultAttrCntLim ),
)
c .attrValLenLim = c .attrValLenLim .Resolve (
getenv [int ](envarAttrValLenLim ),
fallback [int ](defaultAttrValLenLim ),
)
c .attrValDepthLim = c .attrValDepthLim .Resolve (
fallback [int ](defaultAttrValDepthLim ),
)
return c
}
type LoggerProvider struct {
embedded .LoggerProvider
resource *resource .Resource
processors []Processor
attributeCountLimit int
attributeValueLengthLimit int
attributeValueDepthLimit int
allowDupKeys bool
loggersMu sync .Mutex
loggers map [instrumentation .Scope ]*logger
stopped atomic .Bool
processorOperationsMu sync .Mutex
processorOperationsActive int
processorOperationsDone chan struct {}
noCmp [0 ]func ()
}
var _ log .LoggerProvider = (*LoggerProvider )(nil )
func NewLoggerProvider (opts ...LoggerProviderOption ) *LoggerProvider {
cfg := newProviderConfig (opts )
return &LoggerProvider {
resource : cfg .resource ,
processors : cfg .processors ,
attributeCountLimit : cfg .attrCntLim .Value ,
attributeValueLengthLimit : cfg .attrValLenLim .Value ,
attributeValueDepthLimit : cfg .attrValDepthLim .Value ,
allowDupKeys : cfg .allowDupKeys .Value ,
}
}
func (p *LoggerProvider ) Logger (name string , opts ...log .LoggerOption ) log .Logger {
if name == "" {
global .Warn ("Invalid Logger name." , "name" , name )
}
if p .stopped .Load () {
return noop .NewLoggerProvider ().Logger (name , opts ...)
}
cfg := log .NewLoggerConfig (opts ...)
attrs := cfg .InstrumentationAttributes ()
attrs , invalid := attrs .Filter (attribute .KeyValue .Valid )
if len (invalid ) > 0 {
logInvalidAttribute ()
}
if !p .allowDupKeys {
attrs , _, _ = attrnorm .SetDedupLimitDepth (attrs , p .attrValueDepthLimit ())
} else {
attrs , _ = attrnorm .SetLimitDepth (attrs , p .attrValueDepthLimit ())
}
scope := instrumentation .Scope {
Name : name ,
Version : cfg .InstrumentationVersion (),
SchemaURL : cfg .SchemaURL (),
Attributes : attrs ,
}
p .loggersMu .Lock ()
defer p .loggersMu .Unlock ()
if p .loggers == nil {
l := newLogger (p , scope )
p .loggers = map [instrumentation .Scope ]*logger {scope : l }
return l
}
l , ok := p .loggers [scope ]
if !ok {
l = newLogger (p , scope )
p .loggers [scope ] = l
}
return l
}
func (p *LoggerProvider ) attrValueDepthLimit () int {
if p .attributeValueDepthLimit == 0 {
return defaultAttrValDepthLim
}
return p .attributeValueDepthLimit
}
func (p *LoggerProvider ) Shutdown (ctx context .Context ) error {
p .processorOperationsMu .Lock ()
if p .stopped .Load () {
p .processorOperationsMu .Unlock ()
return nil
}
p .processorOperationsDone = make (chan struct {})
p .stopped .Store (true )
if p .processorOperationsActive == 0 {
close (p .processorOperationsDone )
}
p .processorOperationsMu .Unlock ()
if err := p .waitForProcessorOperations (ctx ); err != nil {
return err
}
var err error
for _ , p := range p .processors {
err = errors .Join (err , p .Shutdown (ctx ))
}
return err
}
func (p *LoggerProvider ) ForceFlush (ctx context .Context ) error {
if len (p .processors ) == 0 || !p .beginProcessorOperation () {
return nil
}
defer p .endProcessorOperation ()
var err error
for _ , p := range p .processors {
err = errors .Join (err , p .ForceFlush (ctx ))
}
return err
}
func (p *LoggerProvider ) beginProcessorOperation () bool {
p .processorOperationsMu .Lock ()
defer p .processorOperationsMu .Unlock ()
if p .stopped .Load () {
return false
}
p .processorOperationsActive ++
return true
}
func (p *LoggerProvider ) endProcessorOperation () {
p .processorOperationsMu .Lock ()
defer p .processorOperationsMu .Unlock ()
p .processorOperationsActive --
if p .processorOperationsActive == 0 && p .stopped .Load () {
close (p .processorOperationsDone )
}
}
func (p *LoggerProvider ) waitForProcessorOperations (ctx context .Context ) error {
if err := ctx .Err (); err != nil {
return err
}
return waitForProcessorOperationsCompletion (ctx , p .processorOperationsDone )
}
func waitForProcessorOperationsCompletion(ctx context .Context , done <-chan struct {}) error {
select {
case <- done :
case <- ctx .Done ():
select {
case <- done :
default :
return ctx .Err ()
}
}
return nil
}
type LoggerProviderOption interface {
apply(providerConfig ) providerConfig
}
type loggerProviderOptionFunc func (providerConfig ) providerConfig
func (fn loggerProviderOptionFunc ) apply (c providerConfig ) providerConfig {
return fn (c )
}
func WithResource (res *resource .Resource ) LoggerProviderOption {
return loggerProviderOptionFunc (func (cfg providerConfig ) providerConfig {
var err error
cfg .resource , err = resource .Merge (resource .Environment (), res )
if err != nil {
otel .Handle (err )
}
return cfg
})
}
func WithProcessor (processor Processor ) LoggerProviderOption {
return loggerProviderOptionFunc (func (cfg providerConfig ) providerConfig {
cfg .processors = append (cfg .processors , processor )
return cfg
})
}
func WithAttributeCountLimit (limit int ) LoggerProviderOption {
return loggerProviderOptionFunc (func (cfg providerConfig ) providerConfig {
cfg .attrCntLim = newSetting (limit )
return cfg
})
}
func WithAttributeValueLengthLimit (limit int ) LoggerProviderOption {
return loggerProviderOptionFunc (func (cfg providerConfig ) providerConfig {
cfg .attrValLenLim = newSetting (limit )
return cfg
})
}
func WithAttributeValueDepthLimit (limit int ) LoggerProviderOption {
if limit == 0 {
limit = defaultAttrValDepthLim
}
return loggerProviderOptionFunc (func (cfg providerConfig ) providerConfig {
cfg .attrValDepthLim = newSetting (limit )
return cfg
})
}
func WithAllowKeyDuplication () LoggerProviderOption {
return loggerProviderOptionFunc (func (cfg providerConfig ) providerConfig {
cfg .allowDupKeys = newSetting (true )
return cfg
})
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .