diff --git a/src/main/settings.py b/src/main/settings.py index c94fed5..ae7deeb 100644 --- a/src/main/settings.py +++ b/src/main/settings.py @@ -5,6 +5,11 @@ from corsheaders.defaults import default_headers from opencensus.trace import config_integration +from main.utils_azure_insights import ( + create_azure_log_handler_config, + create_azure_trace_config, +) + from .azure_settings import Azure azure = Azure() @@ -12,6 +17,7 @@ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +APP_NAME = os.getenv("APP_NAME", "iiif-metadata-server") # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv("SECRET_KEY") @@ -214,11 +220,7 @@ "handlers": ["console"], "propagate": False, }, - "opencensus": { - "handlers": ["console"], - "level": "WARNING", - "propagate": False - }, + "opencensus": {"handlers": ["console"], "level": "WARNING", "propagate": False}, "azure.core.pipeline.policies.http_logging_policy": { "handlers": ["console"], "level": "WARNING", @@ -233,22 +235,15 @@ if APPLICATIONINSIGHTS_CONNECTION_STRING: MIDDLEWARE.append("opencensus.ext.django.middleware.OpencensusMiddleware") - OPENCENSUS = { - "TRACE": { - "SAMPLER": "opencensus.trace.samplers.ProbabilitySampler(rate=1)", - "EXPORTER": f"""opencensus.ext.azure.trace_exporter.AzureExporter( - connection_string='{APPLICATIONINSIGHTS_CONNECTION_STRING}', - service_name='app-iiif-metadata-server' - )""", - } - } + + OPENCENSUS = create_azure_trace_config( + APPLICATIONINSIGHTS_CONNECTION_STRING, APP_NAME + ) + LOGGING["handlers"]["azure"] = create_azure_log_handler_config( + APPLICATIONINSIGHTS_CONNECTION_STRING, APP_NAME + ) config_integration.trace_integrations(["logging"]) - LOGGING["handlers"]["azure"] = { - "level": "DEBUG", - "class": "opencensus.ext.azure.log_exporter.AzureLogHandler", - "connection_string": APPLICATIONINSIGHTS_CONNECTION_STRING, - "formatter": "json" - } + LOGGING["root"]["handlers"].append("azure") for logger_name, logger_details in LOGGING["loggers"].items(): LOGGING["loggers"][logger_name]["handlers"].append("azure") diff --git a/src/main/utils_azure_insights.py b/src/main/utils_azure_insights.py new file mode 100644 index 0000000..a472fff --- /dev/null +++ b/src/main/utils_azure_insights.py @@ -0,0 +1,48 @@ +from functools import partial + +from opencensus.ext.azure.log_exporter import AzureLogHandler +from opencensus.ext.azure.trace_exporter import AzureExporter + + +def add_app_name_to_telemetry(app_name, envelope): + envelope.data.baseData.properties["Application name"] = app_name + envelope.tags["ai.cloud.role"] = f"{app_name} - {envelope.tags['ai.cloud.role']}" + return True + + +def create_azure_trace_config(connection_string, app_name): + exporter = AzureExporter( + connection_string=connection_string, + service_name=app_name, + ) + exporter.add_telemetry_processor(partial(add_app_name_to_telemetry, app_name)) + return { + "TRACE": { + "SAMPLER": "opencensus.trace.samplers.ProbabilitySampler(rate=1)", + "EXPORTER": exporter, + } + } + + +class AzureLogHandlerWithAppName(AzureLogHandler): + app_name = None + + @staticmethod + def set_app_name(name): + AzureLogHandlerWithAppName.app_name = name + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if self.app_name: + telemetry_callback = partial(add_app_name_to_telemetry, self.app_name) + self.add_telemetry_processor(telemetry_callback) + + +def create_azure_log_handler_config(connection_string, app_name): + AzureLogHandlerWithAppName.set_app_name(app_name) + return { + "level": "DEBUG", + "()": AzureLogHandlerWithAppName, + "connection_string": connection_string, + "formatter": "json", + }