如何让 Log4Net 在控制台应用程序中写入 EventLog?

How to get Log4Net to write to EventLog in Console Application?

我正在编写控制台应用程序并希望将日志消息发送到 Windows 事件日志(在我的 Windows 10 笔记本电脑上)。我似乎无法将消息发送到事件日志。但是,我能够让 log4net 将文本文件写入控制台。这是我的 app.config 文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
  </configSections>

  <log4net>

    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
      <param name="File" value="game-playtest-log-file.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>

    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
      <param name="LogName" value="GamePlayTestLog" />
      <param name="ApplicationName" value="GamePlayTest" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>

    <appender name="colored-console" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="INFO" />
        <foreColor value="White, HighIntensity" />
        <backColor value="Green" />
      </mapping>
      <mapping>
        <level value="DEBUG" />
        <foreColor value="White, HighIntensity" />
        <backColor value="Blue" />
      </mapping>
      <mapping>
        <level value="WARN" />
        <foreColor value="Yellow, HighIntensity" />
        <backColor value="Purple" />
      </mapping>
      <mapping>
        <level value="ERROR" />
        <foreColor value="Yellow, HighIntensity" />
        <backColor value="Red" />
      </mapping>

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date --- %message%newline%newline"/>
      </layout>
    </appender>

    <root>
      <appender-ref ref="LogFileAppender"/>
      <appender-ref ref="EventLogAppender"/>
      <appender-ref ref="colored-console" />
      <priority value="DEBUG" />
      <level value="ALL"/>
    </root>

  </log4net>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

这是我正在测试的日志记录代码:

log4net.Config.XmlConfigurator.Configure();
Logger.log.Info("Launching " + options.Input);
Logger.log.Debug("TestDebugMsg");
Logger.log.Fatal("TestFatalMsg");

这是我的记录器class:

using log4net;

namespace GamePlayTest
{
    public static class Logger
    {
        public static readonly ILog log = LogManager.GetLogger(typeof(Logger));
    }
}

根据Apache FAQ,这个问题经常是因为需要以管理员身份创建日志。我通过 New-EventLog 命令手动创建了带有 GamePlayTest 源的 GamePlayTestLog。 GamePlayTestLog 出现在事件日志中,事件为零。但是,消息将转到文本文件和控制台。

我怀疑问题与来源有关,因为我不知道如何设置它。我只是希望使用 exe 名称作为源会起作用。有一些相关的网页和 S/O 文章,但都非常过时。我试过来自 here 的代码。我还尝试了 GitHub 中的示例,但没有成功。我觉得我错过了一些明显的东西。

我已经 运行 来自以管理员身份启动的 PowerShell 会话的控制台应用程序 (GamePlayTest.exe)。这是内部 log4net 日志的内容:

