使用 HTTP 数据收集器 API(公共预览版)将日志数据发送到 Azure MonitorSend log data to Azure Monitor with the HTTP Data Collector API (public preview)

本文介绍如何使用 HTTP 数据收集器 API 从 REST API 客户端将日志数据发送到 Azure Monitor。This article shows you how to use the HTTP Data Collector API to send log data to Azure Monitor from a REST API client. 其中说明了对于脚本或应用程序收集的数据,如何设置其格式、将其包含在请求中,并由 Azure Monitor 授权该请求。It describes how to format data collected by your script or application, include it in a request, and have that request authorized by Azure Monitor. 将针对 PowerShell、C# 和 Python 提供示例。Examples are provided for PowerShell, C#, and Python.

Note

本文最近已更新,从使用术语“Log Analytics”改为使用术语“Azure Monitor 日志”。This article was recently updated to use the term Azure Monitor logs instead of Log Analytics. 日志数据仍然存储在 Log Analytics 工作区中,并仍然由同一 Log Analytics 服务收集并分析。Log data is still stored in a Log Analytics workspace and is still collected and analyzed by the same Log Analytics service. 我们正在更新术语,以便更好地反映 Azure Monitor 中日志的角色。We are updating the terminology to better reflect the role of logs in Azure Monitor. 有关详细信息,请参阅 Azure Monitor 术语更改See Azure Monitor terminology changes for details.

Note

Azure Monitor HTTP 数据收集器 API 以公共预览版形式提供。The Azure Monitor HTTP Data Collector API is in public preview.

概念Concepts

可以使用 HTTP 数据收集器 API,从能够调用 REST API 的任何客户端将日志数据发送到 Azure Monitor 中的 Log Analytics 工作区。You can use the HTTP Data Collector API to send log data to a Log Analytics workspace in Azure Monitor from any client that can call a REST API. 这可能是 Azure 自动化中从 Azure 或另一个云收集管理数据的 runbook,也可能是使用 Azure Monitor 合并和分析日志数据的备用管理系统。This might be a runbook in Azure Automation that collects management data from Azure or another cloud, or it might be an alternate management system that uses Azure Monitor to consolidate and analyze log data.

Log Analytics 工作区中的所有数据都存储为具有某种特定记录类型的记录。All data in the Log Analytics workspace is stored as a record with a particular record type. 可以将要发送到 HTTP 数据收集器 API 的数据格式化为采用 JSON 格式的多条记录。You format your data to send to the HTTP Data Collector API as multiple records in JSON. 提交数据时,将针对请求负载中的每条记录在存储库中创建单独的记录。When you submit the data, an individual record is created in the repository for each record in the request payload.

HTTP 数据收集器概述

创建请求Create a request

若要使用 HTTP 数据收集器 API,可以创建一个 POST 请求,其中包含要以 JavaScript 对象表示法 (JSON) 格式发送的数据。To use the HTTP Data Collector API, you create a POST request that includes the data to send in JavaScript Object Notation (JSON). 接下来的三个表列出了每个请求所需的属性。The next three tables list the attributes that are required for each request. 在本文的后面部分将更详细地介绍每个属性。We describe each attribute in more detail later in the article.

请求 URIRequest URI

属性Attribute 属性Property
方法Method POSTPOST
URIURI https://<CustomerId>.ods.opinsights.azure.cn/api/logs?api-version=2016-04-01https://<CustomerId>.ods.opinsights.azure.cn/api/logs?api-version=2016-04-01
内容类型Content type application/jsonapplication/json

请求 URI 参数Request URI parameters

参数Parameter 说明Description
CustomerIDCustomerID Log Analytics 工作区的唯一标识符。The unique identifier for the Log Analytics workspace.
资源Resource API 资源名称: /api/logs。The API resource name: /api/logs.
API 版本API Version 用于此请求的 API 版本。The version of the API to use with this request. 目前,API 版本为 2016-04-01。Currently, it's 2016-04-01.

请求标头Request headers

