有时候我们需要用到window服务来执行定时任务,然后配合log4net记录程序运行情况,这里简单记录下配置的整个过程以及注意要点:

一.添加windows服务

1.设计页面,右键添加安装程序

windows服务与log4net应用

2.右键serviceInstaller,修改几个属性:StartType选择Automatic,跟随系统启动

windows服务与log4net应用

windows服务与log4net应用

3.右键serviceProcessInstaller1,修改account属性:为LocalSystem

windows服务与log4net应用

4.修改service1.cs服务名称与serviceInstall中服务名称的属性一致

windows服务与log4net应用

5.service1.cs代码中,添加自己的定时任务代码,

protected override void OnStart(string[] args)
{
     ReportJobScheduler.Start();
}

protected override void OnStop()
{

}

 

 

二.加入log4Net记录日志

1.nuget包工具给项目添加log4Net

2.修改配置文件App.config,添加相关节点

windows服务与log4net应用

 3.最容易忽视且最重要一点,Properties下的AssemblyInfo.cs文件添加如下代码:

[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]

 

控制台应用程序中也要注意别忘记修改AssemblyInfo.cs文件。

 4、windows服务在Program.cs的Main方法中添加如下代码:

string assemblyFilePath = Assembly.GetExecutingAssembly().Location;
string assemblyDirPath = Path.GetDirectoryName(assemblyFilePath);
string configFilePath = assemblyDirPath + "\\log4net.config";

XmlConfigurator.ConfigureAndWatch(new FileInfo(configFilePath));

 

PS:如果是Web程序,Global配置文件下,Application_Start方法中添加代码(log4net.config配成了一个单独文件):

protected void Application_Start(object sender, EventArgs e)
 {
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Server.MapPath("/log4net.config")));
 }

 三、安装和卸载服务

1.安装与运行:

进入如下目录:C:\Windows\Microsoft.NET\Framework64\v4.0.30319,将InstallUtil.exe复制到改windows服务bin/debug下:

windows服务与log4net应用

2.cmd命令窗口(管理员身份运行),进入到该debug目录下,之后的安装,运行命令如下:

安装:InstallUtil.exe WindowsDemo0205.exe

卸载:InstallUtil.exe -u WindowsDemo0205.exe

运行:net start MyService

停止:net stop MyService

 

异常问题:

在windows 安装服务报异常:System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件日志。不可 访问的日志: Security

windows服务与log4net应用

 

方法:以管理员身份运行命令提示符即可

相关文章:

  • 2022-12-23
  • 2021-04-20
  • 2022-01-19
  • 2021-10-18
猜你喜欢
  • 2022-12-23
  • 2022-01-15
  • 2022-12-23
  • 2021-09-15
  • 2022-01-05
  • 2021-10-26
相关资源
相似解决方案