NetLah.Extensions.Logging.Serilog.AspNetCore 0.2.3

The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org. Prefix Reserved
.NET 6.0 .NET Core 3.1
There is a newer version of this package available.
See the version list below for details.
dotnet add package NetLah.Extensions.Logging.Serilog.AspNetCore --version 0.2.3
NuGet\Install-Package NetLah.Extensions.Logging.Serilog.AspNetCore -Version 0.2.3
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NetLah.Extensions.Logging.Serilog.AspNetCore" Version="0.2.3" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add NetLah.Extensions.Logging.Serilog.AspNetCore --version 0.2.3
#r "nuget: NetLah.Extensions.Logging.Serilog.AspNetCore, 0.2.3"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install NetLah.Extensions.Logging.Serilog.AspNetCore as a Cake Addin
#addin nuget:?package=NetLah.Extensions.Logging.Serilog.AspNetCore&version=0.2.3

// Install NetLah.Extensions.Logging.Serilog.AspNetCore as a Cake Tool
#tool nuget:?package=NetLah.Extensions.Logging.Serilog.AspNetCore&version=0.2.3

NetLah.Extensions.Logging.Serilog - .NET Library

NetLah.Extensions.Logging.Serilog and NetLah.Extensions.Logging.Serilog.AspNetCore are library contain a set of reusable utility classes for initializing Serilog and initializing Microsoft.Extensions.Logging.ILogger for ASP.NETCore, hosting application (Worker serivce) and ConsoleApp. The utility classes are AppLog, AspNetCoreApplicationBuilderExtensions, AspNetCoreApplicationBuilderExtensions, HostBuilderExtensions.

Nuget package

NuGet NuGet

Build Status

Build Status

Getting started

Reference

Sample appsettings.json

{
  "AllowedHosts": "*",
  "Serilog": {
    "Using": ["Serilog.Sinks.Console"],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "App": "Information",
        "System": "Warning",
        "Microsoft": "Warning",
        "Microsoft.AspNetCore.Authentication": "Information",
        "Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker": "Error",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo:0": { "Name": "Console" },
    "Enrich": ["FromLogContext", "WithMachineName"],
    "Destructure": [
      {
        "Name": "ToMaximumDepth",
        "Args": { "maximumDestructuringDepth": 4 }
      },
      {
        "Name": "ToMaximumStringLength",
        "Args": { "maximumStringLength": 100 }
      },
      {
        "Name": "ToMaximumCollectionCount",
        "Args": { "maximumCollectionCount": 10 }
      }
    ],
    "Properties": {}
  }
}

Sample appsettings.Development.json

{
  "Serilog": {
    "Using:1": "Serilog.Sinks.Debug",
    "Using:2": "Serilog.Sinks.File",
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "App": "Debug"
      }
    },
    "WriteTo:1": { "Name": "Debug" },
    "WriteTo:2": {
      "Name": "File",
      "Args": {
        "path": "Logs/sample-.log",
        "rollingInterval": "Day"
      }
    }
    //"WriteTo:3": {
    //  "Name": "Seq",
    //  "Args": {
    //    "serverUrl": "https://seq",
    //    "apiKey": "ZrV42..."
    //  }
    //},
  }
}

ASP.NETCore 6.0

using NetLah.Extensions.Logging;

AppLog.InitLogger();
AppLog.Logger.LogInformation("Application starting...");
try
{
    var builder = WebApplication.CreateBuilder(args);
    builder.UseSerilog(logger => logger.LogInformation("Application initializing..."));

    // Add services to the container.

    builder.Services.AddControllers();

    var app = builder.Build();

    // Configure the HTTP request pipeline.

    app.UseAuthorization();

    app.MapControllers();

    app.Run();
}
catch (Exception ex)
{
    AppLog.Logger.LogCritical(ex, "Application terminated unexpectedly");
}
finally
{
    Serilog.Log.CloseAndFlush();
}

ConsoleApp

using Microsoft.Extensions.Logging;
using NetLah.Extensions.Configuration;
using NetLah.Extensions.Logging;

AppLog.InitLogger();
try
{
    AppLog.Logger.LogInformation("Application configure...");   // write log console only

    var configuration = ConfigurationBuilderBuilder.Create<Program>(args).Build();
    var logger = AppLog.CreateAppLogger<Program>(configuration);

    logger.LogInformation("Hello World!");      //  write log to sinks
}
catch (Exception ex)
{
    AppLog.Logger.LogCritical(ex, "Application terminated unexpectedly");
}
finally
{
    Serilog.Log.CloseAndFlush();
}

ConsoleApp with Dependency Injection

using Microsoft.Extensions.Logging;
using NetLah.Extensions.Configuration;
using NetLah.Extensions.Logging;

AppLog.InitLogger();
try
{
    AppLog.Logger.LogInformation("Application configure...");   // write log console only

    var configuration = ConfigurationBuilderBuilder.Create<Program>(args).Build();
    var logger = AppLog.CreateAppLogger<Program>(configuration);
    logger.LogInformation("Service configure...");      // write log to sinks

    IServiceCollection services = new ServiceCollection();
    services.AddSingleton<IConfiguration>(configuration);
    services.AddLogging();
    services.AddSerilog();
    services.AddScoped<Runner>();

    await using var rootServiceProvider = services.BuildServiceProvider();

    await using var scope = new AsyncDisposable<IServiceScope>(rootServiceProvider.CreateScope());

    var runner = scope.Service.ServiceProvider.GetRequiredService<Runner>();
    await runner.RunAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
    AppLog.Logger.LogCritical(ex, "Application terminated unexpectedly");
}
finally
{
    Serilog.Log.CloseAndFlush();
}

internal class AsyncDisposable<TService> : IAsyncDisposable where TService : IDisposable
{
    public AsyncDisposable(TService service) => this.Service = service;

    public TService Service { get; }

    public ValueTask DisposeAsync()
    {
        if (Service is IAsyncDisposable asyncDisposable)
            return asyncDisposable.DisposeAsync();

        Service.Dispose();
#if NETCOREAPP3_1
        return new ValueTask(Task.CompletedTask);
#else
        return ValueTask.CompletedTask;
#endif
    }
}

AspNetCore or Hosting application

using NetLah.Extensions.Logging;

public static void Main(string[] args)
{
    AppLog.InitLogger();
    try
    {
        AppLog.Logger.LogInformation("Application configure...");   // write log console only

        CreateHostBuilder(args).Build().Run();
    }
    catch (Exception ex)
    {
        AppLog.Logger.LogCritical(ex, "Host terminated unexpectedly");
    }
    finally
    {
        Serilog.Log.CloseAndFlush();
    }
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseSerilog2(logger => logger.LogInformation("Application initializing..."))    //  write log to sinks
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        AppLog.Logger.LogInformation("Startup constructor");    //  write log to sinks
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var logger = AppLog.Logger;
        logger.LogInformation("ConfigureServices...");          //  write log to sinks
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
    {
        var logger1 = AppLog.Logger;
        logger1.LogInformation("ConfigureApplication...");              //  write log to sinks
        logger.LogInformation("[Startup] ConfigureApplication...");     //  write log to sinks

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SampleWebApi v1"));
        }

        app.UseSerilogRequestLoggingLevel();

        app.UseHttpsRedirection();
    }
}
Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows
.NET Core netcoreapp3.1
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.2.4 383 1/2/2023
0.2.4-rc1 591 9/14/2022
0.2.3 318 9/2/2022
0.2.3-rc1 153 8/8/2022
0.2.3-alpha.0.1 196 7/7/2022
0.2.2 412 12/1/2021
0.2.1 257 11/19/2021