标头Header 说明Description
授权Authorization 授权签名。The authorization signature. 在本文的后面部分,可以了解有关如何创建 HMAC-SHA256 标头的信息。Later in the article, you can read about how to create an HMAC-SHA256 header.
Log-TypeLog-Type 指定正在提交的数据的记录类型。Specify the record type of the data that is being submitted. 此参数的大小限制为 100 个字符。The size limit for this parameter is 100 characters.
x-ms-datex-ms-date 处理请求的日期,采用 RFC 1123 格式。The date that the request was processed, in RFC 1123 format.
x-ms-AzureResourceIdx-ms-AzureResourceId 应该与数据关联的 Azure 资源的资源 ID。Resource ID of the Azure resource the data should be associated with. 如果未指定此字段,则不会将数据包括在以资源为中心的查询中。If this field isn't specified, the data will not be included in resource-centric queries.
time-generated-fieldtime-generated-field 数据中包含数据项时间戳的字段名称。The name of a field in the data that contains the timestamp of the data item. 如果指定某一字段,其内容用于 TimeGeneratedIf you specify a field then its contents are used for TimeGenerated. 如果未指定此字段,TimeGenerated 的默认值是引入消息的时间。If this field isn’t specified, the default for TimeGenerated is the time that the message is ingested. 消息字段的内容应遵循 ISO 8601 格式 YYYY-MM-DDThh:mm:ssZ。The contents of the message field should follow the ISO 8601 format YYYY-MM-DDThh:mm:ssZ.

授权Authorization

Azure Monitor HTTP 数据收集器 API 的任何请求都必须包含授权标头。Any request to the Azure Monitor HTTP Data Collector API must include an authorization header. 若要验证请求,必须针对发出请求的工作区使用主要或辅助密钥对请求进行签名。To authenticate a request, you must sign the request with either the primary or the secondary key for the workspace that is making the request. 然后,传递该签名作为请求的一部分。Then, pass that signature as part of the request.

下面是授权标头的格式:Here's the format for the authorization header:

Authorization: SharedKey <WorkspaceID>:<Signature>

WorkspaceID 是 Log Analytics 工作区的唯一标识符。WorkspaceID is the unique identifier for the Log Analytics workspace. 签名基于哈希的消息验证代码 (HMAC),它构造自请求并使用 SHA256 算法进行计算。Signature is a Hash-based Message Authentication Code (HMAC) that is constructed from the request and then computed by using the SHA256 algorithm. 然后,使用 Base64 编码进行编码。Then, you encode it by using Base64 encoding.

使用此格式对 SharedKey 签名字符串进行编码:Use this format to encode the SharedKey signature string:

StringToSign = VERB + "\n" +
                  Content-Length + "\n" +
               Content-Type + "\n" +
                  x-ms-date + "\n" +
                  "/api/logs";

下面是签名字符串的示例:Here's an example of a signature string:

POST\n1024\napplication/json\nx-ms-date:Mon, 04 Apr 2016 08:00:00 GMT\n/api/logs

如果具有签名字符串,可在 UTF-8 编码的字符串上使用 HMAC-SHA256 算法对其进行编码,并以 Base64 形式对结果进行编码。When you have the signature string, encode it by using the HMAC-SHA256 algorithm on the UTF-8-encoded string, and then encode the result as Base64. 使用以下格式:Use this format:

Signature=Base64(HMAC-SHA256(UTF8(StringToSign)))

后续部分中的示例提供了示例代码,可帮助你创建授权标头。The samples in the next sections have sample code to help you create an authorization header.

请求正文Request body

消息正文必须采用 JSON 格式。The body of the message must be in JSON. 它必须包括一个或多个记录,其中包含采用以下格式的属性名称和值对:It must include one or more records with the property name and value pairs in this format:

[
    {
        "property 1": "value1",
        "property 2": "value2",
        "property 3": "value3",
        "property 4": "value4"
    }
]

可以使用以下格式在单个请求中一同批处理多个记录。You can batch multiple records together in a single request by using the following format. 所有记录必须都为相同的记录类型。All the records must be the same record type.

[
    {
        "property 1": "value1",
        "property 2": "value2",
        "property 3": "value3",
        "property 4": "value4"
    },
    {
        "property 1": "value1",
        "property 2": "value2",
        "property 3": "value3",
        "property 4": "value4"
    }
]

记录类型和属性Record type and properties

在通过 Azure Monitor HTTP 数据收集器 API 提交数据时定义自定义的记录类型。You define a custom record type when you submit data through the Azure Monitor HTTP Data Collector API. 目前,无法将数据写入已由其他数据类型和解决方案创建的现有记录类型。Currently, you can't write data to existing record types that were created by other data types and solutions. Azure Monitor 读取传入的数据,并创建与输入值的数据类型匹配的属性。Azure Monitor reads the incoming data and then creates properties that match the data types of the values that you enter.

发送到数据收集器 API 的每个请求必须包括 Log-Type 标头以及记录类型的名称。Each request to the Data Collector API must include a Log-Type header with the name for the record type. 后缀 _CL 会自动附加到所输入的名称作为自定义日志,以将其与其他日志类型区分开来。The suffix _CL is automatically appended to the name you enter to distinguish it from other log types as a custom log. 例如,如果输入名称 MyNewRecordType,则 Azure Monitor 将创建类型为 MyNewRecordType_CL 的记录。For example, if you enter the name MyNewRecordType, Azure Monitor creates a record with the type MyNewRecordType_CL. 这会有助于确保用户创建的类型名称与当前或未来的 Azure 解决方案中提供的名称之间不存在任何冲突。This helps ensure that there are no conflicts between user-created type names and those shipped in current or future Azure solutions.

为了识别属性的数据类型,Azure Monitor 将为属性名称添加后缀。To identify a property's data type, Azure Monitor adds a suffix to the property name. 如果某个属性包含 null 值,该属性将不包括在该记录中。If a property contains a null value, the property is not included in that record. 下表列出了属性数据类型及相应的后缀:This table lists the property data type and corresponding suffix:

属性数据类型Property data type 后缀Suffix
StringString _s_s
布尔Boolean _b_b
DoubleDouble _d_d
日期/时间Date/time _t_t
GUIDGUID _g_g

Azure Monitor 对每个属性所使用的数据类型取决于新记录的记录类型是否已存在。The data type that Azure Monitor uses for each property depends on whether the record type for the new record already exists.

  • 如果记录类型不存在,Azure Monitor 将创建新的记录类型,并使用 JSON 类型推理来确定新记录的每个属性的数据类型。If the record type does not exist, Azure Monitor creates a new one using the JSON type inference to determine the data type for each property for the new record.
  • 如果记录类型确实存在,Azure Monitor 将尝试基于现有属性创建新记录。If the record type does exist, Azure Monitor attempts to create a new record based on existing properties. 如果新记录中的属性数据类型不匹配并且无法转换为现有类型,或者如果记录中包含的属性不存在,Azure Monitor 将创建一个具有相关后缀的新属性。If the data type for a property in the new record doesn’t match and can’t be converted to the existing type, or if the record includes a property that doesn’t exist, Azure Monitor creates a new property that has the relevant suffix.

例如,此提交条目将创建具有以下三个属性的记录:number_dboolean_bstring_sFor example, this submission entry would create a record with three properties, number_d, boolean_b, and string_s:

示例记录 1

如果提交了下面的条目,并且所有值都采用字符串格式,则这些属性将不会更改。If you then submitted this next entry, with all values formatted as strings, the properties would not change. 这些值都可以转换为现有数据类型:These values can be converted to existing data types:

示例记录 2

但是,如果提交了下面的内容,Azure Monitor 会创建新属性 boolean_dstring_dBut, if you then made this next submission, Azure Monitor would create the new properties boolean_d and string_d. 这些值不能转换:These values can't be converted:

示例记录 3

如果提交了后续条目,在记录类型创建前,Azure Monitor 将创建具有以下三个属性的记录:number_sboolean_sstring_sIf you then submitted the following entry, before the record type was created, Azure Monitor would create a record with three properties, number_s, boolean_s, and string_s. 在此条目中,每个初始值都采用字符串的格式:In this entry, each of the initial values is formatted as a string:

示例记录 4

保留的属性Reserved properties

以下属性为保留属性,不应在自定义记录类型中使用。The following properties are reserved and should not be used in a custom record type. 如果有效负载中包含这些属性名称中的任何一个,则会收到错误。You will receive an error if your payload includes any of these property names.

  • tenanttenant

数据限制Data limits

发布到 Azure Monitor 数据收集 API 的数据有一些限制。There are some constraints around the data posted to the Azure Monitor Data collection API.

  • 每次发布到 Azure Monitor 数据收集器 API 的数据最大为 30 MB。Maximum of 30 MB per post to Azure Monitor Data Collector API. 这是对单次发布的大小限制。This is a size limit for a single post. 如果单次发布的数据超过 30 MB,应将数据拆分为较小的区块,并同时发送它们。If the data from a single post that exceeds 30 MB, you should split the data up to smaller sized chunks and send them concurrently.
  • 字段值最大为 32 KB。Maximum of 32 KB limit for field values. 如果字段值大于 32 KB,数据将截断。If the field value is greater than 32 KB, the data will be truncated.
  • 给定类型的推荐最大字段数是 50 个。Recommended maximum number of fields for a given type is 50. 这是从可用性和搜索体验角度考虑的现实限制。This is a practical limit from a usability and search experience perspective.
  • Log Analytics 工作区中的表最多仅支持 500 个列(在本文中称为字段)。A table in a Log Analytics workspace only supports up to 500 columns (referred to as a field in this article).
  • 列名称的最大字符数为 500。The maximum number of characters for the column name is 500.

返回代码Return codes

HTTP 状态代码 200 表示已接收请求以便进行处理。The HTTP status code 200 means that the request has been received for processing. 这表示操作已成功完成。This indicates that the operation completed successfully.

此表列出了服务可能返回的完整状态代码集:This table lists the complete set of status codes that the service might return:

代码Code 状态Status 错误代码Error code 说明Description
200200 OKOK 已成功接受请求。The request was successfully accepted.
400400 错误的请求Bad request InactiveCustomerInactiveCustomer 工作区已关闭。The workspace has been closed.
400400 错误的请求Bad request InvalidApiVersionInvalidApiVersion 服务无法识别所指定的 API 版本。The API version that you specified was not recognized by the service.
400400 错误的请求Bad request InvalidCustomerIdInvalidCustomerId 指定的工作区 ID 无效。The workspace ID specified is invalid.
400400 错误的请求Bad request InvalidDataFormatInvalidDataFormat 已提交无效的 JSON。Invalid JSON was submitted. 响应正文可能包含有关如何解决该错误的详细信息。The response body might contain more information about how to resolve the error.
400400 错误的请求Bad request InvalidLogTypeInvalidLogType 所指定日志类型包含特殊字符或数字。The log type specified contained special characters or numerics.
400400 错误的请求Bad request MissingApiVersionMissingApiVersion 未指定 API 版本。The API version wasn’t specified.
400400 错误的请求Bad request MissingContentTypeMissingContentType 未指定内容类型。The content type wasn’t specified.
400400 错误的请求Bad request MissingLogTypeMissingLogType 未指定所需的值日志类型。The required value log type wasn’t specified.
400400 错误的请求Bad request UnsupportedContentTypeUnsupportedContentType 内容类型未设为“application/json”。The content type was not set to application/json.
403403 禁止Forbidden InvalidAuthorizationInvalidAuthorization 服务未能对请求进行身份验证。The service failed to authenticate the request. 验证工作区 ID 和连接密钥是否有效。Verify that the workspace ID and connection key are valid.
404404 未找到Not Found 提供的 URL 不正确,或请求太大。Either the URL provided is incorrect, or the request is too large.
429429 请求过多Too Many Requests 服务遇到来自帐户的大量数据。The service is experiencing a high volume of data from your account. 请稍后重试请求。Please retry the request later.
500500 内部服务器错误Internal Server Error UnspecifiedErrorUnspecifiedError 服务遇到内部错误。The service encountered an internal error. 请重试请求。Please retry the request.
503503 服务不可用Service Unavailable ServiceUnavailableServiceUnavailable 服务当前不可用,无法接收请求。The service currently is unavailable to receive requests. 请重试请求。Please retry your request.

查询数据Query data

若要查询由 Azure Monitor HTTP 数据收集器 API 提交的数据,请搜索以下记录:Type 等于指定的 LogType 值并且附加 _CLTo query data submitted by the Azure Monitor HTTP Data Collector API, search for records with Type that is equal to the LogType value that you specified, appended with _CL. 例如,如果使用了 MyCustomLog,则返回具有 MyCustomLog_CL 的所有记录。For example, if you used MyCustomLog, then you'd return all records with MyCustomLog_CL.

示例请求Sample requests

在接下来的部分中,将找到如何使用不同的编程语言将数据提交到 Azure Monitor HTTP 数据收集器 API 的示例。In the next sections, you'll find samples of how to submit data to the Azure Monitor HTTP Data Collector API by using different programming languages.

对于每个示例,执行以下步骤来设置授权标头的变量:For each sample, do these steps to set the variables for the authorization header:

  1. 在 Azure 门户中,找到 Log Analytics 工作区。In the Azure portal, locate your Log Analytics workspace.
  2. 依次选择“高级设置”和“已连接的源”。Select Advanced Settings and then Connected Sources.
  3. Workspace ID 的右侧,选择复制图标,并粘贴该 ID 作为 Customer ID 变量的值。To the right of Workspace ID, select the copy icon, and then paste the ID as the value of the Customer ID variable.
  4. Primary Key 的右侧,选择复制图标,并粘贴该 ID 作为 Shared Key 变量的值。To the right of Primary Key, select the copy icon, and then paste the ID as the value of the Shared Key variable.

或者,可以针对日志类型和 JSON 数据更改变量。Alternatively, you can change the variables for the log type and JSON data.

PowerShell 示例PowerShell sample

# Replace with your Workspace ID
$CustomerId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  

# Replace with your Primary Key
$SharedKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Specify the name of the record type that you'll be creating
$LogType = "MyRecordType"

# You can use an optional field to specify the timestamp from the data. If the time field is not specified, Azure Monitor assumes the time is the message ingestion time
$TimeStampField = ""


# Create two records with the same set of properties to create
$json = @"
[{  "StringValue": "MyString1",
    "NumberValue": 42,
    "BooleanValue": true,
    "DateValue": "2016-05-12T20:00:00.625Z",
    "GUIDValue": "9909ED01-A74C-4874-8ABF-D2678E3AE23D"
},
{   "StringValue": "MyString2",
    "NumberValue": 43,
    "BooleanValue": false,
    "DateValue": "2016-05-12T20:00:00.625Z",
    "GUIDValue": "8809ED01-A74C-4874-8ABF-D2678E3AE23D"
}]
"@

# Create the function to create the authorization signature
Function Build-Signature ($customerId, $sharedKey, $date, $contentLength, $method, $contentType, $resource)
{
    $xHeaders = "x-ms-date:" + $date
    $stringToHash = $method + "`n" + $contentLength + "`n" + $contentType + "`n" + $xHeaders + "`n" + $resource

    $bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
    $keyBytes = [Convert]::FromBase64String($sharedKey)

    $sha256 = New-Object System.Security.Cryptography.HMACSHA256
    $sha256.Key = $keyBytes
    $calculatedHash = $sha256.ComputeHash($bytesToHash)
    $encodedHash = [Convert]::ToBase64String($calculatedHash)
    $authorization = 'SharedKey {0}:{1}' -f $customerId,$encodedHash
    return $authorization
}


