我想在应用服务诊断 blob 中记录 nlog 生成的应用程序日志 [即应用程序日志记录 (Blob) ] 但只打印默认日志,而不是基于 nlog 的自定义日志 但是当文件目标添加到 nlog.config 时,我可以打印应用程序日志记录(文件系统)。问题仅在于 blob。
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"
throwConfigExceptions="true"
internalLogLevel="info"
internalLogFile="d:\home\LogFiles\temp\internal-nlog-AspNetCore3.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<target xsi:type="Trace" name="String" layout="${level}\: ${logger}[0]${newline} |trace| ${message}${exception:format=tostring}" />
<target xsi:type="Console" name="lifetimeConsole" layout="${level}\: ${logger}[0]${newline} |console| ${message}${exception:format=tostring}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="lifetimeConsole,String" final="true"/>
</rules>
</nlog>
program.cs 文件
namespace testapp
{
public class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
logging.AddConsole();
logging.AddDebug();
logging.AddAzureWebAppDiagnostics();
})
.UseNLog() // NLog: Setup NLog for Dependency injection
.ConfigureServices(serviceCollection => serviceCollection
.Configure<AzureBlobLoggerOptions>(options =>
{
options.BlobName = "testlog.txt";
}))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
基于 Nlog 的日志不会记录在应用服务诊断 blob 中,而是仅打印默认日志。 请帮助解决此问题。
答案 0 :(得分:0)
似乎 System.Diagnostics.Trace-Target 最适用于 ASP.NET 应用程序,而不适用于 Azure 中的 ASP.NetCore 应用程序。
使用 AddAzureWebAppDiagnostics
时,它将所有写入 Microsoft ILogger 的输出重定向到 FileSystem 或 Blob。但是任何写入纯 NLog Logger 对象的输出都不会被重定向。
也许解决方案是设置一个写入 HOME 目录的 NLog FileTarget:
<nlog>
<targets async="true">
<!-- Environment Variable %HOME% matches D:/Home -->
<target type="file" name="appfile" filename="${environment:HOME:cached=true}/logfiles/application/app-${shortdate}-${processid}.txt" />
</targets>
<rules>
<logger name="*" minLevel="Debug" writeTo="appFile" />
</rules>
</nlog>
另见:https://docs.microsoft.com/en-us/azure/app-service/troubleshoot-diagnostic-logs#stream-logs
要包含 Blob 输出,请查看 NLog.Extensions.AzureBlobStorage
Blob-output 的替代品可能是 ApplicationInsights,但可能有不同的定价。