今天测试一个 Windows 服务程序,其中使用 log4net 却总是失败。不论 log4net 的配置写在 app.config 里,还是独立的 config 文件里,都是一样。最终发现原来是在服务里不能正确定位到这个配置文件所致(windows 服务一般默认是运在C:\Windows\System 或是C:\Windows\System32,而我们自己的服务程序一般是放在其他的目录,这样log4net.config文件中的配置路径将无法正确解析)。于是经过尝试之后,发现关键在于如下代码中获取当前 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);
}
}
提示:
右键选择 log4net.config 属性- 始终复制