Azure日志分析:如何将自定义python pandas DataFrames发送到LAW

yduiuuwa  于 2023-10-22  发布在  Python
关注(0)|答案(1)|浏览(103)

我有一个Python脚本,我想每天运行,产生一个Pandas框架。
我希望这个框架每天添加到我的日志分析工作区。
我有一个Windows服务器,可以用来运行我的Python脚本。
我需要做些什么来使这个工作?有没有一种方法可以从 Dataframe 推送到系统日志服务器?

m3eecexj

m3eecexj1#

Azure日志分析:如何将自定义python pandas DataFrames发送到LAW
我在我的环境中复制,下面是我的预期结果:
我从Microsoft文档中获取了下面的代码,并进行了一些修改:

import json
import requests
import datetime
import hashlib
import hmac
import base64

logtype2="RithwikLogs1"
def build_signature(customer_id, shared_key, date, content_length, method, content_type, resource):
    x_headers = 'x-ms-date:' + date
    string_to_hash = method + "\n" + str(content_length) + "\n" + content_type + "\n" + x_headers + "\n" + resource
    bytes_to_hash = bytes(string_to_hash, encoding="utf-8")  
    decoded_key = base64.b64decode(shared_key)
    encoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_hash, digestmod=hashlib.sha256).digest()).decode()
    authorization = "SharedKey {}:{}".format(customer_id,encoded_hash)
    return authorization

def post_data1(customer_id, shared_key, body, log_type):
    method = 'POST'
    content_type = 'application/json'
    resource = '/api/logs'
    rfc1123date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
    content_length = len(body)
    signature = build_signature(customer_id, shared_key, rfc1123date, content_length, method, content_type, resource)
    uri = 'https://' + customer_id + '.ods.opinsights.azure.com' + resource + '?api-version=2016-04-01'

    headers = {
        'content-type': content_type,
        'Authorization': signature,
        'Log-Type': log_type,
        'x-ms-date': rfc1123date
    }

    response = requests.post(uri,data=body, headers=headers)
    if (response.status_code >= 200 and response.status_code <= 299):
        print('Rithwik Data Frame is sent to Log Analytics Worksapce ')
    else:
        print("Response code: {}".format(response.status_code))
rithwik_data1 = pd.DataFrame({
    'Name': ['Rithwik', 'Bojja', 'Chotu'],
    'Age': [23, 23, 20]
})

post_data1('310603f7', 'a3m2jEErIT6HONEdrAhgIGBrT9L78AK0wk0H8HJKkEdTva4nmw==',rithwik_data1.to_json(orient="records")
, logtype2)

Output:

运行python代码后,需要一些时间才能在Log Analytics中生成日志(等待大约5-10分钟)。

Note:

在调用函数时:

post_data1('yourworkspaceid', 'Primarykey(sharedkey)',body(json of df), logtype2)

您可以通过以下方式获得上述值:

相关问题