Skip to content

Commit

Permalink
Logging: Defensively access provider resource
Browse files Browse the repository at this point in the history
Now service name is extracted from the provider defensively and lazily.
This accounts for an SDK that does not provide access to "resource" via
TracerProviders and for lazy initialization of TracerProviders.

Fixes open-telemetry#810
  • Loading branch information
owais committed Feb 1, 2022
1 parent 2189e81 commit de1646a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased](https://github.com/open-telemetry/opentelemetry-python/compare/v1.9.1-0.28b1...HEAD)

### Fixed

- `opentelemetry-instrumentation-logging` retrieves service name defensively.
([#890](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/890))

## [1.9.1-0.28b1](https://github.com/open-telemetry/opentelemetry-python/releases/tag/v1.9.1-0.28b1) - 2022-01-29


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import logging # pylint: disable=import-self
from os import environ
from typing import Collection
from typing import Collection, Optional

from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.instrumentation.logging.constants import (
Expand Down Expand Up @@ -76,20 +76,26 @@ def instrumentation_dependencies(self) -> Collection[str]:
return _instruments

def _instrument(self, **kwargs):
service_name = ""
provider = kwargs.get("tracer_provider", None) or get_tracer_provider()
resource = provider.resource if provider else None
if resource:
service_name = resource.attributes.get("service.name")

old_factory = logging.getLogRecordFactory()
LoggingInstrumentor._old_factory = old_factory

service_name = None
def record_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)

record.otelSpanID = "0"
record.otelTraceID = "0"

nonlocal service_name
if service_name is None:
provider = kwargs.get("tracer_provider", None) or get_tracer_provider()
resource = getattr(provider, "resource", None)
if resource:
service_name = resource.attributes.get("service.name") or ""
else:
service_name = ""

record.otelServiceName = service_name

span = get_current_span()
Expand All @@ -100,6 +106,7 @@ def record_factory(*args, **kwargs):
record.otelTraceID = format(ctx.trace_id, "032x")
return record


logging.setLogRecordFactory(record_factory)

set_logging_format = kwargs.get(
Expand Down

0 comments on commit de1646a

Please sign in to comment.