Topshelf是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务宿主。
官网:http://topshelf-project.com/
文档:https://topshelf.readthedocs.org/en/latest/
代码:https://github.com/topshelf/topshelf
1. 新建一个控制台项目,引用Topshelf和Log4net:
Install-Package Topshelf
Install-Package Topshelf.Log4Net
2. 修改相关文件。
Program.cs:
using System;
using System.IO;
using System.Timers;
using log4net;
using log4net.Config;
using Topshelf;
namespace TopshelfDemo
{
public class TownCrier
{
readonly Timer _timer;
readonly ILog _log = LogManager.GetLogger(typeof(TownCrier));
public TownCrier()
{
_timer = new Timer(5000) { AutoReset = true };
_timer.Elapsed += (sender, eventArgs) =>
{
_log.Info(DateTime.Now);
};
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
class Program
{
public static void Main()
{
var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.xml");
XmlConfigurator.ConfigureAndWatch(logCfg);
HostFactory.Run(x =>
{
x.Service<TownCrier>(s =>
{
s.ConstructUsing(name => new TownCrier());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName("Stuff");
x.SetServiceName("Stuff");
});
}
}
}
log4net.xml:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--日志路径-->
<param name= "File" value= "Logs\"/>
<!--是否是向文件中追加日志-->
<param name= "AppendToFile" value= "true"/>
<!--log保留天数-->
<param name= "MaxSizeRollBackups" value= "10"/>
<!--日志文件名是否是固定不变的-->
<param name= "StaticLogFileName" value= "false"/>
<!--日志文件名格式为:2008-08-31.log-->
<param name= "DatePattern" value= "yyyy-MM-dd".log""/>
<!--日志根据日期滚动-->
<param name= "RollingStyle" value= "Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="[%d] [%p] [%c] - %m%n" />
</layout>
</appender>
<!-- 控制台前台显示日志 -->
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="Info" />
<foreColor value="Green" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="Info" />
<param name="LevelMax" value="Fatal" />
</filter>
</appender>
<root>
<!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
<level value="all" />
<appender-ref ref="ColoredConsoleAppender"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
3. 执行,在控制台和日志文件中每5秒钟显示一条时间信息:
4. 服务相关操作:
安装:TopshelfDemo.exe install
启动:TopshelfDemo.exe start
卸载:TopshelfDemo.exe uninstall