使用Topshelf部署.net core windows服务 Demo
引用相关 包
<ItemGroup>
<PackageReference Include="Topshelf" Version="4.2.1" />
</ItemGroup>
设置项目类型
<Project Sdk="Microsoft.NET.Sdk.Worker">
修改 Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureServices(services =>
{
services.AddHostedService<VideosWatcher>();
});
}
修改后
public class Program
{
public static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.SetServiceName("TopshelfDemo.ServiceName");
x.SetDisplayName("TopshelfDemo.DisplayName");
x.SetDescription("TopshelfDemo.Description");
x.Service<IHost>(s =>
{
s.ConstructUsing(() => CreateHostBuilder(args).Build());
s.WhenStarted(service =>
{
service.Start();
});
s.WhenStopped(async service =>
{
await service.StopAsync();
});
});
x.StartAutomatically();
});
}
const string OutputInfoTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}{NewLine}";
const string OutputPropTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Properties:l}{NewLine}{Exception}{NewLine}";
public static IHostBuilder CreateHostBuilder(string[] args) =>
Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
#if DEBUG
.UseEnvironment(Environments.Development)
#else
.UseEnvironment(Environments.Staging)
//.UseEnvironment(Environments.Production)
#endif
.UseContentRoot(AppContext.BaseDirectory)
.UseSerilog((hostingContext, loggerConfiguration) =>
{
loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.WithExceptionDetails()
.Enrich.FromLogContext()
.WriteTo.Debug()
.WriteTo.Console(theme: SystemConsoleTheme.Colored)
.WriteTo.File(AppContext.BaseDirectory + "log/log.txt",
outputTemplate: OutputInfoTemplate, rollingInterval: RollingInterval.Day)
.WriteTo.File(AppContext.BaseDirectory + "log/error.txt", LogEventLevel.Warning,
outputTemplate: OutputPropTemplate, rollingInterval: RollingInterval.Day);
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
这里我使用 Serilog 作为日志系统
通过修改 outputTemplate 来输出想要 log 文件
效果如下
2020-11-04 17:13:05.873 +08:00 [INF] Worker.SaveMessage 已保存11条数据
2020-11-04 17:13:06.891 +08:00 [INF] Save Message Worker running at: 2020/11/4 17:13:06
2020-11-04 17:13:06.893 +08:00 [INF] Worker.SaveMessage 已保存12条数据
2020-11-04 17:13:07.908 +08:00 [INF] Save Message Worker running at: 2020/11/4 17:13:07
2020-11-04 17:13:07.910 +08:00 [INF] Worker.SaveMessage 已保存13条数据
2020-11-04 17:13:08.928 +08:00 [INF] Save Message Worker running at: 2020/11/4 17:13:08
2020-11-04 17:13:08.929 +08:00 [INF] Worker.SaveMessage 已保存14条数据
2020-11-04 17:13:09.936 +08:00 [INF] Save Message Worker running at: 2020/11/4 17:13:09
2020-11-04 17:13:09.938 +08:00 [INF] Worker.SaveMessage 已保存15条数据
2020-11-04 17:13:10.948 +08:00 [INF] Save Message Worker running at: 2020/11/4 17:13:10
2020-11-04 17:13:10.949 +08:00 [INF] Worker.SaveMessage 已保存16条数据
运行时效果如下:
有颜色显示的 控制台 还是不错的
打包
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>binpublish</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>
部署
找到相应的文件夹
TopshelfDemo.exe install
启动 TopshelfDemo
TopshelfDemo.exe start
卸载 TopshelfDemo
TopshelfDemo.exe uninstall
总体来说 使用非常简单