这个项目扩展了applicationinsightsapi界面以支持Python。

appinsights的Python项目详细描述


https://github.com/brennerm/python-appinsights/workflows/.github/workflows/ci.yml/badge.svghttps://badge.fury.io/py/appinsights.svg

此项目扩展了applicationinsights API表面以支持Python。 Application Insights是一种 允许开发人员保持他们的应用程序可用,执行和 成功。这个Python模块允许您发送各种类型的遥测数据 (事件、跟踪、异常等)到Application Insights服务 可以在Azure门户中可视化。指向Application Insights API的链接 文档可以找到here。在

此项目不受官方支持,不建议高负载 生产用途。这个项目是开源的,欢迎大家的贡献。在

要求

此模块当前支持Python>;=2.7和Python>;=3.4。在

安装

要安装最新版本,可以使用pip。在

$ pip install appinsights

文件

请参阅https://brennerm.github.io/python-appinsights/获取完整文档。在

使用

安装后,可以将遥测发送到Application Insights。这是一些样品。在

Note: before you can send data to you will need an instrumentation key. Please see the Getting an Application Insights Instrumentation Key section for more information.

发送一个简单的事件遥测项目

^{pr2}$

发送具有自定义属性和度量的事件遥测项

fromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.track_event('Test event',{'foo':'bar'},{'baz':42})tc.flush()

发送具有自定义属性的跟踪遥测项目

fromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.track_trace('Test trace',{'foo':'bar'})tc.flush()

{str}1发送遥测项目

fromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.track_metric('My Metric',42)tc.flush()

发送可用性遥测项目

fromapplicationinsightsimportTelemetryClienttc=TelemetryClient('<YOUR INSTRUMENTATION KEY GOES HERE>')tc.track_availability('My Service',250,True,"West Europe")tc.flush()

发送具有自定义属性和度量的异常遥测项目

importsysfromapplicationinsightsimportTelemetryClienttc=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()

为遥测客户端实例配置上下文

fromapplicationinsightsimportTelemetryClienttc=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()

建立遥测对象之间的关联

可以将名为operation_id的上下文字段设置为关联遥测项。 由于操作_id被设置为遥测客户端的属性,因此不应在并行线程中重用该客户端,因为这可能会导致并发问题。在

tc=TelemetryClient(instrumentation_key=instrumentation_key)tc.context.operation.id=<operation_id>tc.track_trace('Test trace')tc.flush()

配置频道相关属性

fromapplicationinsightsimportTelemetryClienttc=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=10

配置遥测处理器

fromapplicationinsightsimportTelemetryClientdefprocess(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)

基本日志记录配置(第一个选项)

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()

基本日志记录配置(第二个选项)

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()

高级日志记录配置

importloggingfromapplicationinsightsimportchannelfromapplicationinsights.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()

记录未处理的异常

fromapplicationinsights.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 items

记录上下文中未处理的异常

fromapplicationinsightsimportchannelfromapplicationinsights.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 items

Track dependency telemetry for HTTP请求和请求

fromapplicationinsights.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 service

Track dependency telemetry用于使用urllib的HTTP请求

fromapplicationinsights.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 service

Track dependency telemetry用于使用urllib2的HTTP请求

fromapplicationinsights.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 service

Track dependency telemetry用于使用urllib3的HTTP请求

fromapplicationinsights.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 service

与烧瓶集成

^{pr21}$

与Django集成

将以下内容放入您的设置.py文件:

# 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",}

这将记录检测密钥的所有请求和异常 在APPLICATION_INSIGHTS设置中指定。此外,一个 appinsights属性将放置在中的每个传入请求对象上 你的观点。它将具有以下属性:

  • 客户端:这是applicationinsights.TelemetryClient 类型,它将向同一检测密钥提交遥测,并且 将每个遥测项目作为当前请求的父级。在
  • 请求:这是applicationinsights.channel.contracts.RequestData 当前请求的实例。您可以修改此的属性 在处理当前请求期间。它将被提交 当请求完成时。在
  • 上下文:这是应用程序oninsights.channel.TelemetryContext 当前ApplicationInsights发送方的对象。在

您还可以将日志连接到Django。例如,记录所有内置项 Django警告和错误,请在中使用以下日志记录配置 <引用>设置.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,}}}

见Django的logging documentation 了解更多信息。在

与其他web框架集成

对于WSGI compliant的任何其他Python web框架, WSGIApplication 可作为中间件将请求记录到Application Insights。在

通过向WSGIApplication构造函数传递字典,向WSGIApplication请求事件添加公共属性:

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()

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何为没有域的主机创建SSL证书?   数字的java正则表达式   java将\t\n显示为节点的原因是什么?   在java 8中按多个字段名分组   java Spring。使用@Configuration注释配置类。拥有多个配置类是否正确?   在java中设置Jasper报表的字体   eclipse Java双括号初始化   java如何测试活动性失败?   java使用JSch列出SFTP中的前N个文件   java Android结合了两个LayoutParams   java简单计算器应用程序防止崩溃   java在Eclipse4中禁用拖放部分   JavaFX过滤JDK Bug系统   java如何为所有实体实现通用spring jpa存储库   未使用正确的方法处理java捕获的异常