I followed the Serilog instructions to add a very basic log file to my application.
I am able to reproduce it doing the following:
- Created a new
ASP.NET Core Web Apiwith Visual Studio with the default parameters: .NET 5, no authentication, configured for HTTPS, enabling OpenAPI support - Installed the
Serilog.AspNetCorepackage - Installed the
Microsoft.Extensions.Hosting.WindowsServicespackage (so I could call theUseWindowsService()extension method) - Edited my
Program.csclass as follow:
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.File("logs.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
try
{
Log.Information("Starting Web Host");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
- Removed the Logging section from the app.settings:
{
"AllowedHosts": "*"
}
So far, when I run the web api from Visual Studio or the windows explorer, everything works great: the file logs.txt is created as expected and the web api is alive.
But then, when I create a windows service to run the app:
sc.exe create TestService binPath="path\to\WebApplication1.exe"
Despite the web api running well, there is no log file created.
Here is some of the things I tried:
- Changed the user running the service with my own account => no change
- Removed the call to
UseWindowsService()=> the web api does not start - Used another provider (NLog) => same behavior: no log file created
- Switched the calls between
UseWindowsService()andUseSerilog()=> no change - Called
UseWindowsService()andUseSerilog()(in both order) afterConfigureWebHostDefaults()=> no change
What did I do wrong? May be the whole run as a windows service part is not the best way to run my web api as a service?