azure-sdk-for-python: AzureMonitorLogExporter breaks if the LoggingHandler is added to the root logger
- azure-monitor-opentelemetry-exporter:
- 1.0.0b23:
- macOS 14.3.1 (23D60):
- 3.10.13:
Describe the bug
The example for the AzureMonitorLogExporter: Export Hello World Log fails if the LoggingHandler is added to the root logger (maybe recursive behaviour?). It works fine if the LoggingHandler is added to a named logger.
To Reproduce Steps to reproduce the behavior:
- Install Requirements
asgiref==3.7.2
azure-core==1.30.1
azure-core-tracing-opentelemetry==1.0.0b11
azure-monitor-opentelemetry==1.3.0
azure-monitor-opentelemetry-exporter==1.0.0b23
certifi==2024.2.2
charset-normalizer==3.3.2
Deprecated==1.2.14
fixedint==0.1.6
idna==3.6
importlib-metadata==6.11.0
isodate==0.6.1
msrest==0.7.1
oauthlib==3.2.2
opentelemetry-api==1.23.0
opentelemetry-instrumentation==0.44b0
opentelemetry-instrumentation-asgi==0.44b0
opentelemetry-instrumentation-dbapi==0.44b0
opentelemetry-instrumentation-django==0.44b0
opentelemetry-instrumentation-fastapi==0.44b0
opentelemetry-instrumentation-flask==0.44b0
opentelemetry-instrumentation-psycopg2==0.44b0
opentelemetry-instrumentation-requests==0.44b0
opentelemetry-instrumentation-urllib==0.44b0
opentelemetry-instrumentation-urllib3==0.44b0
opentelemetry-instrumentation-wsgi==0.44b0
opentelemetry-resource-detector-azure==0.1.3
opentelemetry-sdk==1.23.0
opentelemetry-semantic-conventions==0.44b0
opentelemetry-util-http==0.44b0
packaging==24.0
pip==23.3.1
requests==2.31.0
requests-oauthlib==1.4.0
setuptools==68.2.2
six==1.16.0
typing_extensions==4.10.0
urllib3==2.2.1
wheel==0.41.2
wrapt==1.16.0
zipp==3.18.1
- Run the example Export Hello World Log.
import logging
import os
import sys
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs._internal.export import SimpleLogRecordProcessor
logger_provider = LoggerProvider()
set_logger_provider(logger_provider)
exporter = AzureMonitorLogExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
logger_provider.add_log_record_processor(SimpleLogRecordProcessor(exporter))
# fails
root_logger = logging.getLogger()
root_logger.addHandler(LoggingHandler())
root_logger.addHandler(logging.StreamHandler(stream=sys.stdout))
root_logger.setLevel(logging.NOTSET)
my_logger = logging.getLogger(__name__)
my_logger.setLevel(logging.INFO)
my_logger.warning("Hello World!")
# works
my_logger = logging.getLogger(__name__)
my_logger.addHandler(LoggingHandler())
my_logger.addHandler(logging.StreamHandler(stream=sys.stdout))
my_logger.setLevel(logging.INFO)
my_logger.warning("Hello World!")
Output:
...
A body is sent with the request
https://westeurope-5.in.applicationinsights.azure.com:443 "POST //v2.1/track HTTP/1.1" 200 None
Response status: 200
Response headers:
'Transfer-Encoding': 'chunked'
'Content-Type': 'application/json; charset=utf-8'
'Server': 'Microsoft-HTTPAPI/2.0'
'Strict-Transport-Security': 'REDACTED'
'X-Content-Type-Options': 'REDACTED'
'Date': 'Fri, 15 Mar 2024 20:21:18 GMT'
Envelopes could not be exported and are not retryable: maximum recursion depth exceeded while calling a Python object.
Envelopes could not be exported and are not retryable: maximum recursion depth exceeded while calling a Python object.
Transmission succeeded: Item received: 1. Items accepted: 1
Starting new HTTPS connection (18): westeurope-5.in.applicationinsights.azure.com:443
Process finished with exit code 137 (interrupted by signal 9:SIGKILL)
Expected behavior It should be possible to add the logging handler to the root logger.
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 19 (13 by maintainers)
Commits related to this issue
- docs: recommend to use named loggers instead of the root logger as described in https://github.com/Azure/azure-sdk-for-python/issues/34787 (#35771) — committed to Azure/azure-sdk-for-python by johschmidt42 2 years ago
As I mentioned in the issue you linked:
“The OpenTelemetry LoggingHandler is just like any other Python logging handler so any configuration that supports Python logging handlers should work for OpenTelemetry LoggingHandler as well.”
So if your environment supports configuration through yaml config file of Python logging handlers then it should support the OpenTelemetry’s
LoggerHandleras well.Configuration of the
LoggerProviderhowever is a different ask. This would be configuration of the OpenTelemetry api/sdk itself and that has not been supported yet through config files.@summahto A namespaced logger is just a named logger:
logging.getLogger("my_logger")If you don’t provide a name, you’ll get the root logger in Python.
The docs actually explain why and when to use the Azure Monitor Distro or the Exporter directly. First one is a one stop shop solution whereas the second gives you more flexibility. If you take a look inside at the create_azure_monitor function, you’ll notice that it just sets up the Exporter.
Since the original issue has been resolved and the appropriate documentation has been merged for better guidance for users, I believe this can be closed.
Opened a PR where I extended the README.md for the exporter @RollerKnobster. Feel free to comment. Thanks for the reminder by the way.
Some modules/libraries I use in an application should send logs to Application Insights. For this, the handler
LoggingHandlerneeds be attached to a logger to receive logs. Since modules/libraries use different loggers than my app (different named loggers), I have two options:LoggingHandler(& other handlers) to every module logger I’m interested inLoggingHandleronly to the root logger but filter out some logs (for example the ones in azure.monitor to prevent recurvise logging). Named loggers propagate their logs to the root logger, so the handlers (e.g.LoggingHandler) in the root logger will be handling all logs.I think both approaches are fine. It probably depends on how you like to do things. On one hand, you must explicitely update some named loggers. So you might forget some. But on the other hand, if you allow all logs that are propagated to the root logger to be handled by your handlers, you must think about filtering some of them to not flood your backend with logs.
@johschmidt42
I think that would be a great idea. Feel free to open a PR if you see it fitting somewhere appropriate.
Thank you @lzchen. You’re right. Logs from the Exporter (named logger) are send all the way up to the root logger, so adding the
LoggingHandlerto the root logger does make little sense. They way I see it, there are 2 options then:azure.monitor(e.g. Python logging filters, changing the level ofazure.monitordirectly or replace the LogRecordProcessor as you described)LoggingHandleronly to named loggersIt probably depends on what your logging approach is. For now, I’ll go for the second scenario where I add the
LoggingHandlerto loggers from other modules I want to see logs from.@summahto
@johschmidt42 explained it perfectly, the distro is for a one api solution with simple configuration, whereas the exporter is for more complex telemetry scenarios where we give the user more control over the individual components.
@johschmidt42
That’s a great question. I am assuming you are trying to collect logs from imported libraries that are not created by you or not in your control (otherwise, you can just namespace the libraries appropriately and just use one namespace that is a prefix of all of your namespaces). Collecting ALL logs from every library is a not a common telemetry scenario. Like you mentioned, add the handler to every namespaced logger in each library you want to track would work but very tedious. With that being said, adding to the root handler is technically possible, but with some caveats. The only reason you are getting recursion errors is because you are using the
SimpleLogRecordProcessorwhich exports logs immediately as they are collected. Our documentation recommends using theBatchLogRecordProcessor, which queues up the log records to be exported as a batch using a worker thread. This way, you won’t get spammed with log record exports as they will be exporting on a timer instead. Now, this won’t solve the recursion problem, as we still send logs from the exporter on export, which will then be collected by the logging handler and then exported again. What you can do is setup your logging handler as to IGNORE logs sent from the SDK library. You can do this by matching the name withazure.monitor.and adding a custom processor.You can also achieve similar behavior if you use Python logging filter and apply the same logic.