Skip to content
Snippets Groups Projects
Unverified Commit ffc314f7 authored by Sergey Kanzhelev's avatar Sergey Kanzhelev Committed by GitHub
Browse files

Merge pull request #108 from Microsoft/develop

Releasing 0.11.5
parents a2c854a3 cf16d923
No related branches found
No related tags found
No related merge requests found
Showing
with 563 additions and 595 deletions
{
"python.pythonPath": "/usr/bin/python2.7"
"python.pythonPath": "/usr/bin/python2.7",
"python.unitTest.unittestEnabled": true,
"python.unitTest.unittestArgs": [
"-v",
"-s",
"test",
"-p",
"*test*.py"
],
// pythonVSCode extension
"python.linting.pylintEnabled": true,
"python.linting.flake8Enabled": false,
"python.linting.pep8Enabled": true,
"python.formatting.provider": "yapf"
}
\ No newline at end of file
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "python setup.py sdist"
},
{
"label": "test",
"type": "shell",
"command": "python setup.py -v test"
}
]
}
\ No newline at end of file
# Changelog
## 0.11.5
- Fixed setting custom properties through context. [#102](https://github.com/Microsoft/ApplicationInsights-Python/pull/102)
## 0.11.4
- Schemas for all data types and context objects updated to the latest version.
- Add common properties argument to WSGIApplication initialization. Those common properties will be associated with telemetry produced by WSGIApplication.
## 0.11.3
- Changelog started from this version.
# How to Contribute
If you're interested in contributing, take a look at the general [contributor's guide](https://github.com/Microsoft/ApplicationInsights-Home/blob/master/CONTRIBUTING.md) first.
## Build
Run `python setup.py sdist`
## Test
- Unit tests: `python setup.py test`
- Django tests: `django_tests/all_tests.sh`
Use `pip install -e <path>` to install it into test application for the testing purposes.
## Generate documentation
1. Install [sphinx](http://www.sphinx-doc.org/en/master/usage/installation.html). On Mac: `brew install sphinx-doc`. You can also use virtualenv:
``` bash
% python3 -m venv env # Create 'env' directory
% . env/bin/activate # Activate virtual environment
% pip install sphinx django # Install sphinx and django (so sphinx can find it)
% python setup.py install # Install applicationinsights package
% cd doc
% make html
.
.
% deactivate # Exit virtualenv
```
2. Open docs folder `cd docs`
3. Generate html documents: `make html`
4. Update gh-pages branch
``` bash
git clone https://github.com/Microsoft/ApplicationInsights-Python.git python-gh-pages
cd python-gh-pages/
git checkout gh-pages
cp -r ../python/doc/build/html/ .
git add -A
git commit -m "upgrade to the latest version"
```
## Releasing new version
This is for repository maintainers only:
This package is published to https://pypi.python.org/pypi/applicationinsights. These are the steps to publish the package.
1. Merge `develop` to `master` via [pull request](https://github.com/Microsoft/ApplicationInsights-Python/compare/master...develop).
2. Tag `master`. Use [CHANGELOG.md](CHANGELOG.md) to get release description.
3. Travis should release a new version. For manual steps:
1. Clean up repo: `git clean -xfd`.
2. Make sure `wheel` is installed: `sudo pip install wheel`.
3. Make sure `twine` is installed: `sudo pip install twine`.
4. Create distributions `python setup.py bdist_wheel`.
5. Create `~/.pypirc` file with the following content
``` ini
[distutils]
index-servers=
pypi
[pypi]
username:AppInsightsSDK
password=<pwd here>
```
6. Test distributive. You can upload it to https://test.pypi.org/ using `twine upload --repository-url https://test.pypi.org/legacy/ dist/*`
7. Upload the package `twine upload dist/*`.
4. Regenerate documentation on gh-pages branch.
5. Update versions in `TelemetryChannel.py`, `CHANGELOG.md`, `conf.py` and `setup.py`.
## Contributing
This project welcomes contributions and suggestions. Most contributions require you to
agree to a Contributor License Agreement (CLA) declaring that you have the right to,
and actually do, grant us the rights to use your contribution. For details, visit
https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need
to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the
instructions provided by the bot. You will only need to do this once across all repositories using our CLA.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2014 Microsoft
Copyright (c) 2018 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
......
include DESCRIPTION.rst
include README.md
include README.rst
include LICENSE.txt
include Microsoft.ApplicationInsights.pyproj
include Microsoft.ApplicationInsights.sln
include CHANGELOG.md
include CONTRIBUTING.md
# Include the test suite
recursive-include tests *
global-exclude *.pyc
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>adc6c556-02c1-4b21-bf8a-403d8bc8bce0</ProjectGuid>
<ProjectHome>
</ProjectHome>
<SearchPath>
</SearchPath>
<WorkingDirectory>.</WorkingDirectory>
<OutputPath>.</OutputPath>
<Name>Microsoft.ApplicationInsights</Name>
<RootNamespace>Microsoft.Telemetry</RootNamespace>
<InterpreterId>{2af0f10d-7135-4994-9156-5d01c9c11b7e}</InterpreterId>
<InterpreterVersion>3.4</InterpreterVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
</PropertyGroup>
<ItemGroup>
<Compile Include="applicationinsights\channel\AsynchronousQueue.py" />
<Compile Include="applicationinsights\channel\AsynchronousSender.py" />
<Compile Include="applicationinsights\channel\contracts\Application.py" />
<Compile Include="applicationinsights\channel\contracts\Data.py" />
<Compile Include="applicationinsights\channel\contracts\DataPoint.py" />
<Compile Include="applicationinsights\channel\contracts\DataPointType.py" />
<Compile Include="applicationinsights\channel\contracts\DependencyKind.py" />
<Compile Include="applicationinsights\channel\contracts\DependencySourceType.py" />
<Compile Include="applicationinsights\channel\contracts\Device.py" />
<Compile Include="applicationinsights\channel\contracts\Envelope.py" />
<Compile Include="applicationinsights\channel\contracts\EventData.py" />
<Compile Include="applicationinsights\channel\contracts\ExceptionData.py" />
<Compile Include="applicationinsights\channel\contracts\ExceptionDetails.py" />
<Compile Include="applicationinsights\channel\contracts\Internal.py" />
<Compile Include="applicationinsights\channel\contracts\Location.py" />
<Compile Include="applicationinsights\channel\contracts\MessageData.py" />
<Compile Include="applicationinsights\channel\contracts\MetricData.py" />
<Compile Include="applicationinsights\channel\contracts\Operation.py" />
<Compile Include="applicationinsights\channel\contracts\PageViewData.py" />
<Compile Include="applicationinsights\channel\contracts\RemoteDependencyData.py" />
<Compile Include="applicationinsights\channel\contracts\RequestData.py" />
<Compile Include="applicationinsights\channel\contracts\Session.py" />
<Compile Include="applicationinsights\channel\contracts\SeverityLevel.py" />
<Compile Include="applicationinsights\channel\contracts\StackFrame.py" />
<Compile Include="applicationinsights\channel\contracts\User.py" />
<Compile Include="applicationinsights\channel\contracts\Utils.py">
<SubType>Code</SubType>
</Compile>
<Compile Include="applicationinsights\channel\contracts\__init__.py" />
<Compile Include="applicationinsights\channel\QueueBase.py" />
<Compile Include="applicationinsights\channel\SenderBase.py" />
<Compile Include="applicationinsights\channel\SynchronousQueue.py" />
<Compile Include="applicationinsights\channel\SynchronousSender.py" />
<Compile Include="applicationinsights\channel\TelemetryChannel.py" />
<Compile Include="applicationinsights\channel\TelemetryContext.py" />
<Compile Include="applicationinsights\channel\__init__.py" />
<Compile Include="applicationinsights\exceptions\enable.py" />
<Compile Include="applicationinsights\exceptions\__init__.py" />
<Compile Include="applicationinsights\logging\LoggingHandler.py" />
<Compile Include="applicationinsights\logging\__init__.py" />
<Compile Include="applicationinsights\requests\WSGIApplication.py" />
<Compile Include="applicationinsights\requests\__init__.py" />
<Compile Include="applicationinsights\TelemetryClient.py" />
<Compile Include="applicationinsights\__init__.py" />
<Compile Include="doc\conf.py" />
<Compile Include="setup.py">
<SubType>Code</SubType>
</Compile>
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestApplication.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestData.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestDataPoint.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestDevice.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestEnvelope.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestEventData.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestExceptionData.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestExceptionDetails.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestInternal.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestLocation.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestMessageData.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestMetricData.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestOperation.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestPageViewData.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestRemoteDependencyData.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestRequestData.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestSession.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestStackFrame.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\TestUser.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\Utils.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\contracts_tests\__init__.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\TestAsynchronousQueue.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\TestAsynchronousSender.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\TestQueueBase.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\TestSenderBase.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\TestSynchronousQueue.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\TestSynchronousSender.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\TestTelemetryChannel.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\TestTelemetryContext.py" />
<Compile Include="tests\applicationinsights_tests\channel_tests\__init__.py" />
<Compile Include="tests\applicationinsights_tests\exception_tests\TestEnable.py" />
<Compile Include="tests\applicationinsights_tests\exception_tests\__init__.py" />
<Compile Include="tests\applicationinsights_tests\logging_tests\TestLoggingHandler.py" />
<Compile Include="tests\applicationinsights_tests\logging_tests\__init__.py" />
<Compile Include="tests\applicationinsights_tests\requests_tests\TestWSGIApplication.py" />
<Compile Include="tests\applicationinsights_tests\requests_tests\__init__.py" />
<Compile Include="tests\applicationinsights_tests\__init__.py" />
<Compile Include="tests\tests.py" />
<Compile Include="tests\applicationinsights_tests\TestTelemetryClient.py" />
</ItemGroup>
<ItemGroup>
<Folder Include="applicationinsights\" />
<Folder Include="applicationinsights\channel\" />
<Folder Include="applicationinsights\channel\contracts\" />
<Folder Include="applicationinsights\exceptions\" />
<Folder Include="applicationinsights\logging\" />
<Folder Include="applicationinsights\requests\" />
<Folder Include="doc\" />
<Folder Include="doc\static\" />
<Folder Include="doc\templates\" />
<Folder Include="tests\" />
<Folder Include="tests\applicationinsights_tests\" />
<Folder Include="tests\applicationinsights_tests\channel_tests\" />
<Folder Include="tests\applicationinsights_tests\channel_tests\contracts_tests\" />
<Folder Include="tests\applicationinsights_tests\exception_tests\" />
<Folder Include="tests\applicationinsights_tests\logging_tests\" />
<Folder Include="tests\applicationinsights_tests\requests_tests\" />
</ItemGroup>
<ItemGroup>
<InterpreterReference Include="{2af0f10d-7135-4994-9156-5d01c9c11b7e}\2.7" />
<InterpreterReference Include="{2af0f10d-7135-4994-9156-5d01c9c11b7e}\3.4" />
</ItemGroup>
<ItemGroup>
<Content Include=".gitignore" />
<Content Include="DESCRIPTION.rst" />
<Content Include="doc\applicationinsights.channel.contracts.rst" />
<Content Include="doc\applicationinsights.channel.rst" />
<Content Include="doc\applicationinsights.exceptions.rst" />
<Content Include="doc\applicationinsights.logging.rst" />
<Content Include="doc\applicationinsights.requests.rst" />
<Content Include="doc\applicationinsights.rst" />
<Content Include="doc\index.rst" />
<Content Include="doc\make.bat" />
<Content Include="doc\Makefile" />
<Content Include="doc\static\overrides.css" />
<Content Include="doc\templates\layout.html" />
<Content Include="LICENSE.txt" />
<Content Include="MANIFEST.in" />
<Content Include="README.md" />
<Content Include="setup.cfg" />
</ItemGroup>
<PropertyGroup>
<VisualStudioVersion>12.0</VisualStudioVersion>
<PtvsTargetsFile>$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0\Python Tools\Microsoft.PythonTools.targets</PtvsTargetsFile>
</PropertyGroup>
<Import Condition="Exists($(PtvsTargetsFile))" Project="$(PtvsTargetsFile)" />
<Import Condition="!Exists($(PtvsTargetsFile))" Project="$(MSBuildToolsPath)\Microsoft.Common.targets" />
<!-- Uncomment the CoreCompile target to enable the Build command in
Visual Studio and specify your pre- and post-build commands in
the BeforeBuild and AfterBuild targets below. -->
</Project>
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30723.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "Microsoft.ApplicationInsights", "Microsoft.ApplicationInsights.pyproj", "{ADC6C556-02C1-4B21-BF8A-403D8BC8BCE0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{ADC6C556-02C1-4B21-BF8A-403D8BC8BCE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ADC6C556-02C1-4B21-BF8A-403D8BC8BCE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
# Application Insights for Python #
[![Build Status](https://travis-ci.org/Microsoft/ApplicationInsights-Python.svg?branch=master)](https://travis-ci.org/Microsoft/ApplicationInsights-Python)
[![PyPI version](https://badge.fury.io/py/applicationinsights.svg)](http://badge.fury.io/py/applicationinsights)
This project extends the Application Insights API surface to support Python. [Application Insights](http://azure.microsoft.com/en-us/services/application-insights/) is 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.
## Requirements ##
Python >=2.7 and Python >=3.4 are currently supported by this module.
For opening the project in Microsoft Visual Studio you will need [Python Tools for Visual Studio](http://pytools.codeplex.com/).
## Installation ##
To install the latest release you can use [pip](http://www.pip-installer.org/).
```
$ pip install applicationinsights
```
## Usage ##
Once 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 the [Getting an Application Insights Instrumentation Key](https://github.com/Microsoft/AppInsights-Home/wiki#getting-an-application-insights-instrumentation-key) section for more information.
**Sending a simple event telemetry item**
```python
from applicationinsights import TelemetryClient
tc = TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')
tc.track_event('Test event')
tc.flush()
```
**Sending an event telemetry item with custom properties and measurements**
```python
from applicationinsights import TelemetryClient
tc = TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')
tc.track_event('Test event', { 'foo': 'bar' }, { 'baz': 42 })
tc.flush()
```
**Sending a trace telemetry item with custom properties**
```python
from applicationinsights import TelemetryClient
tc = TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')
tc.track_trace('Test trace', { 'foo': 'bar' })
tc.flush()
```
**Sending a metric telemetry item**
```python
from applicationinsights import TelemetryClient
tc = TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')
tc.track_metric('My Metric', 42)
tc.flush()
```
**Sending an exception telemetry item with custom properties and measurements**
```python
import sys
from applicationinsights import TelemetryClient
tc = TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')
try:
raise Exception('blah')
except:
tc.track_exception()
try:
raise Exception("blah")
except:
tc.track_exception(*sys.exc_info(), properties={ 'foo': 'bar' }, measurements={ 'x': 42 })
tc.flush()
```
**Configuring context for a telemetry client instance**
```python
from applicationinsights import TelemetryClient
tc = 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.track_trace('My trace with context')
tc.flush()
```
**Configuring channel related properties**
```python
from applicationinsights import TelemetryClient
tc = 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 queue
tc.channel.sender.max_queue_item_count = 10
```
**Basic logging configuration (first option)**
```python
import logging
from applicationinsights.logging import enable
# set up logging
enable('<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 items
# alternatively flush manually via handler.flush()
```
**Basic logging configuration (second option)**
```python
import logging
from applicationinsights.logging import LoggingHandler
# set up logging
handler = 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:
raise Exception('Some exception')
except:
# this will send an exception to the Application Insights service
logging.exception('Code went boom!')
# logging shutdown will cause a flush of all un-sent telemetry items
# alternatively flush manually via handler.flush()
```
**Advanced logging configuration**
```python
import logging
from applicationinsights.logging import LoggingHandler
# set up logging
handler = LoggingHandler('<YOUR INSTRUMENTATION KEY GOES HERE>')
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 unhandled exceptions**
```python
from applicationinsights.exceptions import enable
# set up exception capture
enable('<YOUR INSTRUMENTATION KEY GOES HERE>')
# raise an exception (this will be sent to the Application Insights service as an exception telemetry object)
raise Exception('Boom!')
```
**Integrating with Flask**
```python
from flask import Flask
from applicationinsights.flask.ext import AppInsights
# instantiate the Flask application
app = Flask(__name__)
app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = '<YOUR INSTRUMENTATION KEY GOES HERE>'
# log requests, traces and exceptions to the Application Insights service
appinsights = AppInsights(app)
# define a simple route
@app.route('/')
def hello_world():
return 'Hello World!'
# run the application
if __name__ == '__main__':
app.run()
```
**Integrating with Django**
Place the following in your `settings.py` file:
```python
# If on Django < 1.10
MIDDLEWARE_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.10
MIDDLEWARE = [
# ... 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 the `APPLICATION_INSIGHTS` setting. In addition, an
`appinsights` property will be placed on each incoming `request` object in
your views. This will have the following properties:
* `client`: This is an instance of the `applicationinsights.TelemetryClient`
type, which will submit telemetry to the same instrumentation key, and
will parent each telemetry item to the current request.
* `request`: This is the `applicationinsights.channel.contracts.RequestData`
instance 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 the `applicationinsights.channel.TelemetryContext`
object 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 in
`settings.py`:
```python
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's [logging documentation](https://docs.djangoproject.com/en/1.11/topics/logging/)
for more information.
**Integrating with other web frameworks**
For any other Python web framework that is [WSGI compliant](https://www.python.org/dev/peps/pep-0333/),
the [WSGIApplication](https://github.com/Microsoft/ApplicationInsights-Python/blob/master/applicationinsights/requests/WSGIApplication.py)
can 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:
```
from flask import Flask
from applicationinsights.requests import WSGIApplication
# instantiate the Flask application and wrap its WSGI application
app = Flask(__name__)
# Construct dictionary which contains properties to be included with every request event
common_properties = {
"service": "hello_world_flask_app",
"environment": "production"
}
app.wsgi_app = WSGIApplication('<YOUR INSTRUMENTATION KEY GOES HERE>', app.wsgi_app, common_properties=common_properties)
# define a simple route
@app.route('/')
def hello_world():
return 'Hello World!'
# run the application
if __name__ == '__main__':
app.run()
```
## Publishing new version to pypi.python.org
This package is published to https://pypi.python.org/pypi/applicationinsights. These are the steps to publish the package.
1. Update the version in the following places:
* /applicationinsights/channel/TelemetryChannel.py
* conf.py
* setup.py
2. Create ~/.pypirc file with the following content
```
[distutils]
index-servers=
pypi
[pypi]
username:AppInsightsSDK
password=<pwd here>
```
3. Create distribution package:
```
python setup.py sdist
```
4. Install twine
```
sudo pip install twine
```
5. twine upload dist/*
Application Insights for Python
===============================
This project extends the Application Insights API surface to support Python. `Application Insights <http://azure.microsoft.com/en-us/services/application-insights/>`_ is 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.
.. image:: https://travis-ci.org/Microsoft/ApplicationInsights-Python.svg?branch=master
:target: https://travis-ci.org/Microsoft/ApplicationInsights-Python
.. image:: https://badge.fury.io/py/applicationinsights.svg
:target: http://badge.fury.io/py/applicationinsights
This project extends the Application Insights API surface to support Python. `Application Insights <http://azure.microsoft.com/services/application-insights/>`_ is 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.
Requirements
------------
Python 2.7 and Python 3.4 are currently supported by this module.
For opening the project in Microsoft Visual Studio you will need `Python Tools for Visual Studio <http://pytools.codeplex.com/>`_.
Python >=2.7 and Python >=3.4 are currently supported by this module.
Installation
------------
......@@ -32,7 +37,7 @@ Once installed, you can send telemetry to Application Insights. Here are a few s
from applicationinsights import TelemetryClient
tc = TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')
tc.track_event("Test event")
tc.track_event('Test event')
tc.flush()
**Sending an event telemetry item with custom properties and measurements**
......@@ -92,6 +97,7 @@ Once installed, you can send telemetry to Application Insights. Here are a few s
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()
......@@ -120,7 +126,7 @@ Once installed, you can send telemetry to Application Insights. Here are a few s
logging.info('This is a message')
# logging shutdown will cause a flush of all un-sent telemetry items
# alternatively flush manually via handler.flush()
logging.shutdown()
**Basic logging configuration (second option)**
......@@ -144,16 +150,23 @@ Once installed, you can send telemetry to Application Insights. Here are a few s
# logging shutdown will cause a flush of all un-sent telemetry items
# alternatively flush manually via handler.flush()
logging.shutdown()
**Advanced logging configuration**
.. code:: python
import logging
from applicationinsights import channel
from applicationinsights.logging import LoggingHandler
# set up channel with context
telemetry_channel = channel.TelemetryChannel()
telemetry_channel.context.application.ver = '1.2.3'
telemetry_channel.context.properties['my_property'] = 'my_value'
# set up logging
handler = LoggingHandler('<YOUR INSTRUMENTATION KEY GOES HERE>')
handler = 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')
......@@ -165,6 +178,7 @@ Once installed, you can send telemetry to Application Insights. Here are a few s
# logging shutdown will cause a flush of all un-sent telemetry items
# alternatively flush manually via handler.flush()
logging.shutdown()
**Logging unhandled exceptions**
......@@ -178,16 +192,41 @@ Once installed, you can send telemetry to Application Insights. Here are a few s
# raise an exception (this will be sent to the Application Insights service as an exception telemetry object)
raise Exception('Boom!')
**Logging requests**
# exceptions will cause a flush of all un-sent telemetry items
**Logging unhandled exceptions with context**
.. code:: python
from flask import Flask
from applicationinsights.requests import WSGIApplication
from applicationinsights import channel
from applicationinsights.exceptions import enable
# set up channel with context
telemetry_channel = channel.TelemetryChannel()
telemetry_channel.context.application.ver = '1.2.3'
telemetry_channel.context.properties['my_property'] = 'my_value'
# set up exception capture
enable('<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)
raise Exception('Boom!')
# exceptions will cause a flush of all un-sent telemetry items
# instantiate the Flask application and wrap its WSGI application
**Integrating with Flask**
.. code:: python
from flask import Flask
from applicationinsights.flask.ext import AppInsights
# instantiate the Flask application
app = Flask(__name__)
app.wsgi_app = WSGIApplication('<YOUR INSTRUMENTATION KEY GOES HERE>', app.wsgi_app)
app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = '<YOUR INSTRUMENTATION KEY GOES HERE>'
# log requests, traces and exceptions to the Application Insights service
appinsights = AppInsights(app)
# define a simple route
@app.route('/')
......@@ -197,3 +236,148 @@ Once installed, you can send telemetry to Application Insights. Here are a few s
# run the application
if __name__ == '__main__':
app.run()
**Integrating with Django**
Place the following in your `settings.py` file:
.. code:: python
# If on Django < 1.10
MIDDLEWARE_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.10
MIDDLEWARE = [
# ... 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 the `APPLICATION_INSIGHTS` setting. In addition, an
`appinsights` property will be placed on each incoming `request` object in
your views. This will have the following properties:
* `client`: This is an instance of the `applicationinsights.TelemetryClient`
type, which will submit telemetry to the same instrumentation key, and
will parent each telemetry item to the current request.
* `request`: This is the `applicationinsights.channel.contracts.RequestData`
instance 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 the `applicationinsights.channel.TelemetryContext`
object 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 in
`settings.py`:
.. code:: python
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's `logging documentation <https://docs.djangoproject.com/en/1.11/topics/logging/>`_
for more information.
**Integrating with other web frameworks**
For any other Python web framework that is `WSGI compliant <https://www.python.org/dev/peps/pep-0333/>`_,
the `WSGIApplication <https://github.com/Microsoft/ApplicationInsights-Python/blob/master/applicationinsights/requests/WSGIApplication.py>`_
can 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:
.. code:: python
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from applicationinsights.requests import WSGIApplication
# define a simple pyramid route
def hello_world(request):
return Response('Hello World!')
# construct dictionary which contains properties to be included with every request event
common_properties = {
"service": "hello_world_flask_app",
"environment": "production"
}
if __name__ == '__main__':
# create a simple pyramid app
with Configurator() as config:
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 middleware
app = WSGIApplication('<YOUR INSTRUMENTATION KEY GOES HERE>', app, common_properties=common_properties)
# run the app
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
......@@ -34,7 +34,7 @@ class TelemetryClient(object):
this value.
Returns:
:class:`channel.TelemetryChannel`. the context instance.
:class:`channel.TelemetryContext`. the context instance.
"""
return self._context
......
......@@ -12,7 +12,7 @@ if sys.version_info >= (3, 0):
# set up internal context
internal_context = contracts.Internal()
internal_context.sdk_version = platform_moniker + ':0.11.4'
internal_context.sdk_version = platform_moniker + ':0.11.5'
class TelemetryChannel(object):
"""The telemetry channel is responsible for constructing a :class:`contracts.Envelope` object from the passed in
......@@ -96,14 +96,14 @@ class TelemetryChannel(object):
tags[key] = value
envelope.data = contracts.Data()
envelope.data.base_type = data.DATA_TYPE_NAME
if hasattr(data, 'properties') and local_context.properties:
properties = data.properties
if not properties:
properties = {}
data.properties = properties
for key in local_context.properties:
if key not in properties:
properties[key] = local_context.properties[key]
for prop_context in [context, self._context]:
if not prop_context:
continue
if hasattr(data, 'properties') and prop_context.properties:
properties = data.properties
for key in prop_context.properties:
if key not in properties:
properties[key] = prop_context.properties[key]
envelope.data.base_data = data
self._queue.put(envelope)
......
......@@ -172,7 +172,13 @@ class ApplicationInsightsMiddleware(object):
# If use_view_name is set, then we'll look up the name of the view.
if self._settings.use_view_name:
mod = inspect.getmodule(view_func)
name = view_func.__name__
if hasattr(view_func, "__name__"):
name = view_func.__name__
elif hasattr(view_func, "__class__") and hasattr(view_func.__class__, "__name__"):
name = view_func.__class__.__name__
else:
name = "<unknown>"
if mod:
opname = "%s %s.%s" % (data.http_method, mod.__name__, name)
else:
......
......@@ -10,12 +10,12 @@ BASEDIR=$(pwd)
# Django/python compatibility matrix...
if $PYTHON -c "import sys; sys.exit(0 if sys.version_info < (3, 0) else 1)"; then
# Django2.0 won't support Python2
DJANGO_VERSIONS='1.7.11 1.8.18 1.9.13 1.10.7 1.11.4'
DJANGO_VERSIONS='1.7.11 1.8.19 1.9.13 1.10.8 1.11.13'
elif $PYTHON -c "import sys; sys.exit(0 if sys.version_info < (3, 5) else 1)"; then
DJANGO_VERSIONS='1.7.11 1.8.18 1.9.13 1.10.7 1.11.4'
DJANGO_VERSIONS='1.7.11 1.8.19 1.9.13 1.10.8 1.11.13 2.0.6'
else
# python3.5 dropped html.parser.HtmlParserError versions older than Django1.8 won't work
DJANGO_VERSIONS='1.8.18 1.9.13 1.10.7 1.11.4'
DJANGO_VERSIONS='1.8.19 1.9.13 1.10.8 1.11.13 2.0.6'
fi
# For each Django version...
......@@ -38,7 +38,20 @@ do
trap cleanup EXIT SIGINT
# Create virtual environment
virtualenv -p $PYTHON $TMPDIR/env
if $PYTHON -c "import sys; sys.exit(0 if sys.version_info < (3, 3) else 1)"; then
if command -v virtualenv >/dev/null 2>&1; then
virtualenv -p $PYTHON $TMPDIR/env || exit $?
elif $PYTHON -c "import sys; sys.exit(0 if sys.version_info < (3, 0) else 1)"; then
if command -v virtualenv2 >/dev/null 2>&1; then
virtualenv2 -p $PYTHON $TMPDIR/env || exit $?
fi
else
echo Requires virtualenv
exit 1
fi
else
$PYTHON -m venv $TMPDIR/env
fi
# Install Django version + application insights
. $TMPDIR/env/bin/activate
......
......@@ -198,7 +198,7 @@ class RequestSettingsTests(AITestCase):
@override_settings(APPLICATION_INSIGHTS={'ikey': TEST_IKEY, 'use_view_name': True})
def test_use_view_name(self):
"""Tests that request names are set to URLs when use_operation_url=True"""
"""Tests that request names are set to view names when use_view_name=True"""
self.plug_sender()
self.client.get('/')
event = self.get_events(1)
......@@ -207,13 +207,22 @@ class RequestSettingsTests(AITestCase):
@override_settings(APPLICATION_INSIGHTS={'ikey': TEST_IKEY, 'use_view_name': False})
def test_use_view_name_off(self):
"""Tests that request names are set to view names when use_operation_url=False"""
"""Tests that request names are set to URLs when use_view_name=False"""
self.plug_sender()
self.client.get('/')
event = self.get_events(1)
self.assertEqual(event['data']['baseData']['name'], 'GET /', "Request name")
self.assertEqual(event['tags']['ai.operation.name'], 'GET /', "Operation name")
@override_settings(APPLICATION_INSIGHTS={'ikey': TEST_IKEY, 'use_view_name': True})
def test_view_name_class(self):
"""Tests that classes can be correctly identified when use_view_name=True"""
self.plug_sender()
self.client.get('/class')
event = self.get_events(1)
self.assertEqual(event['data']['baseData']['name'], 'GET aitest.views.classview', "Request name")
self.assertEqual(event['tags']['ai.operation.name'], 'GET aitest.views.classview', "Operation name")
@override_settings(APPLICATION_INSIGHTS=None)
def test_appinsights_still_supplied(self):
"""Tests that appinsights is still added to requests even if APPLICATION_INSIGHTS is unspecified"""
......
......@@ -4,11 +4,6 @@ from django.contrib import admin
from . import views
urlpatterns = [
# Examples:
# url(r'^$', 'aitest.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.home, name='home'),
url(r'^logger$', views.logger, name='logger'),
url(r'^thrower$', views.thrower, name='thrower'),
......@@ -16,4 +11,5 @@ urlpatterns = [
url(r'^getid/([0-9]+)$', views.getid, name='getid'),
url(r'^returncode/([0-9]+)$', views.returncode, name='returncode'),
url(r'^templater/([^/]*)$', views.templater, name='templater'),
url(r'^class$', views.classview(), name='class'),
]
......@@ -25,3 +25,7 @@ def returncode(request, id):
def templater(request, data):
return TemplateResponse(request, 'template.html', {'context': data})
class classview:
def __call__(self, request):
return HttpResponse("You called a class.")
......@@ -32,20 +32,6 @@ DataPointType class
:member-order: groupwise
:inherited-members:
DependencyKind class
--------------------
.. autoclass:: applicationinsights.channel.contracts.DependencyKind
:members:
:member-order: groupwise
:inherited-members:
DependencySourceType class
--------------------------
.. autoclass:: applicationinsights.channel.contracts.DependencySourceType
:members:
:member-order: groupwise
:inherited-members:
Device class
------------
.. autoclass:: applicationinsights.channel.contracts.Device
......
......@@ -52,16 +52,16 @@ master_doc = 'index'
# General information about the project.
project = 'Application Insights SDK for Python'
copyright = '2014, Microsoft'
copyright = '2018, Microsoft'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.11.4'
version = '0.11.5'
# The full version, including alpha/beta/rc tags.
release = '0.11.4'
release = '0.11.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
......
......@@ -5,7 +5,7 @@ from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
......@@ -14,7 +14,7 @@ setup(
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# http://packaging.python.org/en/latest/tutorial.html#version
version='0.11.4',
version='0.11.5',
description='This project extends the Application Insights API surface to support Python.',
long_description=long_description,
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment