Skip to content

Commit d5fdcd6

Browse files
authored
Add code.lineno, code.function and code.filepath to all logs (#3675)
Signed-off-by: Bogdan Drutu <[email protected]>
1 parent 66e7d61 commit d5fdcd6

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1919
([#3623](https://github.com/open-telemetry/opentelemetry-python/pull/3623))
2020
- Improve Resource Detector timeout messaging
2121
([#3645](https://github.com/open-telemetry/opentelemetry-python/pull/3645))
22+
- Add `code.lineno`, `code.function` and `code.filepath` to all logs
23+
([#3645](https://github.com/open-telemetry/opentelemetry-python/pull/3645))
2224

2325
## Version 1.22.0/0.43b0 (2023-12-15)
2426

opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,12 @@ def _get_attributes(record: logging.LogRecord) -> Attributes:
455455
attributes = {
456456
k: v for k, v in vars(record).items() if k not in _RESERVED_ATTRS
457457
}
458+
459+
# Add standard code attributes for logs.
460+
attributes[SpanAttributes.CODE_FILEPATH] = record.pathname
461+
attributes[SpanAttributes.CODE_FUNCTION] = record.funcName
462+
attributes[SpanAttributes.CODE_LINENO] = record.lineno
463+
458464
if record.exc_info:
459465
exc_type = ""
460466
message = ""

opentelemetry-sdk/tests/logs/test_handler.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,20 @@ def test_log_record_user_attributes(self):
112112
log_record = args[0]
113113

114114
self.assertIsNotNone(log_record)
115-
self.assertEqual(log_record.attributes, {"http.status_code": 200})
115+
self.assertEqual(len(log_record.attributes), 4)
116+
self.assertEqual(log_record.attributes["http.status_code"], 200)
117+
self.assertTrue(
118+
log_record.attributes[SpanAttributes.CODE_FILEPATH].endswith(
119+
"test_handler.py"
120+
)
121+
)
122+
self.assertEqual(
123+
log_record.attributes[SpanAttributes.CODE_FUNCTION],
124+
"test_log_record_user_attributes",
125+
)
126+
# The line of the log statement is not a constant (changing tests may change that),
127+
# so only check that the attribute is present.
128+
self.assertTrue(SpanAttributes.CODE_LINENO in log_record.attributes)
116129
self.assertTrue(isinstance(log_record.attributes, BoundedAttributes))
117130

118131
def test_log_record_exception(self):

0 commit comments

Comments
 (0)