c# - Asp .net core webapi 记录到 Dev 中的文件,一旦部署在 azure 中就写入应用程序洞察

标签 c# azure asp.net-core asp.net-web-api

我正在使用 .net7 和 asp.net core 创建一个新的 WebApi 我之前使用过 NLog 并且知道如何设置日志记录,但由于我正在部署到 azure 并将使用 Application Insights 在那里进行日志记录,但我不知道不想在 DEV 中使用它。

它如何配置我的应用程序,以便在部署后记录到 dev 和 APPI 中的文件?

最佳答案

检查以下步骤,以便在开发环境中访问应用程序时将跟踪记录到文本文件,并在部署到 Azure 应用服务时将跟踪记录到 Application Insights。

感谢 @Jignesh Trivedi 提供的 nlog.config 文件。

配置将日志发送到文本文件。

  • 安装 NuGet 包 NLog.Web.AspNetCore
  • 创建一个新的配置文件并将其命名为 nlog.config。在该文件中添加以下设置。
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="info"
      internalLogFile="C:\Users\YourPath\NLogs\internallog.txt">
  <extensions>
    <add assembly="NLog.Web.AspNetCore" />
  </extensions>
  <targets>
    <target name="logfile" xsi:type="File"
            fileName="C:\Users\YourPath\NLogs\internallog.txt"
            layout="${longdate} ${level:uppercase=true} ${message}"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" writeTo="logfile" />
    <logger name="*" minlevel="Trace" writeTo="alldata" />
    <logger name="Microsoft.*" maxLevel="Info" final="true" />
    <loggername name="*" minlevel="Trace" writeTo="otherFile-web" />
  </rules>
</nlog>
  • Program.cs 文件中,添加以下代码行。
using NLog.Web;

var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();

builder.Logging.ClearProviders();
builder.Host.UseNLog();

WeatherForecastController.cs中,添加日志

[HttpGet(Name = "GetWeatherForecast")]
 public IEnumerable<WeatherForecast> Get()
 {
     _logger.LogInformation("Log Information from Weatherforecast.");
     _logger.LogDebug("Debug Message from the Controller Action.");
     _logger.LogWarning("Iam Log Warning.");
     _logger.LogError("Hello, this is Log Error.");

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

当我在本地运行应用程序并执行 GET 方法时,会在我在 nlog.config 中提到的路径中创建一个新的文本文件 - internalLogFiletarget 路径。

本地输出: enter image description here

配置 Application Insights 日志记录

  • 在 Azure 门户中创建 Application Insights,复制连接字符串并将其粘贴到 appsetting.json 文件中。
{
  "Logging": {
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Debug",
        "Microsoft": "Error"
      }
    },
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
  "ConnectionString": "Connection String from Application Insights"
  }
}

右键单击解决方案资源管理器 => 添加 Application Insights 遥测 => Azure Application Insights

  • Program.cs 文件中添加以下代码。
builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]);

我的 Program.cs 文件

using NLog;
using NLog.Web;

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

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var isDevelopment = environment == Environments.Development;
var logger =(dynamic) null;

#region DevLog
if (isDevelopment)
{
    logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
    #endregion
}

try
{
    var builder = WebApplication.CreateBuilder(args);


    #region ApplicationInsights
    if (!isDevelopment)
    {
        builder.Services.AddSingleton(typeof(ITelemetryChannel), new ServerTelemetryChannel());
        builder.Services.AddApplicationInsightsTelemetry();     
    }
    else
    {
        builder.Logging.ClearProviders();
        builder.Host.UseNLog();
    }
    #endregion

    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();  

    var app = builder.Build();

    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
}
catch (Exception ex)
{
    logger.Error(ex, "Error in init");
    throw;
}
finally
{
    NLog.LogManager.Shutdown();
}

.csproj 文件

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

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <ApplicationInsightsResourceId>/subscriptions/****/resourceGroups/****/providers/microsoft.insights/components/11-40vscode</ApplicationInsightsResourceId>
    <UserSecretsId>****</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.Profiler.AspNetCore" Version="2.4.0" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="5.1.5" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>

将应用部署到 Azure 并启用 Application Insights

enter image description here

  • 运行应用程序并在 Application Insights 中检查交易搜索日志

enter image description here

enter image description here

引用资料取自MSDoc

关于c# - Asp .net core webapi 记录到 Dev 中的文件,一旦部署在 azure 中就写入应用程序洞察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74391499/

相关文章:

c# - Simple Injector 条件注入(inject)

c# - Azure 计划 Web 作业设置

c# - EF 核心字符串区分大小写不起作用

c# - 通过API下载soundcloud数据

c# - 使用枚举查找文件夹中的所有文件

c# - ASP MVC 模型列表 <object> 在 POST 操作中返回空

asp.net-web-api - 从 .NET Core 2.0 Web API 中完全删除控制台日志记录

azure - 调用/ token 端点没有给我 access_token

git - 在 Azure 中,如何在不同的服务器中克隆使用 git-lfs 存储库的存储库?

c# - .Net Core 3.1 将额外的 config.json 文件添加到 Startup 中的配置参数