Kemenkeu.Logging.Core 1.0.0

dotnet add package Kemenkeu.Logging.Core --version 1.0.0                
NuGet\Install-Package Kemenkeu.Logging.Core -Version 1.0.0                
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="Kemenkeu.Logging.Core" Version="1.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Kemenkeu.Logging.Core --version 1.0.0                
#r "nuget: Kemenkeu.Logging.Core, 1.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Kemenkeu.Logging.Core as a Cake Addin
#addin nuget:?package=Kemenkeu.Logging.Core&version=1.0.0

// Install Kemenkeu.Logging.Core as a Cake Tool
#tool nuget:?package=Kemenkeu.Logging.Core&version=1.0.0                

Kemenkeu.Logging.Core

A logging middleware library for ASP.NET Core applications that leverages Serilog for logging requests, responses, and other important context data. This library is equipped with flexible options for logging configurations and supports output to Console and Elasticsearch.

Features

  • Logs request and response payloads.
  • Configurable inclusion of headers and user information.
  • Supports Serilog integration with Console and Elasticsearch sinks.
  • Customizable logging options via appsettings.json and LoggingOptions.
  • Middleware-based logging with support for attributes to control logging on a per-endpoint basis.

Prerequisites

Ensure you have the following installed:

  • .NET 3.1 or later
  • ASP.NET Core
  • Elasticsearch (if using Elasticsearch sink)

Installation

Install the package via NuGet:

dotnet add package Kemenkeu.Logging.Core

Configuration

  1. Define Logging Options in appsettings.json:

    Add configuration settings for LoggingOptions and Elasticsearch as follows:

    {
      "App": {
        "Name": "MyAppName"  // Used to define Elasticsearch index format
      },
      "Logging": {
        "Elasticsearch": {
          "Url": "http://localhost:9200"
        }
      }     
    }
    
    • App.Name: Used to create the Elasticsearch index format.
    • Logging.Elasticsearch.Url: URL of your Elasticsearch instance.
  2. Logging Options in Code:

    You can also configure LoggingOptions directly in Startup.cs or Program.cs to control specific logging behaviors.

Usage

1. Setup in Startup.cs

In .NET 3.1 and .NET 5, you can configure logging in the Startup.cs file as follows:

using Kemenkeu.Logging.Core;
using Serilog;

public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Configure logging with custom options
        services.AddKemenkeuLogging(_configuration, options =>
        {
            options.EnableGlobalLogging = false;
            options.IncludeRequestPayload = true;
            options.IncludeResponsePayload = false;
            options.IncludeHeaders = true;
            options.IncludeUserInfo = true;
        });

        services.AddControllers(); // Register other necessary services
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseKemenkeuLogging(); // Adds LoggingMiddleware to pipeline
        app.UseRouting();
        app.UseEndpoints(endpoints => endpoints.MapControllers());
    }
}

1. Setup in Program.cs

In .NET 6 and later, you can configure logging in the Program.cs file as follows:

using Kemenkeu.Logging.Core;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Configure Serilog and LoggingMiddleware using AddKemenkeuLogging
builder.Services.AddKemenkeuLogging(builder.Configuration, options =>
{
    options.EnableGlobalLogging = false;
    options.IncludeRequestPayload = true;
    options.IncludeResponsePayload = false;
    options.IncludeHeaders = true;
    options.IncludeUserInfo = true;
});

var app = builder.Build();

// Use LoggingMiddleware
app.UseKemenkeuLogging();

// Configure the HTTP request pipeline.
app.UseAuthorization();
app.MapControllers();
app.Run();

2. Attributes for Controlling Logging on Specific Endpoints

You can use custom attributes EnableLoggingAttribute and DisableLoggingAttribute (defined in the middleware) to control logging on individual endpoints.

  • Enable Logging on a Specific Endpoint:

    [EnableLogging(IncludeRequestPayload = true, IncludeResponsePayload = true)]
    public IActionResult GetSomeData()
    {
        // Your code here
    }
    
  • Disable Logging on a Specific Endpoint:

    [DisableLogging]
    public IActionResult HealthCheck()
    {
        return Ok("Healthy");
    }
    

Logging Options

Below is an overview of the LoggingOptions:

Option Description
EnableGlobalLogging Enables logging for all requests globally. Default: false
IncludeRequestPayload Includes request payloads in the logs. Default: true
IncludeResponsePayload Includes response payloads in the logs. Default: false
IncludeHeaders Logs request and response headers. Default: true
IncludeUserInfo Logs user information based on claims. Default: true

Elasticsearch Setup

If you're using the Elasticsearch sink:

  1. Ensure your Elasticsearch instance is running and accessible at the specified URL.
  2. The library will automatically create a daily index following the format {AppName}-logs-yyyy.MM.dd.

Example Logs

Here�s an example of how logs will appear:

{
  "@timestamp": "2024-01-01T12:34:56.789Z",
  "level": "Information",
  "message": "Handled request POST /api/some-endpoint in 123ms. Status Code: 200",
  "properties": {
    "RequestBody": { "key": "value" },
    "ResponseBody": { "responseKey": "responseValue" },
    "UserInfo": {
      "UserId": "12345",
      "UserName": "johndoe",
      "ClientIp": "127.0.0.1",
      "ClientId": "my-client-id"
    },
    "StatusCode": 200,
    "ElapsedMilliseconds": 123
  }
}

Additional Resources

Troubleshooting

  • Issue: Logs are not appearing in Elasticsearch.
    • Solution: Check that the Elasticsearch URL is correct and the instance is reachable.
  • Issue: Middleware is not logging requests/responses.
    • Solution: Ensure EnableGlobalLogging is set to true or EnableLoggingAttribute is applied to the endpoint.

Contributing

Contributions are welcome! Please submit a pull request or open an issue to suggest improvements.

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.1 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
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
1.0.0 80 11/8/2024