timer 一直打印log_使用Timer,Topshelf和Log4Net的.NET Windows服务模板

timer 一直打印log

介绍 (Introduction)

What I like about Topshelf is that it turns a console application into a service installer with a comprehensive set of command-line options for installing, configuring, and running your application as a service. This means you can run it as a console application and easily install it as a service without having to write the code.

我对Topshelf的满意之处在于,它可以将控制台应用程序转换为服务安装程序,并具有用于安装,配置和将应用程序作为服务运行的一整套命令行选项。 这意味着您可以将其作为控制台应用程序运行,并且可以轻松将其作为服务安装,而无需编写代码。

I also utilize the Topshelf.Log4Net to enable both service and application logging.

我还利用Topshelf.Log4Net启用服务和应用程序日志记录。

For your convenience, the Visual Studio template can be downloaded from http://blog.ittelligence.com/wp-content/uploads/2018/12/ITtelligence-Windows-Service.zip and simply imported

为了方便起见,可以从http://blog.ittelligence.com/wp-content/uploads/2018/12/ITtelligence-Windows-Service.zip下载Visual Studio模板并只需导入

创建模板 (Creating the template)

1) Start Visual Studio and create a Console Application (.NET Framework) Project

1)启动Visual Studio并创建一个控制台应用程序(.NET Framework)项目

2) From Package Manage Console run this command to install Topshelf

2)从Package Manage Console运行此命令以安装Topshelf

Install-Package Topshelf -Version 4.1.0 

3) From Package Manage Console run this command to install Log4Net for Topshelf

3)从Package Manage Console运行此命令以安装Log4Net for Topshelf

4) Add a class and call it MyService.cs

4)添加一个类并将其命名为MyService.cs

5) Add the following code to Service.cs (See comments in the code to understand what it is doing)

5)将以下代码添加到Service.cs中 (请参阅代码中的注释以了解其功能)

Application specific code can be added to the OnTimedEvent method.

可以将应用程序特定的代码添加到OnTimedEvent方法。

using log4net;
using log4net.Config;
using System;
using System.Timers;

namespace WindowsServiceTemplate
{
public class MyService
{
// Setup log4net logger
private static readonly ILog _log = LogManager.GetLogger(typeof(MyService));

// The timer that triggers the event
private Timer _heartbeatTimer = new Timer();

// Boolean to determine if trigger should reoccur
private volatile bool _requestServiceStop = false;

// Interval that event should be triggered at
private readonly long _heartbeatInterval = 10;

public MyService()
{
// Configure log4net from app.config file
XmlConfigurator.Configure();
// Set the timer interval
_heartbeatTimer.Interval = _heartbeatInterval * 1000;
// Set the event that should be triggered
_heartbeatTimer.Elapsed += OnTimedEvent;
// Important! We do not want the event to reoccur unless on trigger has finished
_heartbeatTimer.AutoReset = false;
// Start event
_heartbeatTimer.Start();
}

public void Start()
{
// Event should not stop the timer
_requestServiceStop = false;
// Start event
_heartbeatTimer.Start();
}

public void Stop()
{
// Event should stop the timer
_requestServiceStop = true;
// Stop event
_heartbeatTimer.Stop();
}

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Log heartbeat message
_log.Info($"Heartbeat\t{DateTime.Now}");

// Put code here

// Start timer again if no request to stop recieved
if (!_requestServiceStop)
{
_heartbeatTimer.Start();
}
}
}
} 

6) Add a class and call it ConfigureService.cs

6)添加一个类,并将其称为ConfigureService .cs

7) Add the following code to ConfigureService.cs (See comments in the code to understand what it is doing)

7)将以下代码添加到ConfigureService .cs中 (请参阅代码中的注释以了解其功能)

using log4net.Config;
using Topshelf;

namespace WindowsServiceTemplate
{
internal static class ConfigureService
{
internal static void Configure()
{
// Configure log4net from app.config file
XmlConfigurator.Configure();

// Service configuration
HostFactory.Run(configure =>
{
configure.Service<MyService>(service =>
{
service.ConstructUsing(s => new MyService());
service.WhenStarted(s => s.Start());
service.WhenStopped(s => s.Stop());
});

// Set account that window service use to run.
configure.RunAsLocalSystem();

// Set service to the log4net
configure.UseLog4Net();

// Service text
configure.SetServiceName("Put your service name here");
configure.SetDisplayName("Put your service display name here");
configure.SetDescription("Put your service description here");
});
}
}
} 

8) Edit the App.config file. Essentially we are adding the Log4Net configuration 

8)编辑App.config文件。 本质上,我们正在添加Log4Net配置

<?xml version="1.0" encoding="utf-8"?>

<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>

<log4net>
<appender name="console" type="log4net.Appender.ConsoleAppender, log4net">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{ABSOLUTE} [%thread] %-5p %c{1}:%L - %m%n" />
</layout>
</appender>

<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="logs\" />
<datePattern value="'Service-Name-'dd.MM.yyyy'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>

<root>
<level value="DEBUG" />
<appender-ref ref="console" />
<appender-ref ref="RollingFile" />
</root>
</log4net>
</configuration> 

9) Finally, edit Program.cs

9)最后,编辑Program.cs

namespace WindowsServiceTemplate
{
internal class Program
{
private static void Main(string[] args)
{
// Start Windows Service
ConfigureService.Configure();
}
}
} 

示范执行 (Demo Execution)

This is demo execution of application directly from command line.

这是直接从命令行执行应用程序的演示。

The following shows a sample of the log file that is generated

下面显示了生成的日志文件的示例

The application can easily be installed as a Windows Service with the INSTALL parameter

使用INSTALL参数可以轻松将应用程序安装为Windows服务。

The installed service

已安装的服务

结论 (Conclusion)

I hope you found this tutorial useful. You are encouraged to ask questions, report any bugs or make any other comments about it below.

希望本教程对您有所帮助。 鼓励您在下面提出问题,报告任何错误或对此作出任何其他评论。

Note: If you need further "Support" about this topic, please consider using the Ask a Question feature of Experts Exchange. I monitor questions asked and would be pleased to provide any additional support required in questions asked in this manner, along with other EE experts...  

注意 :如果您需要有关此主题的更多“支持”,请考虑使用Experts Exchange 的“提问”功能。 我会监督提出的问题,并很高兴与其他电子工程师一起提供以这种方式提出的问题所需的任何其他支持...

Please do not forget to press the "Thumbs Up" button if you think this article was helpful and valuable for EE members.

如果您认为本文对EE成员有用且有价值,请不要忘记按下“竖起大拇指”按钮。

It also provides me with positive feedback. Thank you!

它还为我提供了积极的反馈。 谢谢!

翻译自: https://www.experts-exchange.com/articles/33372/NET-Windows-Service-Template-using-Timer-Topshelf-and-Log4Net.html

timer 一直打印log

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值