Tuesday 9 January 2024

ASP.NET Hosting Tutorial: Serilog's External Logging for APIs

Leave a Comment

Robust logging is an essential tool in the dynamic field of application development for deciphering and resolving software behavior issues. This is an easy operation, made possible by the widely used.NET logging package Serilog. This post will discuss how to use Serilog to establish external logging sources for Windows Services and APIs, offering a complete logging solution.



Packages Required

Make sure you have installed the required Serilog packages before beginning implementation.

<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />

Serilog configuration in the API
You need to add the following settings to your appsettings.json file in order to configure Serilog in your API.

"LogBaseDirectory": "C:\\WindowsServiceLogs\\",
"Serilog": {
  "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
  "MinimumLevel": "Debug",
  "WriteTo": [
    {
      "Name": "Console"
    },
    {
      "Name": "File",
      "Args": {
        "path": "%APP_BASE_DIRECTORY%/Logs/log-.txt",
        "rollingInterval": "Day"
      }
    }
  ]
}

The %APP_BASE_DIRECTORY% placeholder will be read from app settings and updated at the startup of the service.

API Startup Configuration

In the startup of your API, configure Serilog as follows.

using Serilog;

var host = Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .UseSerilog((context, services, configuration) => configuration
        .ReadFrom.Configuration(context.Configuration)
        .ReadFrom.Services(services))
    .ConfigureServices(services =>
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();

        if (!Directory.Exists(configuration["LogBaseDirectory"]))
        {
            Directory.CreateDirectory(configuration["LogBaseDirectory"]);
        }

        Environment.SetEnvironmentVariable("APP_BASE_DIRECTORY", configuration["LogBaseDirectory"]);

        services.AddHostedService<SimpleWorker>();
    })
    .Build();

await host.RunAsync();
Worker Class

Now, let's create a simple worker class that utilizes Serilog for logging.

public class SimpleWorker : BackgroundService
{
    private readonly ILogger<SimpleWorker> _logger;

    public SimpleWorker(ILogger<SimpleWorker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Execute SimpleWorker -> [ExecuteAsync]");

            await Task.Delay(1000, stoppingToken);
        }
    }

    public override Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Starting service [StartAsync]");

        return base.StartAsync(cancellationToken);
    }

    public override Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Stopping service [StopAsync]");

        return base.StopAsync(cancellationToken);
    }
}

With Serilog, logging for APIs and Windows Services becomes an effortless endeavor. By configuring Serilog to use external logging sources, you ensure that your application's behavior is well-documented and can be easily analyzed. Embrace the power of Serilog to enhance your logging strategy and make troubleshooting a breeze.

Best ASP.NET Core 8.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

0 comments:

Post a Comment