Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Capture the correct log caller #605

Merged
merged 1 commit into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/instana/instrumentation/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,16 @@ def log_with_instana(wrapped, instance, argv, kwargs):
# argv[0] = level
# argv[1] = message
# argv[2] = args for message
if sys.version_info >= (3, 13):
stacklevel = 3
else:
stacklevel = 2
try:
tracer, parent_span, _ = get_tracer_tuple()

# Only needed if we're tracing and serious log
if tracing_is_off() or argv[0] < logging.WARN:
return wrapped(*argv, **kwargs)
return wrapped(*argv, **kwargs, stacklevel=stacklevel)

msg = str(argv[1])
args = argv[2]
Expand All @@ -48,7 +52,7 @@ def log_with_instana(wrapped, instance, argv, kwargs):
except Exception:
logger.debug('log_with_instana:', exc_info=True)

return wrapped(*argv, **kwargs)
return wrapped(*argv, **kwargs, stacklevel=stacklevel)


logger.debug('Instrumenting logging')
Expand Down
22 changes: 22 additions & 0 deletions tests/clients/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@

import logging
import unittest
import pytest
from instana.singletons import agent, tracer


class TestLogging(unittest.TestCase):
@pytest.fixture
def capture_log(self, caplog):
self.caplog = caplog

def setUp(self):
""" Clear all spans before a test run """
self.recorder = tracer.recorder
Expand Down Expand Up @@ -74,3 +79,20 @@ def test_root_exit_span(self):
self.assertEqual(2, spans[0].k)

self.assertEqual('foo bar', spans[0].data["log"].get('message'))

@pytest.mark.usefixtures("capture_log")
def test_log_caller(self):
handler = logging.StreamHandler()
handler.setFormatter(
logging.Formatter("source: %(funcName)s, message: %(message)s")
)
self.logger.addHandler(handler)

def log_custom_warning():
self.logger.warning("foo %s", "bar")

with tracer.start_active_span("test"):
log_custom_warning()
self.assertEqual(self.caplog.records[0].funcName, "log_custom_warning")

self.logger.removeHandler(handler)
Loading