Adding Serilog as a service to Generic Host .NET8

Aman Singh Parihar
1 min readOct 4, 2024

Logging is an important part of any application. It helps to understand in and out of the application. I’ve created a simple program to use Serilog with the .NET 8 generic host IHostApplicationBuilder.

Packages required


<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog" Version="4.0.2" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.2" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />


Program.cs


using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace Memory
{
internal class Program
{
static async Task Main(string[] args)
{
var builder = Host.CreateApplicationBuilder(args);

var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();

builder.Services.AddSerilog(config =>
{
config.ReadFrom.Configuration(builder.Configuration);
});

builder.Services.AddSingleton<Worker>();

IHost host = builder.Build();

var worker = host.Services.GetRequiredService<Worker>();
await worker.ExecuteAsync();
}
}
}

Worker.cs, here we have injected the logger.

using Microsoft.Extensions.Logging;

namespace Memory
{
public class Worker(ILogger<Worker> logger)
{
public async Task ExecuteAsync()
{

logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1_000);

}
}
}

Loaded configuration from the appsettings.json

{
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "Console",
"Args": {
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
],
"Enrich": [ "FromLogContext" ],
"Properties": {
"Application": "Memory"
}
}
}

Log in the console

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Aman Singh Parihar
Aman Singh Parihar

Written by Aman Singh Parihar

I work as a software engineer and having experience in web technologies. I like to share my knowledge with the community and aspire to learn cool things.

No responses yet