Package: appinsights
This project extends the Application Insights API surface to support Python.Application Insightsis a service that
allows developers to keep their application available, performing and
succeeding. This Python module will allow you to send telemetry of various kinds
(event, trace, exception, etc.) to the Application Insights service where they
can be visualized in the Azure Portal. A link to the Application Insights API
documentation can be foundhere.This project is not officially supported and not recommended for high load
production use. The project is open source and welcomes contributions.RequirementsPython >=2.7 and Python >=3.4 are currently supported by this module.InstallationTo install the latest release you can usepip.$ pip install appinsightsDocumentationPlease seehttps://brennerm.github.io/python-appinsights/for full documentation.UsageOnce installed, you can send telemetry to Application Insights. Here are a few samples.Note: before you can send data to you will need an instrumentation key. Please see theGetting an Application Insights Instrumentation Keysection for more information.Sending a simple event telemetry itemfromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.track_event('Test event')tc.flush()Sending an event telemetry item with custom properties and measurementsfromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.track_event('Test event',{'foo':'bar'},{'baz':42})tc.flush()Sending a trace telemetry item with custom propertiesfromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.track_trace('Test trace',{'foo':'bar'})tc.flush()Sending a metric telemetry itemfromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.track_metric('My Metric',42)tc.flush()Sending an availability telemetry itemfromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.track_availability('My Service',250,True,"West Europe")tc.flush()Sending an exception telemetry item with custom properties and measurementsimportsysfromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')try:raiseException('blah')except:tc.track_exception()try:raiseException("blah")except:tc.track_exception(*sys.exc_info(),properties={'foo':'bar'},measurements={'x':42})tc.flush()Configuring context for a telemetry client instancefromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.context.application.ver='1.2.3'tc.context.device.id='My current device'tc.context.device.oem_name='Asus'tc.context.device.model='X31A'tc.context.device.type="Other"tc.context.user.id='santa@northpole.net'tc.context.properties['my_property']='my_value'tc.track_trace('My trace with context')tc.flush()Establishing correlation between telemetry objectscontext field called operation_id can be set to associate telemetry items.
Since operation_id is being set as a property of telemetry client, the client shouldn’t be reused in parallel threads as it might lead to concurrency issues.tc=TelemetryClient(instrumentation_key=instrumentation_key)tc.context.operation.id=<operation_id>tc.track_trace('Test trace')tc.flush()Configuring channel related propertiesfromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')# flush telemetry every 30 seconds (assuming we don't hit max_queue_item_count first)tc.channel.sender.send_interval_in_milliseconds=30*1000# flush telemetry if we have 10 or more telemetry items in our queuetc.channel.queue.max_queue_length=10Configuring TelemetryProcessorfromapplicationinsightsimportTelemetryClientdefprocess(data,context):data.properties["NEW_PROP"]="MYPROP"# Add propertycontext.user.id="MYID"# Change IDreturnTrue# Not filteredtc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.add_telemetry_processor(process)Basic logging configuration (first option)importloggingfromapplicationinsights.loggingimportenable# set up loggingenable('<YOUR INSTRUMENTATION KEY GOES HERE>')# log something (this will be sent to the Application Insights service as a trace)logging.info('This is a message')# logging shutdown will cause a flush of all un-sent telemetry itemslogging.shutdown()Basic logging configuration (second option)importloggingfromapplicationinsights.loggingimportLoggingHandler# set up logginghandler=LoggingHandler('<YOUR INSTRUMENTATION KEY GOES HERE>')logging.basicConfig(handlers=[handler],format='%(levelname)s:%(message)s',level=logging.DEBUG)# log something (this will be sent to the Application Insights service as a trace)logging.debug('This is a message')try:raiseException('Some exception')except:# this will send an exception to the Application Insights servicelogging.exception('Code went boom!')# logging shutdown will cause a flush of all un-sent telemetry items# alternatively flush manually via handler.flush()logging.shutdown()Advanced logging configurationimportloggingfromapplicationinsightsimportchannelfromapplicationinsights.loggingimportLoggingHandler# set up channel with contexttelemetry_channel=channel.TelemetryChannel()telemetry_channel.context.application.ver='1.2.3'telemetry_channel.context.properties['my_property']='my_value'# set up logginghandler=LoggingHandler('<YOUR INSTRUMENTATION KEY GOES HERE>',telemetry_channel=telemetry_channel)handler.setLevel(logging.DEBUG)handler.setFormatter(logging.Formatter('%(levelname)s:%(message)s'))my_logger=logging.getLogger('simple_logger')my_logger.setLevel(logging.DEBUG)my_logger.addHandler(handler)# log something (this will be sent to the Application Insights service as a trace)my_logger.debug('This is a message')# logging shutdown will cause a flush of all un-sent telemetry items# alternatively flush manually via handler.flush()logging.shutdown()Logging unhandled exceptionsfromapplicationinsights.exceptionsimportenable# set up exception captureenable('<YOUR INSTRUMENTATION KEY GOES HERE>')# raise an exception (this will be sent to the Application Insights service as an exception telemetry object)raiseException('Boom!')# exceptions will cause a flush of all un-sent telemetry itemsLogging unhandled exceptions with contextfromapplicationinsightsimportchannelfromapplicationinsights.exceptionsimportenable# set up channel with contexttelemetry_channel=channel.TelemetryChannel()telemetry_channel.context.application.ver='1.2.3'telemetry_channel.context.properties['my_property']='my_value'# set up exception captureenable('<YOUR INSTRUMENTATION KEY GOES HERE>',telemetry_channel=telemetry_channel)# raise an exception (this will be sent to the Application Insights service as an exception telemetry object)raiseException('Boom!')# exceptions will cause a flush of all un-sent telemetry itemsTrack dependency telemetry for HTTP requests with requestsfromapplicationinsights.clientimportenable_for_requestsimportrequestsenable_for_requests('<YOUR INSTRUMENTATION KEY GOES HERE>')requests.get("https://www.python.org/")# a dependency telemetry will be sent to the Application Insights serviceTrack dependency telemetry for HTTP requests with urllibfromapplicationinsights.clientimportenable_for_urllibimporturllib.requestsenable_for_urllib('<YOUR INSTRUMENTATION KEY GOES HERE>')urllib.request.urlopen("https://www.python.org/")# a dependency telemetry will be sent to the Application Insights serviceTrack dependency telemetry for HTTP requests with urllib2fromapplicationinsights.clientimportenable_for_urllib2importurllib2enable_for_urllib2('<YOUR INSTRUMENTATION KEY GOES HERE>')urllib2.urlopen("https://www.python.org/")# a dependency telemetry will be sent to the Application Insights serviceTrack dependency telemetry for HTTP requests with urllib3fromapplicationinsights.clientimportenable_for_urllib3importurllib3.requestsenable_for_urllib3('<YOUR INSTRUMENTATION KEY GOES HERE>')urllib3.PoolManager().request("GET","https://www.python.org/")# a dependency telemetry will be sent to the Application Insights serviceIntegrating with FlaskfromflaskimportFlaskfromapplicationinsights.flask.extimportAppInsights# instantiate the Flask applicationapp=Flask(__name__)app.config['APPINSIGHTS_INSTRUMENTATIONKEY']='<YOUR INSTRUMENTATION KEY GOES HERE>'# log requests, traces and exceptions to the Application Insights serviceappinsights=AppInsights(app)# define a simple route@app.route('/')defhello_world():# the following message will be sent to the Flask log as well as Application Insightsapp.logger.info('Hello World route was called')return'Hello World!'# run the applicationif__name__=='__main__':app.run()Integrating with DjangoPlace the following in yoursettings.pyfile:# If on Django < 1.10MIDDLEWARE_CLASSES=[# ... or whatever is below for you ...'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.auth.middleware.SessionAuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',# ... or whatever is above for you ...'applicationinsights.django.ApplicationInsightsMiddleware',# Add this middleware to the end]# If on Django >= 1.10MIDDLEWARE=[# ... or whatever is below for you ...'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',# ... or whatever is above for you ...'applicationinsights.django.ApplicationInsightsMiddleware',# Add this middleware to the end]APPLICATION_INSIGHTS={# (required) Your Application Insights instrumentation key'ikey':"00000000-0000-0000-0000-000000000000",# (optional) By default, request names are logged as the request method# and relative path of the URL.  To log the fully-qualified view names# instead, set this to True.  Defaults to False.'use_view_name':True,# (optional) To log arguments passed into the views as custom properties,# set this to True.  Defaults to False.'record_view_arguments':True,# (optional) Exceptions are logged by default, to disable, set this to False.'log_exceptions':False,# (optional) Events are submitted to Application Insights asynchronously.# send_interval specifies how often the queue is checked for items to submit.# send_time specifies how long the sender waits for new input before recycling# the background thread.'send_interval':1.0,# Check every second'send_time':3.0,# Wait up to 3 seconds for an event# (optional, uncommon) If you must send to an endpoint other than the# default endpoint, specify it here:'endpoint':"https://dc.services.visualstudio.com/v2/track",}This will log all requests and exceptions to the instrumentation key
specified in theAPPLICATION_INSIGHTSsetting.  In addition, anappinsightsproperty will be placed on each incomingrequestobject in
your views.  This will have the following properties:client: This is an instance of theapplicationinsights.TelemetryClienttype, which will submit telemetry to the same instrumentation key, and
will parent each telemetry item to the current request.request: This is theapplicationinsights.channel.contracts.RequestDatainstance for the current request.  You can modify properties on this
object during the handling of the current request.  It will be submitted
when the request has finished.context: This is theapplicationinsights.channel.TelemetryContextobject for the current ApplicationInsights sender.You can also hook up logging to Django.  For example, to log all builtin
Django warnings and errors, use the following logging configuration insettings.py:LOGGING={'version':1,'disable_existing_loggers':False,'handlers':{# The application insights handler is here'appinsights':{'class':'applicationinsights.django.LoggingHandler','level':'WARNING'}},'loggers':{'django':{'handlers':['appinsights'],'level':'WARNING','propagate':True,}}}See Django’slogging documentationfor more information.Integrating with other web frameworksFor any other Python web framework that isWSGI compliant,
theWSGIApplicationcan be used as a middleware to log requests to Application Insights.Add common properties to WSGIApplication request events by passing in a dictionary to the WSGIApplication constructor:fromwsgiref.simple_serverimportmake_serverfrompyramid.configimportConfiguratorfrompyramid.responseimportResponsefromapplicationinsights.requestsimportWSGIApplication# define a simple pyramid routedefhello_world(request):returnResponse('Hello World!')# construct dictionary which contains properties to be included with every request eventcommon_properties={"service":"hello_world_flask_app","environment":"production"}if__name__=='__main__':# create a simple pyramid appwithConfigurator()asconfig:config.add_route('hello','/')config.add_view(hello_world,route_name='hello')app=config.make_wsgi_app()# wrap the app in the application insights request logging middlewareapp=WSGIApplication('<YOUR INSTRUMENTATION KEY GOES HERE>',app,common_properties=common_properties)# run the appserver=make_server('0.0.0.0',6543,app)server.serve_forever()