-
Notifications
You must be signed in to change notification settings - Fork 922
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
Open
Manvi2402
wants to merge
7
commits into
open-telemetry:main
Choose a base branch
from
Manvi2402:add-baggage-log-processor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 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 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
Some comments aren't visible on the classic Files Changed page.
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(): | ||
| 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 | ||
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
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.
Show resolved
Hide 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I like that you've used a Union here. The BaggageSpanProcessor just takes a single predicate, would you mind updating it to match this so they are kept consistent? Updating to use the union should be fully backward compatible so long as we use the
if callablecheck like you have below.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @MikeGoldsmith , I've updated BaggageSpanProcessor to support multiple predicates using the same Union type, with the if callable check for backward compatibility.