[英]Windows service isn't writing to its log file in C#
I want to start with Windows service in C#. 我想从C#中的Windows服务开始。 I would start with a simple service that would print:
我将从一个可以打印的简单服务开始:
Hello (as soon service start)
Goodbye (as soon service stop)
This should be pretty simple, and genuinely, in VB.net I would achieve this easily. 这应该非常简单,并且真正地,在VB.net中,我将轻松实现这一目标。 So I've created a new C# Windows Service project, imported
log4net
with nuGet package manager . 因此,我创建了一个新的C#Windows Service项目,并使用nuGet软件包管理器导入了
log4net
。 Then I've the service class: 然后是服务类:
public partial class Service1 : ServiceBase
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
log.Info("hello");
}
protected override void OnStop()
{
log.Info("goodbye");
}
}
and so VS creates the static class: 因此,VS创建了静态类:
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
log.Info("NewService1");
ServiceBase.Run(ServicesToRun);
}
}
This is the App.config
with log4net configuration: 这是带有log4net配置的
App.config
:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="FileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="C:\logging\operativity.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{dd/MM/yyyy HH:mm:ss.fff} - %level - %message%newline" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{dd/MM/yyyy HH:mm:ss} - %level - %message%newline" />
</layout>
</appender>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
I've installed a service installer, so i've installed the service with installutil
and started it (with success), but, alas, no hello/goodbye are logged. 我已经安装了服务安装程序,因此我已经使用
installutil
安装了服务并启动了它(成功),但是,可惜,没有记录任何问候/再见。 This style of logging is the same that I used in another project and it worked without any problems. 这种日志记录样式与我在另一个项目中使用的日志记录样式相同,并且可以正常工作。
Why I can't get no hello this time? 为什么这次我不能打招呼?
假设您没有隐藏或删除示例中的任何代码,则需要在调用任何日志方法(Info,Debug等)之前配置log4net:
log4net.Config.XmlConfigurator.Configure();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.