[英]log4net doesn't log in Windows Event Viewer
我想使用 log4net 登錄 Windows 事件查看器。
我創建了一個控制台應用程序(.NET Framework 4),我添加了參考 log4net.dll,我將以下代碼放在我的 App.config 中:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="EventLogAppender"/>
</root>
</log4net>
<startup><supportedRuntime version="v2.0.50727"/></startup>
</configuration>
我輸入了以下代碼:
class Program
{
static void Main(string[] args)
{
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error("test error", new Exception("error's exception", new Exception("error's innerexception")));
Console.Read();
}
}
它沒有記錄,沒有任何反應,為什么?
謝謝
您需要調用configure 。
改變:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", Watch = true)]
至
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
當您指定ConfigFile = "App.config"
時,它會查找 App.config 但您的文件名將是[FileName].Config
。
您需要從 log4net 庫中調用XmlConfigurator.Configure來對其進行初始化。 (見下文)
class Program
{
static void Main(string[] args)
{
// you need this
XmlConfigurator.Configure();
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error("test error", new Exception("error's exception", new Exception("error's innerexception")));
Console.Read();
}
}
在您的應用程序開始時調用 XmlConfigurator.Configure()。
您還需要授予運行應用程序的用戶將數據放入事件日志的權限。
一個很好的方法是使用 powershell,管理員模式
New-EventLog EventLogName -source ApplicationName
另外,將這兩個參數添加到附加程序中
<param name="LogName" value="EventLogName " />
<param name="ApplicationName" value="ApplicationName" />
問候,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.