我正在使用 .net7 和 asp.net 核心創建一個新的 WebApi 我以前使用過 NLog 并且知道如何設定日志記錄,但是由于我正在部署到 azure 并且將使用 Application Insights 在那里進行日志記錄,但我不想在 DEV 中使用它。
它如何配置我的應用程式,以便在部署后登錄到 dev 和 APPI 中的檔案?
uj5u.com熱心網友回復:
檢查以下步驟以在開發環境中訪問應用程式時將跟蹤記錄到文本檔案,并在部署到 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.configinternalLogFiletarget
本地輸出:

配置到 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"
}
}
右鍵單擊solution explorer => Add Application Insights Telemetry=> 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.

- 運行應用程式并檢查
Transaction Search并Logs輸入Application Insights.


參考自MSDoc
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/532151.html
