如何在 Windows 服务中正确使用 log4net
今天终于发现原来是在服务里不能正确定位到这个配置文件所致。
于是经过尝试之后,发现关键在于如下代码中获取当前 exe 所在目录并用于得到 config 文件的路径。按这个写法就可以正确输出日志了:
public class Service1 : ServiceBase{ // 进程的主入口点 private static void Main() { string assemblyFilePath = Assembly.GetExecutingAssembly().Location; string assemblyDirPath = Path.GetDirectoryName(assemblyFilePath); string configFilePath = assemblyDirPath + "//log4net.config"; DOMConfigurator.ConfigureAndWatch(new FileInfo(configFilePath)); ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] {new Service1()}; ServiceBase.Run(ServicesToRun); } // 其他略}