c# - log4net 不能在 Windows 服务中工作

标签 c# logging windows-services

我有一个控制台应用程序,我正在将其转换为 Windows 服务。作为控制台应用程序,我的 log4net 日志记录工作正常。但是将其转换为 Windows 服务时,我的 log4net 日志记录已停止工作。

我已将其添加到服务项目中的 assemblyInfo.cs 中:

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

这是我的带有 onstart 和 onstop 的服务类:

private static log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private Builder _builder;

        public YCSWebServerService()
        {
            InitializeComponent();
            _builder = new Builder();
        }

        protected override void OnStart(string[] args)
        {
            _log.Info("YCSWebServerService started");
            _builder.Start();
        }

        protected override void OnStop()
        {
            _log.Info("YCSWebServerService stopped");
            _builder.Stop();
        }

我有一个“特定的”log4net 配置文件添加到我的服务项目中:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="EventLogAppender" />
    </root>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
      <threshold value="DEBUG" />
      <applicationName value="Lantic YCS WebServer" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="(%-5level %date{hh}:%date{mm}:%date{ss} [%thread] %logger [%property{NDC}] ) %message %n" />
      </layout>
    </appender>
  </log4net>

</configuration>

有什么想法或提示吗?

最佳答案

您是否刚刚在 app.config 文件中添加了一个 log4net 部分?在你的问题中,你提到你有“特定的 log4net 配置文件”,但你提供的示例看起来像 app.config 的全部内容。 如果 app.config 是这种情况,那么您可以在 AssemblyInfo.cs 中使用更简单的字符串:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

当我修复 log4net 未记录到 Windows 服务文件的类似问题时,在我的 app.config 部分添加 requirePermission="false"也帮助了我(请参阅额外属性 - requirePermission="false"):

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/>
  </configSections>

关于c# - log4net 不能在 Windows 服务中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3139481/

相关文章:

c# - 使用 itextsharp 在现有 pdf 中插入文本

linux - 如何在 Logrotate 上使用日期和时间作为文件名的一部分?

java - 使用 JNA 启动/停止服务

c# - 托管在 Windows 服务中的 wcf 服务,我有哪些缓存选项?

c# - MSMQ:MessageQueue.Close() 在 .EndReceive() 处抛出异常 -1073741536

c# - 从 foreach 循环中将模型加载到局部 View 中

c# - 如何使用菜单条显示所有打开的MDI窗体C#

c# - 如何返回具有任意类型成员的 IList

Java/ Selenium : Still getting "ChromeDriver was started successfully" message after disabling logging

sql-server - SQL Server 2008 的备份应用程序日志在哪里?