Reputation: 3
I have created a basic worker service that only creates a log file through log4net nugget package in .net core 3.1. When I run the .exe file of the application it runs fine within debug or release. As soon as I install the service and start the service from the windows services.msc it shows the status for 'running' but nothing really happens at the backend. Services doesn't seem to be running at all. No Log directory containing log files created. The worker service 'Log On' as 'Local System account' and has read/write permissions.
Following are the files
Worker.cs
using log4net;
using log4net.Config;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Fluent;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace WorkerService1
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
// DO YOUR STUFF HERE
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
Log.Info("Connecting to Hub.");
await base.StartAsync(cancellationToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
// DO YOUR STUFF HERE
await base.StopAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}
Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WorkerService1
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
}
Upvotes: 0
Views: 1205
Reputation: 456437
LocalSystem
Win32 services start with a working directory different than where the exe is. So loading a file like log4net.config
won't find that file in the current directory. You'll need to use something like AppContext.BaseDirectory
to find the proper config file location.
Upvotes: 1