ASP.NET Core Web API:如何使用Microsoft.Extensions.Logging.AzureAppServices将日志发送到Blob存储

5w9g7ksd  于 2023-06-24  发布在  .NET
关注(0)|答案(1)|浏览(142)

我有一个ASP.NET Core 6.0 Web API。我的API托管在Azure上。我正在尝试使用Microsoft.Extensions.Logging.AzureAppServices配置日志记录到blob。
我已经遵循了许多教程,但无论我做什么,日志记录都不会显示在azure blob上。
我在搜索时发现了这个:https://github.com/dotnet/aspnetcore/issues/28486
然而,我发现很多人在youtube和教程是没有这个问题。
我还尝试使用GUI Visual Studio连接到Blob容器,它添加了以下代码行:

builder.Services.AddAzureClients(clientBuilder =>
{
    clientBuilder.AddBlobServiceClient(builder.Configuration["MyConnection:blob"], preferMsi: false);
    clientBuilder.AddQueueServiceClient(builder.Configuration["MyConnection:queue"], preferMsi: false);
});

我尝试在appsettings.json中添加连接,但也不起作用。
我不确定是我做错了什么,还是这真的坏了。我会很感激任何帮助或更好的想法日志。

jrcvhitl

jrcvhitl1#

我面临着类似的问题,所以作为替代,你可以使用下面的过程:
首先创建一个Asp.Net Core Web Api,下面是代码行:

Controller.cs:

using Microsoft.AspNetCore.Mvc;

namespace WebApplication8.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            _logger.LogInformation("Secret Rithwik");
            _logger.LogDebug("Debug message in Get Rithwik");
            _logger.LogWarning("Warning Message Rithwik");
            _logger.LogError("Error message in Get Rithwik");
            _logger.LogCritical("Critical Rithwik");

            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();

            
        }
    }
}

csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="7.0.7" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>

</Project>

Program.cs:

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton(typeof(ITelemetryChannel), new ServerTelemetryChannel());
builder.Services.AddApplicationInsightsTelemetry();
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

appsettings.json:

{
  "Logging": {
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Debug",
        "Microsoft": "Error"
      }
    },
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=1f694869-7-7e6ac60e1b58;IngestionEndpoint=https://centralindia-0.in.applicationinsights.azure.com/;LiveEndpoint=https://centralindia.livediagnostics.monitor.azure.com/"
  }
}

Now in Application Insights:

现在,我已经使用诊断设置将这些日志发送到存储帐户,如下所示:

然后:

Now after some time check the logs in storage account:

在这里,我首先将日志发送到应用程序洞察,然后发送到存储帐户。

相关问题