Skip to content

Instantly share code, notes, and snippets.

@PennyQ
Last active November 2, 2021 12:27
Show Gist options
  • Save PennyQ/32e69897eeee23b08f8dbb0d0b59d537 to your computer and use it in GitHub Desktop.
Save PennyQ/32e69897eeee23b08f8dbb0d0b59d537 to your computer and use it in GitHub Desktop.
import logging
try:
from opencensus.ext.azure.log_exporter import AzureLogHandler
except:
raise ImportError("To be able to use add_azure_log_handler opencensus must be installed.\
Specifically opencensus-ext-azure==1.0.8")
# ----set up application insights connection----
instrumentation_key= "your_instrumentation_key"
ingestion_endpoint="your_enpoint_url"
export_interval = 1 #by second
try:
connection_string = f"InstrumentationKey={instrumentation_key};IngestionEndpoint={ingestion_endpoint}"
azure_handler = AzureLogHandler(connection_string=connection_string, export_interval=export_interval)
except Exception:
raise ValueError("Failed to create Azure handler with given connection_string.")
# ----tags the logs in azure analytics----
custom_dimensions = {"team": "test_penny", "usecase": "test_penny"}
extra_tags = None
if extra_tags:
custom_dimensions.update(extra_tags)
azure_handler.add_telemetry_processor(
lambda envelope: envelope.data.baseData.properties.update(custom_dimensions)
)
LOG_FORMAT = '%(levelname)s \t %(filename)s:%(funcName)s:%(lineno)d - %(message)s'
azure_handler.setFormatter(logging.Formatter(LOG_FORMAT))
# ----initiate the logger----
logger = logging.getLogger("test")
logger.setLevel(logging.INFO)
logger.addHandler(azure_handler)
# ----send log content-----
accuracy = 0.96
model_name = "linear regression"
logger.info("Hello, World! We start project %s" % "run-test", extra={"custom_dimensions": {"accuracy": accuracy, "model_name": model_name}})
logger.warning("There is a warning!")
logger.error("Error happens! Accuracy is below %f" %85.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment