你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 .NET 的 Azure Monitor 引入客户端库 - 版本 1.1.1

Azure Monitor 引入客户端库用于将自定义日志发送到 Azure Monitor

此库允许将几乎任何源中的数据发送到支持的内置表或 Log Analytics 工作区中创建的自定义表。 甚至可以使用自定义列来扩展内置表的架构。

资源:

入门

先决条件

安装包

使用 NuGet 安装适用于 .NET 的 Azure Monitor 引入客户端库:

dotnet add package Azure.Monitor.Ingestion

验证客户端

引入数据需要经过身份验证的客户端。 若要进行身份验证,请创建类的 TokenCredential 实例。 将其传递给 类的 LogsIngestionClient 构造函数。

为了进行身份验证,以下示例使用 DefaultAzureCredential 包中的 Azure.Identity

var endpoint = new Uri("<data_collection_endpoint_uri>");
var credential = new DefaultAzureCredential();
var client = new LogsIngestionClient(endpoint, credential);

为 Azure 主权云配置客户端

默认情况下, LogsIngestionClient 配置为连接到 Azure 公有云。 若要改为连接到主权云,请设置 LogsIngestionClientOptions.Audience 属性。 例如:

var endpoint = new Uri("<data_collection_endpoint_uri>");
var credential = new DefaultAzureCredential();
var clientOptions = new LogsIngestionClientOptions
{
    Audience = LogsIngestionAudience.AzureChina
};
var client = new LogsIngestionClient(endpoint, credential, clientOptions);

上传日志

有关日志引入的示例,请参阅 示例 部分。

关键概念

数据收集终结点

数据收集终结点 (DCE) 允许你唯一地配置 Azure Monitor 的引入设置。 本文 概述了 DCE,包括其内容、结构以及如何创建和使用它们。

数据收集规则

数据收集规则 (DCR) 定义 Azure Monitor 收集的数据,并指定发送或存储这些数据的方式和位置。 REST API 调用必须指定要使用的 DCR。 一个 DCE 可以支持多个 DCR,因此,可以为不同的源和目标表指定不同的 DCR。

DCR 必须了解输入数据的结构和目标表的结构。 如果这两个结构不匹配,它可以使用转换将源数据转换为与目标表匹配。 你还可使用转换来筛选源数据并执行任何其他计算或转换。

有关详细信息,请参阅 Azure Monitor 中的数据收集规则

Log Analytics 工作区表

自定义日志可以将数据发送到你创建的任何自定义表,还可以发送到 Log Analytics 工作区中的某些内置表。 目标表必须先存在,然后才能向它发送数据。 目前支持以下内置表:

线程安全

我们保证所有客户端实例方法都是线程安全的,并且相互独立, (准则) 。 此设计可确保重用客户端实例的建议始终是安全的,即使跨线程也是如此。

其他概念

客户端选项 | 访问响应 | 长时间运行的操作 | 处理失败 | 诊断 | 嘲笑 | 客户端生存期

示例

可以使用 示例熟悉不同的 API。

使用依赖项注入注册客户端

