[英]Dynamically Set Nlog Log Level per Logger Instance ASP.Net Core 2.x
[英]Redirect all ASP.NET Core logging into a single NLog logger
我有一個ASP.NET項目,將其日志發送到NLog。
但是在這個項目中,我有自己的NLog記錄器,我想知道如何通過它路由所有日志。
我想我不應該將NLog添加為記錄器,但是我應該找到一種方法來注冊一種每次ASP嘗試記錄任何內容時都會被調用的方法。
如何做到這一點?
這是創建記錄器的代碼:
// create the module name
var ProcessName = Process.GetCurrentProcess().ProcessName;
_ModuleName = ProcessName + " (\"" + Oracle.GuessMyName() + "\")";
// create the logger configuration
var Configuration = new LoggingConfiguration();
// create the file target
var FileTarget = new FileTarget ("file")
{
FileName = @"x:\Logs\${processname}.log",
ArchiveFileName = @"x:\Logs\${processname}.{#}.log",
Layout = @"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
ArchiveEvery = FileArchivePeriod.Day,
ArchiveNumbering = ArchiveNumberingMode.Rolling,
MaxArchiveFiles = 7,
ConcurrentWrites = true
};
Configuration.AddTarget(FileTarget);
// create the viewer target
var ViewerTarget = new NLogViewerTarget ("viewer")
{
Layout = @"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
IncludeSourceInfo = true,
IncludeCallSite = true,
Address = @"udp://127.0.0.1:9999"
};
Configuration.AddTarget(ViewerTarget);
// set the rules
Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));
// set the configuration
LogManager.Configuration = Configuration;
// create a new logger
_Logger = LogManager.GetLogger(_ModuleName);
這也是ASP.net附加到nlog的方式:
LoggerFactory.AddNLog();
Application.AddNLogWeb();
現在,兩個進程的當前日志布局如下所示(每次重新啟動進程時,動物名稱都會自動更改)
所以這兩個過程:shinobi和mouserun在這里都有它們自己的日志輸出,但是與ASP相關的任何內容都將轉到ASP的名為Microsoft的nlog實例,而不管該過程如何。
目標是在shinobi記錄器中包含shinobi的ASP輸出,而在mouserun記錄器中具有mouserun的ASP輸出。
查看NLog.Extensions.Logging的代碼,在該代碼中注入自己的自定義日志提供程序。
您可以做同樣的事情,只需包裝您的global-logger對象:
public static ILoggerFactory AddNLog(this ILoggerFactory factory, NLogProviderOptions options)
{
ConfigureHiddenAssemblies();
using (var provider = new NLogLoggerProvider(options))
{
factory.AddProvider(provider);
}
return factory;
}
您還可以創建一個自定義目標,並使用NLog規則將所有非全局記錄器消息重定向到該目標:
https://github.com/nlog/NLog/wiki/Configuration-file#rules
然后,自定義目標可以將日志事件轉發到全局記錄器:
https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target
您應該謹慎使用循環日志記錄。 也許在自定義目標中有一個過濾器,以忽略來自全局記錄器的消息。
但是我認為這是一個丑陋的解決方案,而且我無法理解只有一個記錄器對象的限制。 尤其是當原因是因為它應該以應用程序命名之后。 為什么不為名稱添加一個全局變量,而不是濫用logger-name?
或者,您可以創建一個自定義目標包裝器,該包裝器將Logger固定在LogEventInfo上,因此,當轉發到包裝的目標(UDP- / File-target)時,它們似乎都來自同一記錄器。
類似於此人正在嘗試執行的操作:
https://github.com/NLog/NLog/issues/2352
還是一個非常丑陋的解決方案,僅在無法弄清楚如何在所需Nlog目標的配置中避免使用logger-name時才應使用(例如,使用其他方式配置file-target-filename)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.