Skip to content
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

Add app_name to logs and traces #182

Merged
merged 1 commit into from
May 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 15 additions & 20 deletions src/main/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@
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()

# 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")
Expand Down Expand Up @@ -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",
Expand All @@ -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")
Expand Down
48 changes: 48 additions & 0 deletions src/main/utils_azure_insights.py
Original file line number Diff line number Diff line change
@@ -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",
}
Loading