简体   繁体   English

.NET Core Topshelf 服务和 Serilog

[英].NET Core Topshelf Service and Serilog

I am building a Windows service using .net core 3.1 with Topshelf and Serilog.我正在使用带有 Topshelf 和 Serilog 的 .net core 3.1 构建 Windows 服务。 The Serilog works fine if I run the exe only.如果我只运行 exe,Serilog 工作正常。 If I start as a service with "MyServiceApp.exe start" then the log file is created and some initial log is written.如果我以“MyServiceApp.exe start”作为服务启动,则会创建日志文件并写入一些初始日志。 But that is all.但仅此而已。 Nothing from MyService!没有来自 MyService!

2020-03-18 13:38:33.389 +01:00 [INF] Args: ["start"]
2020-03-18 13:38:33.452 +01:00 [INF] Configuration Result:
[Success] Name MyService
[Success] Description MyService.
[Success] ServiceName MyService
2020-03-18 13:38:33.458 +01:00 [INF] Topshelf v4.2.1.215, .NET Framework v3.1.0
2020-03-18 13:38:33.474 +01:00 [DBG] Starting MyService
2020-03-18 13:38:34.226 +01:00 [INF] The MyService service was started.

Program.cs:程序.cs:

var exeRootFolder = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
var configuration = new ConfigurationBuilder()
.SetBasePath(exeRootFolder)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
HostFactory.Run(windowsService =>
{
windowsService.UseSerilog(Log.Logger);
windowsService.Service<RabbitMQServiceAgent>(sc =>
{
sc.ConstructUsing(hs => new MyService());
sc.WhenStarted((s, h) => s.Start(h));
sc.WhenStopped((s, h) => s.Stop(h));
});

windowsService.EnableServiceRecovery(r => r.RestartService(TimeSpan.FromSeconds(10)));
windowsService.SetServiceName("MyService");
windowsService.SetDisplayName("MyService");
windowsService.SetDescription("MyService.");
});

MyService.cs我的服务.cs

public class MyService : ServiceControl
{
public MyService()
{

}

public bool Start(HostControl hostControl)
{
Log.Information("Starting Service");

var myThread = new System.Threading.Thread(new System.Threading.ThreadStart(foreverWhile));
myThread.IsBackground = true;
myThread.Start();

return true;
}
public void foreverWhile()
{
while (true)
{
// to do something forever
Log.Debug("foreverWhile");
System.Threading.Thread.Sleep(2000);
}
}

public bool Stop(HostControl hostControl)
{
Log.Information("Stopping Service");

return true;
}
}
}

我重新编写了使用 Worker Service 的服务,现在 Serilog 工作正常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM