C# windows 事件查看器

C# windows event viewer

我想使用带有 EventLogAppender 的 log4net 在 Windows 事件查看器中记录来自我的 C# 应用程序的错误(错误必须记录在应用程序日志下) 我有一个 log4net.config class 代码

<configuration>
<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />
</configSections>
  <log4net>
   <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
       <applicationName value="MySource" />
       <layout type="log4net.Layout.PatternLayout">
         <conversionPattern value="{%level} {%date} – %message%newline" />
       </layout>
    </appender>

  <root>
     <level value="DEBUG" />
     <appender-ref ref="EventLogAppender" />
  </root>
  </log4net>
</configuration>

在 AssemblyInfo 中,我添加了以下行

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch=true)]

然后在我的程序中class

class Program
{
  static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

  static void Main(string[] args)
  {
     string name=null;
     try
     {
         Console.WriteLine("Name : " + name.ToString());
     }
     catch (NullReferenceException nullException)
     {
        log.Error("Name is NULL", nullException);
     }
}
}

我不得不提一下,我使用电源 shell 创建了一个名为 "MySource"

的新事件日志

问题是我收到以下错误:

log4net:ERROR Could not create Appender [EventLogAppender] of type [log4net.Appender.EventLogAppender]. Reported error follows.
System.TypeLoadException: Could not load type 'log4net.Appender.EventLogAppender' from assembly 'log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a'.
   at System.Reflection.RuntimeAssembly.GetType(QCallAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive, ObjectHandleOnStack assemblyLoadContext)
   at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
   at log4net.Util.SystemInfo.GetTypeFromString(Assembly relativeAssembly, String typeName, Boolean throwOnError, Boolean ignoreCase)
   at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)
log4net:ERROR Appender named [EventLogAppender] not found.

最新版本的 log4net(截至今天为 2.0.8)正在实施 .net 标准 1.3:https://logging.apache.org/log4net/release/release-notes.html

在 .net 标准 1.3 中 EventLogAppender 不受支持:https://logging.apache.org/log4net/release/framework-support.html#netstandard-1.3

如果您想使用 EventLogAppender,您将不得不切换到 .net 框架。