若要向 di) 容器 (依赖项注入注册 LogsIngestionClient ,请调用 AddLogsIngestionClient 方法。 有关详细信息,请参阅 注册客户端

上传自定义日志

可以使用 或 LogsIngestionClient.UploadAsync 方法上传日志LogsIngestionClient.Upload。 请注意数据引入 限制。 此方法有一个可选参数:string contentEncoding。 这指的是传入的 RequestContent 的编码。 如果要传入已操作的内容,请设置 contentEncoding 参数。 例如,如果内容已 gzipped,请将 contentEncoding 设置为“gzip”。 如果未设置此参数,则默认行为是 gzip 所有输入。

var endpoint = new Uri("<data_collection_endpoint>");
var ruleId = "<data_collection_rule_id>";
var streamName = "<stream_name>";

var credential = new DefaultAzureCredential();
LogsIngestionClient client = new(endpoint, credential);
DateTimeOffset currentTime = DateTimeOffset.UtcNow;

// Use BinaryData to serialize instances of an anonymous type into JSON
BinaryData data = BinaryData.FromObjectAsJson(
    new[] {
        new
        {
            Time = currentTime,
            Computer = "Computer1",
            AdditionalContext = new
            {
                InstanceName = "user1",
                TimeZone = "Pacific Time",
                Level = 4,
                CounterName = "AppMetric1",
                CounterValue = 15.3
            }
        },
        new
        {
            Time = currentTime,
            Computer = "Computer2",
            AdditionalContext = new
            {
                InstanceName = "user2",
                TimeZone = "Central Time",
                Level = 3,
                CounterName = "AppMetric1",
                CounterValue = 23.5
            }
        },
    });

// Upload our logs
Response response = await client.UploadAsync(
    ruleId,
    streamName,
    RequestContent.Create(data)).ConfigureAwait(false);

将自定义日志作为 IEnumerable 上传

还可以使用 LogsIngestionClient.UploadLogsIngestionClient.UploadAsync 方法上传日志,其中日志在泛型 IEnumerable 类型中传递,以及可选 LogsUploadOptions 参数。 参数 LogsUploadOptions 包括序列化程序、并发和 EventHandler。

var endpoint = new Uri("<data_collection_endpoint_uri>");
var ruleId = "<data_collection_rule_id>";
var streamName = "<stream_name>";

var credential = new DefaultAzureCredential();
LogsIngestionClient client = new(endpoint, credential);

DateTimeOffset currentTime = DateTimeOffset.UtcNow;

var entries = new List<Object>();
for (int i = 0; i < 100; i++)
{
    entries.Add(
        new {
            Time = currentTime,
            Computer = "Computer" + i.ToString(),
            AdditionalContext = i
        }
    );
}

// Upload our logs
Response response = await client.UploadAsync(ruleId, streamName, entries).ConfigureAwait(false);

使用 EventHandler 将自定义日志作为 IEnumerable 上传

可以使用 或 LogsIngestionClient.UploadAsync 方法上传日志LogsIngestionClient.Upload。 在这两种方法中,日志以泛型 IEnumerable 类型传递。 此外,还有一个 LogsUploadOptions类型参数,可在其中设置序列化程序、并发和 EventHandler。 默认序列化程序设置为 System.Text.Json,但你可以传入要使用的序列化程序。 属性 MaxConcurrency 设置将在 方法中使用的 UploadAsync 线程数。 默认值为 5,此参数在 方法中 Upload 未使用。 EventHandler 用于错误处理。 它为用户提供了在批处理失败时中止上传的选项,并访问失败的日志和相应的异常。 如果没有 EventHandler,如果上传失败, AggregateException 将引发 。

var endpoint = new Uri("<data_collection_endpoint_uri>");
var ruleId = "<data_collection_rule_id>";
var streamName = "<stream_name>";

var credential = new DefaultAzureCredential();
LogsIngestionClient client = new(endpoint, credential);

DateTimeOffset currentTime = DateTimeOffset.UtcNow;

var entries = new List<Object>();
for (int i = 0; i < 100; i++)
{
    entries.Add(
        new {
            Time = currentTime,
            Computer = "Computer" + i.ToString(),
            AdditionalContext = i
        }
    );
}
// Set concurrency and EventHandler in LogsUploadOptions
LogsUploadOptions options = new LogsUploadOptions();
options.MaxConcurrency = 10;
options.UploadFailed += Options_UploadFailed;

// Upload our logs
Response response = await client.UploadAsync(ruleId, streamName, entries, options).ConfigureAwait(false);

Task Options_UploadFailed(LogsUploadFailedEventArgs e)
{
    // Throw exception from EventHandler to stop Upload if there is a failure
    IReadOnlyList<object> failedLogs = e.FailedLogs;
    // 413 status is RequestTooLarge - don't throw here because other batches can successfully upload
    if ((e.Exception is RequestFailedException) && (((RequestFailedException)e.Exception).Status != 413))
        throw e.Exception;
    else
        return Task.CompletedTask;
}

验证日志

可以使用 Azure Monitor 查询 库验证数据是否已正确上传。 先运行 上传自定义日志 示例,然后再验证日志。

var workspaceId = "<log_analytics_workspace_id>";
var tableName = "<table_name>";

var credential = new DefaultAzureCredential();
LogsQueryClient logsQueryClient = new(credential);

LogsBatchQuery batch = new();
string query = tableName + " | Count;";
string countQueryId = batch.AddWorkspaceQuery(
    workspaceId,
    query,
    new QueryTimeRange(TimeSpan.FromDays(1)));

Response<LogsBatchQueryResultCollection> queryResponse =
    await logsQueryClient.QueryBatchAsync(batch).ConfigureAwait(false);

Console.WriteLine("Table entry count: " +
    queryResponse.Value.GetResult<int>(countQueryId).Single());

疑难解答

有关诊断各种故障方案的详细信息,请参阅 故障排除指南

后续步骤

若要详细了解 Azure Monitor,请参阅 Azure Monitor 服务文档

贡献

本项目欢迎贡献和建议。 大多数贡献要求你同意贡献者许可协议 (CLA),并声明你有权(并且确实有权)授予我们使用你的贡献的权利。 有关详细信息,请访问 https://cla.microsoft.com

提交拉取请求时,CLA 机器人将自动确定你是否需要提供 CLA,并相应地修饰 PR。 例如,标签和注释。 按照机器人提供的说明操作。 只需使用 CLA 在所有存储库中对 CLA 进行一次签名。

此项目采用了 Microsoft 开放源代码行为准则。 有关详细信息,请参阅 行为准则常见问题解答 或如有任何问题或意见,请联系 opencode@microsoft.com

曝光数