Windows 服务中正确使用 log4net

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;
using log4net;
using log4net.Config;


namespace DCServer
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            string assemblyFilePath = Assembly.GetExecutingAssembly().Location;
            string assemblyDirPath = Path.GetDirectoryName(assemblyFilePath);
            string configFilePath = assemblyDirPath + "\\log4net.config";
            
             XmlConfigurator.ConfigureAndWatch(new FileInfo(configFilePath));

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new DC()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}
服务里不能正确定位到这个配置文件所致(windows 服务一般默认是运在C:\Windows\System 或是C:\Windows\System32,而我们自己的服务程序一般是放在其他的目录,这样log4net.config文件中的配置路径将无法正确解析)。于是经过尝试之后,发现关键在于如下代码中获取当前 exe 所在目录并用于得到 config 文件的路径

猜你喜欢

转载自blog.csdn.net/farmwang/article/details/80676690