log4net: log4net assembly [log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=**********]. Loaded from [C:\Users\fores\git\game-playtest-tool\GamePlayTest\bin\x64\Release\log4net.dll]. (.NET Runtime [4.0.30319.42000] on Microsoft Windows NT 6.2.9200.0)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [GamePlayTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [GamePlayTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\fores\git\game-playtest-tool\GamePlayTest\bin\x64\Release\GamePlayTest.exe]
log4net: Assembly [GamePlayTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [GamePlayTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: configuring repository [log4net-default-repository] using .config file section
log4net: Application config file is [C:\Users\fores\git\game-playtest-tool\GamePlayTest\bin\x64\Release\GamePlayTest.exe.Config]
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Loading Appender [LogFileAppender] type: [log4net.Appender.RollingFileAppender]
log4net: Setting Property [File] to String value [game-playtest-log-file.txt]
log4net: Setting Property [AppendToFile] to Boolean value [True]
log4net: Setting Property [RollingStyle] to RollingMode value [Size]
log4net: Setting Property [MaxSizeRollBackups] to Int32 value [10]
log4net: Setting Property [MaximumFileSize] to String value [10MB]
log4net: Setting Property [StaticLogFileName] to Boolean value [True]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%date [%thread] %-5level %logger [%property{NDC}] - %message%newline]
log4net: Converter [date] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [thread] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [level] Option [] Format [min=5,max=2147483647,leftAlign=True]
log4net: Converter [literal] Option [ ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [logger] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [property] Option [NDC] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Searched for existing files in [C:\Users\fores\git\game-playtest-tool\GamePlayTest\bin\x64\Release]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\Users\fores\git\game-playtest-tool\GamePlayTest\bin\x64\Release\game-playtest-log-file.txt] append [True]
log4net: Created Appender [LogFileAppender]
log4net: Adding appender named [LogFileAppender] to logger [root].
log4net: Loading Appender [EventLogAppender] type: [log4net.Appender.EventLogAppender]
log4net: Setting Property [LogName] to String value [GamePlayTestLog]
log4net: Setting Property [ApplicationName] to String value [GamePlayTest]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%date [%thread] %-5level %logger [%property{NDC}] - %message%newline]
log4net: Converter [date] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [thread] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [level] Option [] Format [min=5,max=2147483647,leftAlign=True]
log4net: Converter [literal] Option [ ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [logger] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [property] Option [NDC] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Source [GamePlayTest] is registered to log []
log4net: Created Appender [EventLogAppender]
log4net: Adding appender named [EventLogAppender] to logger [root].
log4net: Loading Appender [colored-console] type: [log4net.Appender.ColoredConsoleAppender]
log4net: Setting Property [Level] to Level value [INFO]
log4net: Setting Property [ForeColor] to Colors value [White, HighIntensity]
log4net: Setting Property [BackColor] to Colors value [Green]
log4net: Setting Collection Property [AddMapping] to object [log4net.Appender.ColoredConsoleAppender+LevelColors]
log4net: Setting Property [Level] to Level value [DEBUG]
log4net: Setting Property [ForeColor] to Colors value [White, HighIntensity]
log4net: Setting Property [BackColor] to Colors value [Blue]
log4net: Setting Collection Property [AddMapping] to object [log4net.Appender.ColoredConsoleAppender+LevelColors]
log4net: Setting Property [Level] to Level value [WARN]
log4net: Setting Property [ForeColor] to Colors value [Yellow, HighIntensity]
log4net: Setting Property [BackColor] to Colors value [Purple]
log4net: Setting Collection Property [AddMapping] to object [log4net.Appender.ColoredConsoleAppender+LevelColors]
log4net: Setting Property [Level] to Level value [ERROR]
log4net: Setting Property [ForeColor] to Colors value [Yellow, HighIntensity]
log4net: Setting Property [BackColor] to Colors value [Red]
log4net: Setting Collection Property [AddMapping] to object [log4net.Appender.ColoredConsoleAppender+LevelColors]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%date --- %message%newline%newline]
log4net: Converter [date] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ --- ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Created Appender [colored-console]
log4net: Adding appender named [colored-console] to logger [root].
log4net: Logger [root] Level string is [DEBUG].
log4net: Logger [root] level set to [name="DEBUG",value=30000].
log4net: Logger [root] Level string is [ALL].
log4net: Logger [root] level set to [name="ALL",value=-2147483648].
log4net: Hierarchy Threshold []
log4net: Shutdown called on Hierarchy [log4net-default-repository]

这是日志文件中的示例行:

2016-04-13 17:27:52,098 [1] INFO  GamePlayTest.Logger - Launching C:\Program Files (x86)\Devotion\DevotionWin.exe

使用自定义事件日志时,您必须重新启动事件日志服务才能正确显示。

只有事件日志的创建需要运行具有管理员权限。使用 New-EventLog 时,请确保参数 -LogName 对应于 log4net 配置中的 'LogName' 参数,并且 -Source 参数对应于 log4net 配置中的“ApplicationName”参数。

创建日志条目时,应用程序本身不需要管理员权限即可登录到 windows 事件日志。创建事件日志后,关闭 EventViewer 并再次打开它,该条目应出现在树视图中的 Applications and Services Logs 节点下。