This repository was archived by the owner on Sep 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 247
Skeleton for Azure Log Exporter #657
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
8c20fea
initial work on log exporter
reyang 7d8f5de
add links to doc
reyang e0d7eaa
update docs and changelog
reyang e62753a
update unit test
reyang 05d1119
add more examples
reyang 9089c02
decouple QueueExitEvent from exporter
reyang 220673f
test exit event
reyang 9b64a68
clean up emit from log exporter
reyang 5ab3f5c
align the logging API with Python practice
reyang 84b29e3
minor doc fix
reyang ff500a4
fix lint
reyang 92d7d17
fix lint
reyang f718b27
improve coverage
reyang cbab810
fix lint
reyang 6f30149
use super
reyang c8c8def
update README for logging integration
reyang 69defce
log exporter internal exception
reyang c989146
improve exception handling
reyang 93e92e4
simplify interface
reyang 19b0792
minor cleanup
reyang 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
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,38 @@ | ||
| # Copyright 2019, OpenCensus 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 logging | ||
|
|
||
| from opencensus.ext.azure.log_exporter import AzureLogHandler | ||
| from opencensus.ext.azure.trace_exporter import AzureExporter | ||
| from opencensus.trace import config_integration | ||
| from opencensus.trace.samplers import ProbabilitySampler | ||
| from opencensus.trace.tracer import Tracer | ||
|
|
||
| config_integration.trace_integrations(['logging']) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # TODO: you need to specify the instrumentation key in the | ||
| # APPINSIGHTS_INSTRUMENTATIONKEY environment variable. | ||
| handler = AzureLogHandler() | ||
| handler.setFormatter(logging.Formatter('%(traceId)s %(spanId)s %(message)s')) | ||
| logger.addHandler(handler) | ||
|
|
||
| tracer = Tracer(exporter=AzureExporter(), sampler=ProbabilitySampler(1.0)) | ||
|
|
||
| logger.warning('Before the span') | ||
| with tracer.span(name='test'): | ||
| logger.warning('In the span') | ||
| logger.warning('After the span') |
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,23 @@ | ||
| # Copyright 2019, OpenCensus 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 logging | ||
|
|
||
| from opencensus.ext.azure.log_exporter import AzureLogHandler | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
| # TODO: you need to specify the instrumentation key in the | ||
| # APPINSIGHTS_INSTRUMENTATIONKEY environment variable. | ||
| logger.addHandler(AzureLogHandler()) | ||
| logger.warning('Hello, World!') |
File renamed without changes.
File renamed without changes.
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
File renamed without changes.
File renamed without changes.
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
119 changes: 119 additions & 0 deletions
119
contrib/opencensus-ext-azure/opencensus/ext/azure/log_exporter/__init__.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,119 @@ | ||
| # Copyright 2019, OpenCensus 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 logging | ||
| import threading | ||
| import time | ||
|
|
||
| from opencensus.common.schedule import Queue | ||
| from opencensus.common.schedule import QueueEvent | ||
| from opencensus.ext.azure.common import Options | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| __all__ = ['AzureLogHandler'] | ||
|
|
||
|
|
||
| class BaseLogHandler(logging.Handler): | ||
| def __init__(self): | ||
| super(BaseLogHandler, self).__init__() | ||
| self._queue = Queue(capacity=8192) # TODO: make this configurable | ||
| self._worker = Worker(self._queue, self) | ||
| self._worker.start() | ||
|
|
||
| def close(self): | ||
| self._worker.stop() | ||
|
|
||
| def createLock(self): | ||
| self.lock = None | ||
|
|
||
| def emit(self, record): | ||
| self._queue.put(record, block=False) | ||
|
|
||
| def _export(self, batch, event=None): | ||
| try: | ||
| return self.export(batch) | ||
| finally: | ||
| if event: | ||
| event.set() | ||
|
|
||
| def export(self, batch): | ||
| raise NotImplementedError | ||
|
|
||
| def flush(self, timeout=None): | ||
| self._queue.flush(timeout=timeout) | ||
|
|
||
|
|
||
| class Worker(threading.Thread): | ||
| daemon = True | ||
|
|
||
| def __init__(self, src, dst): | ||
| self._src = src | ||
| self._dst = dst | ||
| self._stopping = False | ||
| super(Worker, self).__init__( | ||
| name='{} Worker'.format(type(dst).__name__) | ||
| ) | ||
|
|
||
| def run(self): | ||
| src = self._src | ||
| dst = self._dst | ||
| while True: | ||
| batch = src.gets(dst.max_batch_size, dst.export_interval) | ||
| if batch and isinstance(batch[-1], QueueEvent): | ||
| try: | ||
| dst._export(batch[:-1], event=batch[-1]) | ||
| except Exception: | ||
| logger.exception('Unhandled exception from exporter.') | ||
| if batch[-1] is src.EXIT_EVENT: | ||
| break | ||
| else: | ||
| continue | ||
| try: | ||
| dst._export(batch) | ||
| except Exception: | ||
| logger.exception('Unhandled exception from exporter.') | ||
|
|
||
| def stop(self, timeout=None): | ||
| start_time = time.time() | ||
| wait_time = timeout | ||
| if self.is_alive() and not self._stopping: | ||
| self._stopping = True | ||
| self._src.put(self._src.EXIT_EVENT, block=True, timeout=wait_time) | ||
| elapsed_time = time.time() - start_time | ||
| wait_time = timeout and max(timeout - elapsed_time, 0) | ||
| if self._src.EXIT_EVENT.wait(timeout=wait_time): | ||
| return time.time() - start_time # time taken to stop | ||
|
|
||
|
|
||
| class AzureLogHandler(BaseLogHandler): | ||
| """Handler for logging to Microsoft Azure Monitor. | ||
|
|
||
| :param options: Options for the log handler. | ||
| """ | ||
|
|
||
| def __init__(self, **options): | ||
| self.options = Options(**options) | ||
| if not self.options.instrumentation_key: | ||
| raise ValueError('The instrumentation_key is not provided.') | ||
| self.export_interval = self.options.export_interval | ||
| self.max_batch_size = self.options.max_batch_size | ||
| super(AzureLogHandler, self).__init__() | ||
|
|
||
| def export(self, batch): | ||
| if batch: | ||
| for item in batch: | ||
| item.traceId = getattr(item, 'traceId', 'N/A') | ||
| item.spanId = getattr(item, 'spanId', 'N/A') | ||
| print(self.format(item)) | ||
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
Oops, something went wrong.
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.
Note the circular reference here, we've been bitten by this before trying to clean up exporters. See
opencensus-python/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
Lines 372 to 406 in 04c111f
Uh oh!
There was an error while loading. Please reload this page.
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.
My original understanding is that we have
Handler.closewhich can be used explicitly or implicitly (by Python logging library), and the circular reference will be collected by the GC. This shouldn't cause problem? Is this to prevent memory leak, or to reduce GC overhead?Regarding memory leak, I run the following app for an hour and see a flat memory usage:
For GC overhead, given the circle is pretty small, I guess there is no noticeable difference?
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 thought there were more general problems cleaning up circular references in python, but it may only be a problem for classes that define
__del__(see https://stackoverflow.com/a/2428888), in which case this is fine.