# Create the function to create and post the request
Function Post-LogAnalyticsData($customerId, $sharedKey, $body, $logType)
{
    $method = "POST"
    $contentType = "application/json"
    $resource = "/api/logs"
    $rfc1123date = [DateTime]::UtcNow.ToString("r")
    $contentLength = $body.Length
    $signature = Build-Signature `
        -customerId $customerId `
        -sharedKey $sharedKey `
        -date $rfc1123date `
        -contentLength $contentLength `
        -method $method `
        -contentType $contentType `
        -resource $resource
    $uri = "https://" + $customerId + ".ods.opinsights.azure.cn" + $resource + "?api-version=2016-04-01"

    $headers = @{
        "Authorization" = $signature;
        "Log-Type" = $logType;
        "x-ms-date" = $rfc1123date;
        "time-generated-field" = $TimeStampField;
    }

    $response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -Body $body -UseBasicParsing
    return $response.StatusCode

}

# Submit the data to the API endpoint
Post-LogAnalyticsData -customerId $customerId -sharedKey $sharedKey -body ([System.Text.Encoding]::UTF8.GetBytes($json)) -logType $logType  

C# 示例C# sample

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace OIAPIExample
{
    class ApiExample
    {
        // An example JSON object, with key/value pairs
        static string json = @"[{""DemoField1"":""DemoValue1"",""DemoField2"":""DemoValue2""},{""DemoField3"":""DemoValue3"",""DemoField4"":""DemoValue4""}]";

        // Update customerId to your Log Analytics workspace ID
        static string customerId = "xxxxxxxx-xxx-xxx-xxx-xxxxxxxxxxxx";

        // For sharedKey, use either the primary or the secondary Connected Sources client authentication key   
        static string sharedKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

        // LogName is name of the event type that is being submitted to Azure Monitor
        static string LogName = "DemoExample";

        // You can use an optional field to specify the timestamp from the data. If the time field is not specified, Azure Monitor assumes the time is the message ingestion time
        static string TimeStampField = "";

        static void Main()
        {
            // Create a hash for the API signature
            var datestring = DateTime.UtcNow.ToString("r");
            var jsonBytes = Encoding.UTF8.GetBytes(json);
            string stringToHash = "POST\n" + jsonBytes.Length + "\napplication/json\n" + "x-ms-date:" + datestring + "\n/api/logs";
            string hashedString = BuildSignature(stringToHash, sharedKey);
            string signature = "SharedKey " + customerId + ":" + hashedString;

            PostData(signature, datestring, json);
        }

        // Build the API signature
        public static string BuildSignature(string message, string secret)
        {
            var encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = Convert.FromBase64String(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hash = hmacsha256.ComputeHash(messageBytes);
                return Convert.ToBase64String(hash);
            }
        }

        // Send a request to the POST API endpoint
        public static void PostData(string signature, string date, string json)
        {
            try
            {
                string url = "https://" + customerId + ".ods.opinsights.azure.cn/api/logs?api-version=2016-04-01";

                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Log-Type", LogName);
                client.DefaultRequestHeaders.Add("Authorization", signature);
                client.DefaultRequestHeaders.Add("x-ms-date", date);
                client.DefaultRequestHeaders.Add("time-generated-field", TimeStampField);

                System.Net.Http.HttpContent httpContent = new StringContent(json, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                Task<System.Net.Http.HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent);

                System.Net.Http.HttpContent responseContent = response.Result.Content;
                string result = responseContent.ReadAsStringAsync().Result;
                Console.WriteLine("Return Result: " + result);
            }
            catch (Exception excep)
            {
                Console.WriteLine("API Post Exception: " + excep.Message);
            }
        }
    }
}

Python 2 示例Python 2 sample

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

# Update the customer ID to your Log Analytics workspace ID
customer_id = 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'

# For the shared key, use either the primary or the secondary Connected Sources client authentication key   
shared_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# The log type is the name of the event that is being submitted
log_type = 'WebMonitorTest'

# An example JSON web monitor object
json_data = [{
   "slot_ID": 12345,
    "ID": "5cdad72f-c848-4df0-8aaa-ffe033e75d57",
    "availability_Value": 100,
    "performance_Value": 6.954,
    "measurement_Name": "last_one_hour",
    "duration": 3600,
    "warning_Threshold": 0,
    "critical_Threshold": 0,
    "IsActive": "true"
},
{   
    "slot_ID": 67890,
    "ID": "b6bee458-fb65-492e-996d-61c4d7fbb942",
    "availability_Value": 100,
    "performance_Value": 3.379,
    "measurement_Name": "last_one_hour",
    "duration": 3600,
    "warning_Threshold": 0,
    "critical_Threshold": 0,
    "IsActive": "false"
}]
body = json.dumps(json_data)

#####################
######Functions######  
#####################

# Build the API signature
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).encode('utf-8')  
    decoded_key = base64.b64decode(shared_key)
    encoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_hash, digestmod=hashlib.sha256).digest())
    authorization = "SharedKey {}:{}".format(customer_id,encoded_hash)
    return authorization

# Build and send a request to the POST API
def post_data(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.cn' + 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 'Accepted'
    else:
        print "Response code: {}".format(response.status_code)

post_data(customer_id, shared_key, body, log_type)

替代方法和注意事项Alternatives and considerations

虽然数据收集器 API 应该满足你将自由格式数据收集到 Azure 日志中的大部分需求,但有时候也可能需要替代方法来克服此 API 的某些限制。While the Data Collector API should cover most of your needs to collect free-form data into Azure Logs, there are instances where an alternative might be required to overcome some of the limitations of the API. 所有选项如下所示,包括了主要的考虑事项:All your options are as follows, major considerations included:

替代方法Alternative 说明Description 最适用于Best suited for
自定义事件:Application Insights 中的基于本机 SDK 的引入Custom events: Native SDK-based ingestion in Application Insights Application Insights 通常通过应用程序中的 SDK 进行检测,提供通过“自定义事件”发送自定义数据的功能。Application Insights, typically instrumented through an SDK within your application, offers the ability for you to send custom data through Custom Events.
  • 在应用程序中生成但不由 SDK 通过默认数据类型(即请求、依赖项、异常等)之一选取的数据。Data that is generated within your application, but not picked up by SDK through one of the default data types (ie: requests, dependencies, exceptions, etc).
  • 与 Application Insights 中的其他应用程序数据最常关联的数据Data that is most often correlated to other application data in Application Insights
Azure Monitor Logs 中的数据收集器 APIData Collector API in Azure Monitor Logs Azure Monitor Logs 中的数据收集器 API 是一种用于引入数据的完全开放式方法。The Data Collector API in Azure Monitor Logs is a completely open-ended way to ingest data. 采用 JSON 对象格式的任何数据均可发送到此处。Any data formatted in a JSON object can be sent here. 在发送后,这些数据将被处理,并在 Logs 中可用来与 Logs 中的其他数据关联,或与其他 Application Insights 数据进行对比。Once sent, it will be processed, and available in Logs to be correlated with other data in Logs or against other Application Insights data.

将数据作为文件上传到 Azure Blob 相当容易,这些文件将在这里被处理并上传到 Log Analytics。It is fairly easy to upload the data as files to an Azure Blob blob, from where these files will be processed and uploaded to Log Analytics. 请参阅本文,了解此类管道的示例实现。Please see this article for a sample implementation of such a pipeline.
  • 不一定是在使用 Application Insights 检测的应用程序中生成的数据。Data that is not necessarily generated within an application instrumented within Application Insights.
  • 示例包括查找和事实数据表、参考数据、预先聚合的统计信息等。Examples include lookup and fact tables, reference data, pre-aggregated statistics, etc.
  • 适用于要针对其他 Azure Monitor 数据(例如,Application Insights、其他 Logs 数据类型、安全中心、适用于容器/VM 的 Azure Monitor 等)进行交叉引用的数据。Intended for data that will be cross-referenced against other Azure Monitor data (for example, Application Insights, other Logs data types, Security Center, Azure Monitor for Containers/VMs, etc).
Azure 数据资源管理器Azure Data Explorer Azure 数据资源管理器 (ADX) 是为 Application Insights Analytics 和 Azure Monitor Logs 提供强大支持的数据平台。Azure Data Explorer (ADX) is the data platform that powers Application Insights Analytics and Azure Monitor Logs. 目前,正式版(“GA”)使用原始形式的数据平台,让你可以十分灵活地对群集(RBAC、保有率、架构等)执行各项操作(但需要管理开销)。Now Generally Availabile ("GA"), using the data platform in its raw form provides you complete flexibility (but requiring the overhead of management) over the cluster (RBAC, retention rate, schema, etc). ADX 提供了很多引入选项,其中包括 CSV、TSV 和 JSON 文件。ADX provides many ingestion options including CSV, TSV, and JSON files.
  • 与 Application Insights 或 Logs 下的任何其他数据无关联的数据。Data that will not be correlated to any other data under Application Insights or Logs.
  • 需要 Azure Monitor Logs 中目前未提供的高级引入或处理功能的数据。Data requiring advanced ingestion or processing capabilities not today available in Azure Monitor Logs.

后续步骤Next steps