当Windows服务自动运行时,log4net无法运行

时间:2013-12-16 06:03:44

标签: c# windows-services log4net

我创建了一个Windows服务程序&安装服务:以下用于log4net的配置:

<log4net>
<root>
  <level value="All" />
  <appender-ref ref="RollingLogFileAppender" />
</root>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="D:\\Logs\\Menca.DataImportService\\%property{LogName}\\%property{LogName}.txt" />
  <appendToFile value="true" />
  <rollingStyle value="Composite" />
  <datePattern value="yyyyMMdd" />
  <maxSizeRollBackups value="2000" />
  <maximumFileSize value="500KB" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
  </layout>
</appender>    

当我启动服务手册时,它首次正确记录但在定义的间隔后运行时没有记录。我已经在代码中使用了计时器来每24小时运行一次。但它并没有在下一个时期创建日志。

System.Threading.Timer _timer = new System.Threading.Timer(new System.Threading.TimerCallback(TimerTick),
                null,
                0,
                24 * 3600000
             );

计时器将每24小时调用一次:

private void TimerTick(object sender)
    {
        try
        {
            // Thread.Sleep(15000);
            rCount = 0;
            iCount = 0;

            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            _eventLog.WriteEntry(string.Concat("Scheduled Service Call Start Hour: ", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            Helper.StartDataDump();

            _eventLog.WriteEntry(string.Concat("Scheduled Service Call End Hour: ", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            _eventLog.WriteEntry(string.Concat("Scheduled service call was processed successfully! : ", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

        }
        catch (Exception ex)
        {
            string errMsg = ex.InnerException == null ? ex.InnerException.Message : ex.Message;
            _eventLog.WriteEntry("Error occured in scheduled service call Exception: " + errMsg);
        }
    }

1 个答案:

答案 0 :(得分:1)

这与log4net无关,因为您甚至没有使用它(WriteEntryEventLog方法,而不是ILog方法。要使用log4net,您需要配置,从LogManager获取记录器,然后使用记录方法。样品:

log4net.Config.XmlConfigurator.Configure();
var logger = LogManager.GetLogger("root");
log.Info("Information message");

但是,您遇到的问题是Timer。我建议完成this answer所拥有的内容,因为它将在当前回调完成后启动下一个超时

private Timer _timer;
private ILog _logger = LogManager.GetLogger("root"); // Get the log4net logger
private const int _timeoutInMilliseconds = 10000;    // 10 seconds

public void Start()
{
    _timer = new Timer(new TimerCallback(timerTick),
            null,
            _timeoutInMilliseconds, // Timeout to wait until the callback is called
            Timeout.Infinite        // Makes sure it's only called once
         );
}
private void timerTick(object sender)
{
    _logger.Info("Sample");
    _timer.Change(_timeoutInMilliseconds, Timeout.Infinite); // Wait 10 seconds again
}

否则,您可以修复计时器,以便在超时后通过执行以下操作调用回调:

_timer = new Timer(new TimerCallback(timerTick),
        null,
        0,                     // Set a time here for an initial timeout
        _timeoutInMilliseconds // It will call timerTick every 10 seconds
     );