'How to write .Net core Hosted Service logs into elastic search

I am developing a microservice application that consists of a few aspnet core web APIs and one .net6 hosted service. I use the elastic stack as the distributed logging system. Loggins work perfectly for all the aspnetcore web api. But it does not work for the worker service that was implemented from IHostedService.

This my program.cs of the worker service project

var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", true)
.Build();

Log.Logger = new LoggerConfiguration()
             .MinimumLevel.Information()
             .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
             .MinimumLevel.Override("System", LogEventLevel.Warning)
             .Enrich.FromLogContext()
             .Enrich.WithMachineName()
              .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(node: new Uri((configuration["ElasticConfiguration:Uri"])))
              {
                  AutoRegisterTemplate = true,
                  NumberOfReplicas = 1,
                  NumberOfShards = 2,
                  IndexFormat = $"{configuration["ApplicationName"]}-logs-{ Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT").Replace(".", "-")}-{DateTime.UtcNow:yyyy-MM}",

              })
            .WriteTo.Console()
            .Enrich.WithProperty("ApplicationName", "App Name")
            .CreateLogger();

     IHost host = Host.CreateDefaultBuilder(args)
  
    .ConfigureServices((hostContext, services) =>
    {
        services.AddSingleton(Log.Logger);
        services.AddHostedService<JobScheduler>();
        services.AddGrpcClient<ConfigurationHandler.ConfigurationHandlerClient>(options =>
        {
            options.Address = new Uri(hostContext.Configuration["GRPCSettings:ConfigurationServiceURL"]);
        });
        services.AddSingleton<IConfigurationGrpcClient, ConfigurationGrpcClient>();

    })
    .UseSerilog()
    .Build();


await host.RunAsync();

This is my Background service where I write the logs

 public class JobScheduler : BackgroundService
    {
        private readonly Serilog.ILogger _logger;
        private readonly IConfigurationGrpcClient _taskGRPCService;

    public JobScheduler(Serilog.ILogger logger, IConfigurationGrpcClient taskGRPCService)
    {
        _logger = logger;
        _taskGRPCService = taskGRPCService;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.Information("Task scheduler running at: {time}", DateTimeOffset.Now);
            _logger.Warning("Warning", DateTimeOffset.Now);
            _logger.Error("Error", DateTimeOffset.Now);
            await GetSchedledJobs();
            await Task.Delay(120000, stoppingToken);
        }
    }

    private async Task GetSchedledJobs()
    {
        try
        {
            var responce = await _taskGRPCService.GetScehduledTasksAsync();
        }
        catch (Exception ex)
        {
            _logger.Error(ex, messageTemplate: "Something bad happened {ExceptionType}", propertyValue: "GRPC");
        }
    }
}

Appreciate it if someone can point out where is the issue



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source