Skip to content

Commit

Permalink
fix: capture the correct log caller
Browse files Browse the repository at this point in the history
Signed-off-by: Varsha GS <varsha.gs@ibm.com>
  • Loading branch information
GSVarsha committed Aug 30, 2024
1 parent d7deedf commit 186f81d
Showing 2 changed files with 28 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/instana/instrumentation/logging.py
Original file line number Diff line number Diff line change
@@ -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]
@@ -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')
22 changes: 22 additions & 0 deletions tests/clients/test_logging.py
Original file line number Diff line number Diff line change
@@ -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
@@ -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)

0 comments on commit 186f81d

Please sign in to comment.