Azure Log Analytics:如何将自定义 python pandas 数据帧发送到 LAW

问题描述 投票:0回答:1

我有一个 Python 脚本,我想每天运行它来生成 Pandas 数据框。

我希望每天将此数据框添加到我的日志分析工作区。

我有一个 Windows 服务器,可以用来运行我的 Python 脚本。

我需要做什么才能使这项工作成功?有没有办法从 DataFrames 推送到 Syslog 服务器?

python azure syslog azure-log-analytics sentinel
1个回答
0
投票

我已经在我的环境中重现了,以下是我的预期结果:

我从 Microsoft-Document 中获取了以下代码并进行了一些修改:

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:

enter image description here

enter image description here

enter image description here

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

© www.soinside.com 2019 - 2024. All rights reserved.