1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-10-08 23:21:56 +02:00
Files
opentelemetry-go/sdk/log/provider.go
renovate[bot] 590bcee71b fix(deps): update module github.com/golangci/golangci-lint to v2 (#6499)
This PR contains the following updates:

| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
|
[github.com/golangci/golangci-lint](https://redirect.github.com/golangci/golangci-lint)
| `v1.64.8` -> `v2.0.2` |
[![age](https://developer.mend.io/api/mc/badges/age/go/github.com%2fgolangci%2fgolangci-lint/v2.0.2?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![adoption](https://developer.mend.io/api/mc/badges/adoption/go/github.com%2fgolangci%2fgolangci-lint/v2.0.2?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![passing](https://developer.mend.io/api/mc/badges/compatibility/go/github.com%2fgolangci%2fgolangci-lint/v1.64.8/v2.0.2?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![confidence](https://developer.mend.io/api/mc/badges/confidence/go/github.com%2fgolangci%2fgolangci-lint/v1.64.8/v2.0.2?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|

---

### Release Notes

<details>
<summary>golangci/golangci-lint
(github.com/golangci/golangci-lint)</summary>

###
[`v2.0.2`](https://redirect.github.com/golangci/golangci-lint/blob/HEAD/CHANGELOG.md#v202)

[Compare
Source](https://redirect.github.com/golangci/golangci-lint/compare/v2.0.1...v2.0.2)

1.  Misc.
    -   Fixes flags parsing for formatters
    -   Fixes the filepath used by the exclusion `source` option
2.  Documentation
    -   Adds a section about flags migration
    -   Cleaning pages with v1 options

###
[`v2.0.1`](https://redirect.github.com/golangci/golangci-lint/blob/HEAD/CHANGELOG.md#v201)

[Compare
Source](https://redirect.github.com/golangci/golangci-lint/compare/v2.0.0...v2.0.1)

1.  Linters/formatters bug fixes
    -   `golines`: fix settings during linter load
2.  Misc.
    -   Validates the `version` field before the configuration
    -   `forbidigo`: fix migration

###
[`v2.0.0`](https://redirect.github.com/golangci/golangci-lint/blob/HEAD/CHANGELOG.md#v200)

[Compare
Source](https://redirect.github.com/golangci/golangci-lint/compare/v1.64.8...v2.0.0)

1.  Enhancements
- 🌟 New `golangci-lint fmt` command with dedicated formatter
configuration
(https://golangci-lint.run/welcome/quick-start/#formatting)
- ♻️ New `golangci-lint migrate` command to help migration from v1 to v2
(cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/#command-migrate))
- ⚠️ New default values (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/))
- ⚠️ No exclusions by default (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/#issuesexclude-use-default))
- ⚠️ New default sort order (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/#outputsort-order))
- 🌟 New option `run.relative-path-mode` (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/#runrelative-path-mode))
- 🌟 New linters configuration (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/#linters))
- 🌟 New output format configuration (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/#output))
- 🌟 New `--fast-only` flag (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/#lintersfast))
- 🌟 New option `linters.exclusions.warn-unused` to log a warning if an
exclusion rule is unused.
2.  New linters/formatters
    -   Add `golines` formatter https://github.com/segmentio/golines
3.  Linters new features
- ⚠️ Merge `staticcheck`, `stylecheck`, `gosimple` into one linter
(`staticcheck`) (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/#lintersenablestylecheckgosimplestaticcheck))
    -   `go-critic`: from 0.12.0 to 0.13.0
- `gomodguard`: from 1.3.5 to 1.4.1 (block explicit indirect
dependencies)
    -   `nilnil`: from 1.0.1 to 1.1.0 (new option: `only-two`)
- `perfsprint`: from 0.8.2 to 0.9.1 (checker name in the diagnostic
message)
    -   `staticcheck`: new `quickfix` set of rules
- `testifylint`: from 1.5.2 to 1.6.0 (new options: `equal-values`,
`suite-method-signature`, `require-string-msg`)
- `wsl`: from 4.5.0 to 4.6.0 (new option: `allow-cuddle-used-in-block`)
4.  Linters bug fixes
    -   `bidichk`: from 0.3.2 to 0.3.3
    -   `errchkjson`: from 0.4.0 to 0.4.1
    -   `errname`: from 1.0.0 to 1.1.0
    -   `funlen`: fix `ignore-comments` option
    -   `gci`: from 0.13.5 to 0.13.6
    -   `gosmopolitan`: from 1.2.2 to 1.3.0
    -   `inamedparam`: from 0.1.3 to 0.2.0
    -   `intrange`: from 0.3.0 to 0.3.1
    -   `protogetter`: from 0.3.9 to 0.3.12
- `unparam`: from
[`8a5130c`](https://redirect.github.com/golangci/golangci-lint/commit/8a5130ca722f)
to
[`0df0534`](https://redirect.github.com/golangci/golangci-lint/commit/0df0534333a4)
5.  Misc.
- 🧹 Configuration options renaming (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/))
- 🧹 Remove options (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/))
- 🧹 Remove flags (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/))
- 🧹 Remove alternative names (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/#alternative-linter-names))
- 🧹 Remove or replace deprecated elements (cf. [Migration
guide](https://golangci-lint.run/product/migration-guide/))
    -   Adds an option to display some commands as JSON:
        -   `golangci-lint config path --json`
        -   `golangci-lint help linters --json`
        -   `golangci-lint help formatters --json`
        -   `golangci-lint linters --json`
        -   `golangci-lint formatters --json`
        -   `golangci-lint version --json`
6.  Documentation
- [Migration guide](https://golangci-lint.run/product/migration-guide/)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined),
Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR was generated by [Mend Renovate](https://mend.io/renovate/).
View the [repository job
log](https://developer.mend.io/github/open-telemetry/opentelemetry-go).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOS4yMDcuMSIsInVwZGF0ZWRJblZlciI6IjM5LjIwNy4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJTa2lwIENoYW5nZWxvZyIsImRlcGVuZGVuY2llcyJdfQ==-->

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Tyler Yahn <codingalias@gmail.com>
2025-03-26 10:46:44 -07:00

257 lines
7.4 KiB
Go

// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package log // import "go.opentelemetry.io/otel/sdk/log"
import (
"context"
"errors"
"sync"
"sync/atomic"
"go.opentelemetry.io/otel"
"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/resource"
)
const (
defaultAttrCntLim = 128
defaultAttrValLenLim = -1
envarAttrCntLim = "OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT"
envarAttrValLenLim = "OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT"
)
type providerConfig struct {
resource *resource.Resource
processors []Processor
fltrProcessors []FilterProcessor
attrCntLim setting[int]
attrValLenLim setting[int]
}
func newProviderConfig(opts []LoggerProviderOption) providerConfig {
var c providerConfig
for _, opt := range opts {
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),
)
return c
}
// LoggerProvider handles the creation and coordination of Loggers. All Loggers
// created by a LoggerProvider will be associated with the same Resource.
type LoggerProvider struct {
embedded.LoggerProvider
resource *resource.Resource
processors []Processor
fltrProcessors []FilterProcessor
attributeCountLimit int
attributeValueLengthLimit int
loggersMu sync.Mutex
loggers map[instrumentation.Scope]*logger
stopped atomic.Bool
noCmp [0]func() //nolint: unused // This is indeed used.
}
// Compile-time check LoggerProvider implements log.LoggerProvider.
var _ log.LoggerProvider = (*LoggerProvider)(nil)
// NewLoggerProvider returns a new and configured LoggerProvider.
//
// By default, the returned LoggerProvider is configured with the default
// Resource and no Processors. Processors cannot be added after a LoggerProvider is
// created. This means the returned LoggerProvider, one created with no
// Processors, will perform no operations.
func NewLoggerProvider(opts ...LoggerProviderOption) *LoggerProvider {
cfg := newProviderConfig(opts)
return &LoggerProvider{
resource: cfg.resource,
processors: cfg.processors,
fltrProcessors: cfg.fltrProcessors,
attributeCountLimit: cfg.attrCntLim.Value,
attributeValueLengthLimit: cfg.attrValLenLim.Value,
}
}
// Logger returns a new [log.Logger] with the provided name and configuration.
//
// If p is shut down, a [noop.Logger] instance is returned.
//
// This method can be called concurrently.
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...)
scope := instrumentation.Scope{
Name: name,
Version: cfg.InstrumentationVersion(),
SchemaURL: cfg.SchemaURL(),
Attributes: cfg.InstrumentationAttributes(),
}
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
}
// Shutdown shuts down the provider and all processors.
//
// This method can be called concurrently.
func (p *LoggerProvider) Shutdown(ctx context.Context) error {
stopped := p.stopped.Swap(true)
if stopped {
return nil
}
var err error
for _, p := range p.processors {
err = errors.Join(err, p.Shutdown(ctx))
}
return err
}
// ForceFlush flushes all processors.
//
// This method can be called concurrently.
func (p *LoggerProvider) ForceFlush(ctx context.Context) error {
if p.stopped.Load() {
return nil
}
var err error
for _, p := range p.processors {
err = errors.Join(err, p.ForceFlush(ctx))
}
return err
}
// LoggerProviderOption applies a configuration option value to a LoggerProvider.
type LoggerProviderOption interface {
apply(providerConfig) providerConfig
}
type loggerProviderOptionFunc func(providerConfig) providerConfig
func (fn loggerProviderOptionFunc) apply(c providerConfig) providerConfig {
return fn(c)
}
// WithResource associates a Resource with a LoggerProvider. This Resource
// represents the entity producing telemetry and is associated with all Loggers
// the LoggerProvider will create.
//
// By default, if this Option is not used, the default Resource from the
// go.opentelemetry.io/otel/sdk/resource package will be used.
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
})
}
// WithProcessor associates Processor with a LoggerProvider.
//
// By default, if this option is not used, the LoggerProvider will perform no
// operations; no data will be exported without a processor.
//
// The SDK invokes the processors sequentially in the same order as they were
// registered.
//
// For production, use [NewBatchProcessor] to batch log records before they are exported.
// For testing and debugging, use [NewSimpleProcessor] to synchronously export log records.
//
// See [FilterProcessor] for information about how a Processor can support filtering.
func WithProcessor(processor Processor) LoggerProviderOption {
return loggerProviderOptionFunc(func(cfg providerConfig) providerConfig {
cfg.processors = append(cfg.processors, processor)
if f, ok := processor.(FilterProcessor); ok {
cfg.fltrProcessors = append(cfg.fltrProcessors, f)
}
return cfg
})
}
// WithAttributeCountLimit sets the maximum allowed log record attribute count.
// Any attribute added to a log record once this limit is reached will be dropped.
//
// Setting this to zero means no attributes will be recorded.
//
// Setting this to a negative value means no limit is applied.
//
// If the OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT environment variable is set,
// and this option is not passed, that variable value will be used.
//
// By default, if an environment variable is not set, and this option is not
// passed, 128 will be used.
func WithAttributeCountLimit(limit int) LoggerProviderOption {
return loggerProviderOptionFunc(func(cfg providerConfig) providerConfig {
cfg.attrCntLim = newSetting(limit)
return cfg
})
}
// WithAttributeValueLengthLimit sets the maximum allowed attribute value length.
//
// This limit only applies to string and string slice attribute values.
// Any string longer than this value will be truncated to this length.
//
// Setting this to a negative value means no limit is applied.
//
// If the OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT environment variable is set,
// and this option is not passed, that variable value will be used.
//
// By default, if an environment variable is not set, and this option is not
// passed, no limit (-1) will be used.
func WithAttributeValueLengthLimit(limit int) LoggerProviderOption {
return loggerProviderOptionFunc(func(cfg providerConfig) providerConfig {
cfg.attrValLenLim = newSetting(limit)
return cfg
})
}