.NET Core Topshelf Service and Serilog

Viewed 906

I am building a Windows service using .net core 3.1 with Topshelf and Serilog. The Serilog works fine if I run the exe only. If I start as a service with "MyServiceApp.exe start" then the log file is created and some initial log is written. But that is all. Nothing from 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:

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

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;
}
}
}
1 Answers

I re-wrote the service to use Worker Service and now Serilog is working fine

Related