-
Notifications
You must be signed in to change notification settings - Fork 945
feat: Add BaggageLogProcessor to opentelemetry-processor-baggage #4371
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
Merged
lzchen
merged 13 commits into
open-telemetry:main
from
Manvi2402:add-baggage-log-processor
May 7, 2026
+289
−6
Merged
Changes from 5 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
3449a3d
Add BaggageLogProcessor and address review comments
Manvi2402 391c2dd
Address review comments: add docstring, default max_baggage_attribute…
Manvi2402 992c506
Add test for max_baggage_attributes limit
Manvi2402 51e9774
Fix precommit and pylint issues in BaggageLogProcessor
Manvi2402 9e17389
Merge branch 'main' into add-baggage-log-processor
MikeGoldsmith f90ab6c
Update BaggageSpanProcessor to support multiple predicates for consis…
Manvi2402 4bd1ff8
Merge branch 'add-baggage-log-processor' of https://github.com/Manvi2…
Manvi2402 2e2e42d
Fix unsorted imports and missing newlines
Manvi2402 51a39fc
Fix force_flush signature to match base class
Manvi2402 9e81970
Merge branch 'main' into add-baggage-log-processor
lzchen 953f1d4
Update license comments in log_processor.py
lzchen 46578e0
Update license header to SPDX format
lzchen bbf4520
Merge branch 'main' into add-baggage-log-processor
lzchen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
...ssor/opentelemetry-processor-baggage/src/opentelemetry/processor/baggage/log_processor.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from typing import Sequence, Union | ||
|
|
||
| from opentelemetry.baggage import get_all as get_all_baggage | ||
| from opentelemetry.processor.baggage.processor import BaggageKeyPredicateT | ||
| from opentelemetry.sdk._logs import LogRecordProcessor, ReadWriteLogRecord | ||
|
|
||
| BaggageKeyPredicate = Union[ | ||
| BaggageKeyPredicateT, Sequence[BaggageKeyPredicateT] | ||
| ] | ||
|
|
||
|
|
||
| class BaggageLogProcessor(LogRecordProcessor): | ||
| """ | ||
| The BaggageLogProcessor reads entries stored in Baggage | ||
| from the current context and adds the baggage entries' keys and | ||
| values to the log record as attributes on emit. | ||
|
|
||
| Add this log processor to a logger provider. | ||
|
|
||
| ⚠ Warning ⚠️ | ||
|
|
||
| Do not put sensitive information in Baggage. | ||
|
|
||
| To repeat: a consequence of adding data to Baggage is that the keys and | ||
| values will appear in all outgoing HTTP headers from the application. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| baggage_key_predicate: BaggageKeyPredicate, | ||
| max_baggage_attributes: int = 128, | ||
| ) -> None: | ||
| if callable(baggage_key_predicate): | ||
| self._predicates = [baggage_key_predicate] | ||
| else: | ||
| self._predicates = list(baggage_key_predicate) | ||
| self._max_baggage_attributes = max_baggage_attributes | ||
|
|
||
| def _matches(self, key: str) -> bool: | ||
| return any(predicate(key) for predicate in self._predicates) | ||
|
|
||
| def on_emit(self, log_record: ReadWriteLogRecord) -> None: | ||
| """Add baggage entries as log record attributes on emit. | ||
|
|
||
| Baggage keys are filtered using the provided predicate(s). | ||
| If a baggage key already exists in the log record attributes, | ||
| it will not be overwritten to avoid collisions with attributes | ||
| added by stdlib logging, calls to logging.emit, or custom | ||
| LogRecordProcessors. At most max_baggage_attributes baggage | ||
| entries will be added. | ||
| """ | ||
| baggage = get_all_baggage() | ||
| count = 0 | ||
| for key, value in baggage.items(): | ||
|
tammy-baylis-swi marked this conversation as resolved.
|
||
| if count >= self._max_baggage_attributes: | ||
| break | ||
| if self._matches(key): | ||
| if key not in log_record.log_record.attributes: | ||
| log_record.log_record.attributes[key] = value | ||
| count += 1 | ||
|
|
||
| def shutdown(self) -> None: | ||
| pass | ||
|
|
||
| @staticmethod | ||
| def force_flush(timeout_millis: int = 30000) -> bool: | ||
| return True | ||
163 changes: 163 additions & 0 deletions
163
processor/opentelemetry-processor-baggage/tests/test_baggage_log_processor.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import re | ||
| import unittest | ||
|
|
||
| from opentelemetry.baggage import set_baggage | ||
| from opentelemetry.context import attach, detach | ||
| from opentelemetry.processor.baggage import ( | ||
| ALLOW_ALL_BAGGAGE_KEYS, | ||
| BaggageLogProcessor, | ||
| ) | ||
| from opentelemetry.sdk._logs import LoggerProvider, LogRecordProcessor | ||
| from opentelemetry.sdk._logs.export import ( | ||
| InMemoryLogRecordExporter, | ||
| BatchLogRecordProcessor, | ||
| ) | ||
|
|
||
|
|
||
| class BaggageLogProcessorTest(unittest.TestCase): | ||
|
tammy-baylis-swi marked this conversation as resolved.
|
||
| def setUp(self): | ||
| self.exporter = InMemoryLogRecordExporter() | ||
| self.logger_provider = LoggerProvider() | ||
| self.logger_provider.add_log_record_processor( | ||
| BaggageLogProcessor(ALLOW_ALL_BAGGAGE_KEYS) | ||
| ) | ||
| self.logger_provider.add_log_record_processor( | ||
| BatchLogRecordProcessor(self.exporter) | ||
| ) | ||
| self.logger = self.logger_provider.get_logger("test-logger") | ||
|
|
||
| def _get_attributes(self): | ||
| self.logger_provider.force_flush() | ||
| logs = self.exporter.get_finished_logs() | ||
| self.assertTrue(len(logs) > 0) | ||
| return logs[-1].log_record.attributes | ||
|
|
||
| def test_check_the_baggage(self): | ||
| self.assertIsInstance( | ||
| BaggageLogProcessor(ALLOW_ALL_BAGGAGE_KEYS), LogRecordProcessor | ||
| ) | ||
|
|
||
| def test_baggage_added_to_log_record(self): | ||
| token = attach(set_baggage("queen", "bee")) | ||
| self.logger.emit(None) | ||
| attributes = self._get_attributes() | ||
| self.assertEqual(attributes.get("queen"), "bee") | ||
| detach(token) | ||
|
|
||
| def test_baggage_with_prefix(self): | ||
| token = attach(set_baggage("queen", "bee")) | ||
| logger_provider = LoggerProvider() | ||
| logger_provider.add_log_record_processor( | ||
| BaggageLogProcessor(lambda key: key.startswith("que")) | ||
| ) | ||
| exporter = InMemoryLogRecordExporter() | ||
| logger_provider.add_log_record_processor( | ||
| BatchLogRecordProcessor(exporter) | ||
| ) | ||
| logger = logger_provider.get_logger("test-logger") | ||
| logger.emit(None) | ||
| logger_provider.force_flush() | ||
| logs = exporter.get_finished_logs() | ||
| attributes = logs[-1].log_record.attributes | ||
| self.assertEqual(attributes.get("queen"), "bee") | ||
| detach(token) | ||
|
|
||
| def test_baggage_with_regex(self): | ||
| token = attach(set_baggage("queen", "bee")) | ||
| logger_provider = LoggerProvider() | ||
| logger_provider.add_log_record_processor( | ||
| BaggageLogProcessor( | ||
| lambda key: re.match(r"que.*", key) is not None | ||
| ) | ||
| ) | ||
| exporter = InMemoryLogRecordExporter() | ||
| logger_provider.add_log_record_processor( | ||
| BatchLogRecordProcessor(exporter) | ||
| ) | ||
| logger = logger_provider.get_logger("test-logger") | ||
| logger.emit(None) | ||
| logger_provider.force_flush() | ||
| logs = exporter.get_finished_logs() | ||
| attributes = logs[-1].log_record.attributes | ||
| self.assertEqual(attributes.get("queen"), "bee") | ||
| detach(token) | ||
|
|
||
| def test_no_baggage_not_added(self): | ||
| self.logger.emit(None) | ||
| self.logger_provider.force_flush() | ||
| logs = self.exporter.get_finished_logs() | ||
| self.assertTrue(len(logs) > 0) | ||
| attributes = logs[-1].log_record.attributes | ||
| self.assertNotIn("queen", attributes) | ||
|
|
||
| def test_multiple_predicates(self): | ||
| token1 = attach(set_baggage("queen", "bee")) | ||
| token2 = attach(set_baggage("king", "cobra")) | ||
| logger_provider = LoggerProvider() | ||
| logger_provider.add_log_record_processor( | ||
| BaggageLogProcessor([ | ||
| lambda key: key.startswith("que"), | ||
| lambda key: key.startswith("kin"), | ||
| ]) | ||
| ) | ||
| exporter = InMemoryLogRecordExporter() | ||
| logger_provider.add_log_record_processor( | ||
| BatchLogRecordProcessor(exporter) | ||
| ) | ||
| logger = logger_provider.get_logger("test-logger") | ||
| logger.emit(None) | ||
| logger_provider.force_flush() | ||
| logs = exporter.get_finished_logs() | ||
| attributes = logs[-1].log_record.attributes | ||
| self.assertEqual(attributes.get("queen"), "bee") | ||
| self.assertEqual(attributes.get("king"), "cobra") | ||
| detach(token2) | ||
| detach(token1) | ||
|
|
||
| def test_max_baggage_attributes_limit(self): | ||
| token1 = attach(set_baggage("key1", "val1")) | ||
| token2 = attach(set_baggage("key2", "val2")) | ||
| token3 = attach(set_baggage("key3", "val3")) | ||
| logger_provider = LoggerProvider() | ||
| logger_provider.add_log_record_processor( | ||
| BaggageLogProcessor(ALLOW_ALL_BAGGAGE_KEYS, max_baggage_attributes=2) | ||
| ) | ||
| exporter = InMemoryLogRecordExporter() | ||
| logger_provider.add_log_record_processor( | ||
| BatchLogRecordProcessor(exporter) | ||
| ) | ||
| logger = logger_provider.get_logger("test-logger") | ||
| logger.emit(None) | ||
| logger_provider.force_flush() | ||
| logs = exporter.get_finished_logs() | ||
| attributes = logs[-1].log_record.attributes | ||
| self.assertEqual(len(attributes), 2) | ||
| detach(token3) | ||
| detach(token2) | ||
| detach(token1) | ||
|
|
||
| @staticmethod | ||
| def has_prefix(baggage_key: str) -> bool: | ||
| return baggage_key.startswith("que") | ||
|
|
||
| @staticmethod | ||
| def matches_regex(baggage_key: str) -> bool: | ||
| return re.match(r"que.*", baggage_key) is not None | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.