Windows 服务 运行 使用 Log4Net 的应用程序

Windows Service running application using Log4Net

为了移动几个产品的数据,我创建了一个使用 Log4Net 跟踪进度的 C# 控制台应用程序。 Log4Net 在控制台应用程序 App.Config 文件中配置,目前有两个附加程序,一个 ConsoleAppender 和一个 RollingLogFileAppender。

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="logs\Log.txt" />
  <appendToFile value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %-5level %logger %method - %message%newline%exception" />
  </layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %-5level %logger %method - %message%newline%exception" />
  </layout>
</appender>
<root>
  <level value="DEBUG" />
  <appender-ref ref="RollingLogFileAppender" />
  <appender-ref ref="ConsoleAppender" />
</root>

此应用程序及其日志记录在 运行 独立时运行。现在,为了使此控制台应用程序的 运行 自动化,我正在为 运行 控制台应用程序创建 Windows 服务。该应用程序不需要任何用户输入,因此我确实预测了 运行 通过该服务连接它时会出现任何问题。当服务 运行s 成功调用控制台应用程序时,我可以看到它的工作结果,但是,日志记录似乎不起作用。被调用的可执行文件所在位置的日志没有改变,我无法在我的机器上的其他地方找到另一个日志实例。该服务 运行ning 作为本地系统,因此权限应该不是问题。我已尝试使用以下设置调用应用程序:

ProcessStartInfo processStartInfo = new ProcessStartInfo(@"C:\Constellation\Dev\Caelum\Caelum\bin\Debug\Caelum.exe");
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;

我已经尝试过使用和不使用输出重定向,但都没有用。非常感谢任何建议。

您的可执行文件可能不会在与您放置它的位置完全相同的位置执行。我已经在 system32 文件夹中的某处执行了我的应用程序。

尝试指定日志文件的绝对路径而不是相对路径,看看是否能解决您的问题。

有关类似问题,请参阅 here

您可能需要查看以下内容以验证您的 App.config 是否被 Windows 服务读取。

答案的相关部分在这里:

"If you cannot find a corresponding .exe.config file, then it is possible that the code within the service is falling back to default values. In this case, you can place a properly named and formatted config file alongside the service executable and then restart the service and everything should be fine."