能否通过NLog写入Azure Log Analytics自定义表?.NET 6技术咨询
.NET 6 Web API 写入Azure Log Analytics自定义表的NuGet方案
下面是两种基于workspaceId和sharedKey实现日志写入的可行方案,都是成熟的NuGet包:
1. 官方Azure SDK包:Azure.Monitor.Ingestion
这是微软官方提供的日志摄入SDK,适合需要精细控制日志写入流程的场景。
安装包:
dotnet add package Azure.Monitor.Ingestion配置与使用示例:
首先在Program.cs中注入LogIngestionClient:var builder = WebApplication.CreateBuilder(args); builder.Services.AddAzureClients(clientBuilder => { var workspaceId = builder.Configuration["AzureLogAnalytics:WorkspaceId"]; clientBuilder.AddLogIngestionClient(new Uri($"https://{workspaceId}.ods.opinsights.azure.com")) .WithCredential(new AzureKeyCredential(builder.Configuration["AzureLogAnalytics:SharedKey"])); });在控制器中注入客户端并写入自定义日志:
[ApiController] [Route("[controller]")] public class CustomLogController : ControllerBase { private readonly LogIngestionClient _logIngestionClient; private readonly IConfiguration _config; public CustomLogController(LogIngestionClient logIngestionClient, IConfiguration config) { _logIngestionClient = logIngestionClient; _config = config; } [HttpPost("write")] public async Task<IActionResult> WriteCustomLog() { // 构造符合自定义表字段的日志对象 var logEntries = new List<object> { new { EventType = "UserAction", UserId = "12345", Action = "Login", Timestamp = DateTimeOffset.UtcNow, IpAddress = HttpContext.Connection.RemoteIpAddress?.ToString() } }; // 上传到自定义表(需提前创建数据收集规则DCR,关联目标表) await _logIngestionClient.UploadAsync( workspaceId: _config["AzureLogAnalytics:WorkspaceId"], ruleId: "dcr-xxxxxxxxxxxx", // 替换为你的DCR ID streamName: "Custom-MyCustomTable_CL", // 替换为DCR中定义的流名称 logs: logEntries); return Ok("日志写入成功"); } }注意:使用该包需要先在Azure门户创建数据收集规则(DCR),将自定义表与DCR关联,并确保日志结构与表字段匹配。
2. Serilog日志框架集成:Serilog.Sinks.AzureAnalytics
如果你的项目已经使用Serilog作为日志框架,这个Sink可以快速实现日志写入自定义表,无需额外的客户端配置。
安装包:
dotnet add package Serilog.Sinks.AzureAnalytics配置与使用示例:
在Program.cs中配置Serilog:var builder = WebApplication.CreateBuilder(args); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(builder.Configuration) .WriteTo.AzureAnalytics( workspaceId: builder.Configuration["AzureLogAnalytics:WorkspaceId"], authenticationId: builder.Configuration["AzureLogAnalytics:SharedKey"], logName: "MyCustomTable_CL") // 自定义表名,必须以_CL结尾 .CreateLogger(); builder.Host.UseSerilog();在代码中直接写入日志:
[ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { // 直接写入自定义表 _logger.LogInformation("用户请求了天气数据,请求ID: {RequestId}", HttpContext.TraceIdentifier); // 业务逻辑... return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }
通用注意事项
- 自定义表名称必须以
_CL结尾,这是Azure Log Analytics自定义表的强制命名规则 - SharedKey可从Azure Log Analytics工作区的代理管理 -> 主密钥/辅助密钥中获取
- 使用Azure.Monitor.Ingestion时,DCR的流名称必须与上传时指定的
streamName一致,否则日志无法正确写入目标表
内容的提问来源于stack exchange,提问作者Mustafa
相关产品推荐
相关产品推荐

