ITSS.SimpleLogs 0.4.0

dotnet add package ITSS.SimpleLogs --version 0.4.0
                    
NuGet\Install-Package ITSS.SimpleLogs -Version 0.4.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="ITSS.SimpleLogs" Version="0.4.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ITSS.SimpleLogs" Version="0.4.0" />
                    
Directory.Packages.props
<PackageReference Include="ITSS.SimpleLogs" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ITSS.SimpleLogs --version 0.4.0
                    
#r "nuget: ITSS.SimpleLogs, 0.4.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.
#:package ITSS.SimpleLogs@0.4.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ITSS.SimpleLogs&version=0.4.0
                    
Install as a Cake Addin
#tool nuget:?package=ITSS.SimpleLogs&version=0.4.0
                    
Install as a Cake Tool

ITSS.SimpleLogs

A lightweight, consistent logging helper for ASP.NET Core (.NET 8) applications with first‑class NLog and Serilog support, ready‑to‑use JSON layouts/formatter, HTTP enrichment middleware, and optional request body logging.

Highlights

  • NLog and Serilog: code‑first setup or configuration file based.
  • JSON logs: consistent schema with timestamp, level, message, exception, traceId, logger, and enriched context properties.
  • HTTP middleware: request start/finish logging, correlation via header (e.g., X-Correlation-Id), duration and status.
  • Request body: gated by logger level and method/response (POST/PUT/PATCH and 409/5xx, or always at Debug).

Requirements

  • .NET 8 (net8.0)

Installation

Install the package:

dotnet add package ITSS.SimpleLogs

Quick start (NLog)

  1. In Program.cs (top-level statements) enable NLog and apply the default configuration:
var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSimpleNLog();

// Code-based NLog config (targets, rules, JSON layout, rolling, etc.)
var nlog = ITSS.SimpleLogs.SimpleLogsManager.InitNLogWithDefaultConfig();

var app = builder.Build();

// HTTP enrichment middleware (optionally with correlation header name)
app.UseNLogHttpLoggingEnrichmentMiddleware("X-Correlation-Id");

// (Optional) request body logging for NLog – enabled only when the RequestBody logger is active
app.UseNLogRequestPostedBodyMiddleware();

app.MapGet("/ping", () => "pong");
app.Run();
  1. Alternatively, load NLog from appsettings.json or XML:
// appsettings.json
var nlog = SimpleLogsManager.InitNLogWithAppsettingsConfig();

// or XML file (e.g., nlog.config)
var nlog = SimpleLogsManager.InitNLogWithXmlConfig("nlog.config");

Minimal NLog section in appsettings.json (using custom layouts):

{
  "NLog": {
    "autoReload": true,
    "throwConfigExceptions": true,
    "extensions": [ { "assembly": "ITSS.SimpleLogs" } ],
    "targets": {
      "allFile": {
        "type": "File",
        "fileName": "${basedir}/../Logs/WebApi.log",
        "archiveEvery": "Day",
        "archiveNumbering": "Rolling",
        "layout": { "type": "BaseCustomJsonLayout" }
      }
    },
    "rules": [
      { "logger": "*", "minLevel": "Info", "writeTo": "allFile" }
    ]
  }
}

The default code config writes a single JSON log file (../Logs/WebApi.log relative to basedir) with daily rolling; special HTTP categories (Request/Response/Correlation/RequestBody) are routed to the same file.

Quick start (Serilog)

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSimpleSerilog();

// Default setup (console + file with BaseCustomJsonFormatter)
var serilog = SimpleLogsManager.InitSerilogDefaultConfig();

// or from appsettings.json
// var serilog = SimpleLogsManager.InitSerilogWithAppsettingsConfig(builder.Configuration);

var app = builder.Build();

app.UseSerilogHttpLoggingEnrichmentMiddleware("X-Correlation-Id");

app.MapGet("/ping", () => "pong");
app.Run();

Example Serilog section in appsettings.json (category overrides):

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "ITSS.SimpleLogs.Middlewares.SerilogHttpLoggingEnrichmentMiddleware.RequestBody": "Information"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": { "path": "Logs/log-.txt", "rollingInterval": "Day" }
      }
    ],
    "Enrich": [ "FromLogContext" ]
  }
}

Request body logging controls

  • When: by default for POST/PUT/PATCH and only for 409/5xx responses; always when the RequestBody category runs at Debug level.
  • NLog:
    • Category: ITSS.SimpleLogs.Middlewares.NLogHttpLoggingEnrichmentMiddleware.RequestBody.
    • Enable via NLog rules (e.g., minLevel=Info) and use HttpRequestBodyCustomJsonLayout to emit the Body field.
    • UseNLogRequestPostedBodyMiddleware() wires NLog.Web.NLogRequestPostedBodyMiddleware conditionally only when the logger is active.
  • Serilog:
    • Category: ITSS.SimpleLogs.Middlewares.SerilogHttpLoggingEnrichmentMiddleware.RequestBody.
    • Enable via MinimumLevel.Override. The middleware buffers and reads the body (EnableBuffering).

API quick reference

  • SimpleLogsManager.InitNLogWithDefaultConfig(Action<LoggingConfiguration>? configure = null) – code‑based NLog setup (targets, rules, JSON layouts). You can mutate the config via the callback.
  • SimpleLogsManager.InitNLogWithAppsettingsConfig() – registers custom layouts and loads NLog from appsettings.json.
  • SimpleLogsManager.InitNLogWithXmlConfig(string xmlFilePath) – loads NLog from XML and registers layouts.
  • SimpleLogsManager.ConfigureBaseLayout(...) / ConfigureRequestLayout(...) / ConfigureResponseLayout(...) / ConfigureRequestBodyLayout(...) – runtime JSON layout tweaks.
  • SimpleLogsManager.InitSerilogDefaultConfig() – default Serilog setup (console + file using BaseCustomJsonFormatter).
  • SimpleLogsManager.InitSerilogWithAppsettingsConfig(IConfiguration) – Serilog setup from appsettings.json.
  • WebApplicationExtensions.UseNLogHttpLoggingEnrichmentMiddleware(string? correlationIdHeaderName = null) – HTTP middleware for NLog.
  • WebApplicationExtensions.UseSerilogHttpLoggingEnrichmentMiddleware(string? correlationIdHeaderName = null) – HTTP middleware for Serilog.
  • IServiceProviderExtensions.UseNLogRequestPostedBodyMiddleware() – conditional request body reader for NLog.
  • LoggingExtensions.LogException(this ILogger, Exception) – helper to log exceptions as Error.

JSON log format

Common fields (short example):

{
  "timestamp": "2025-01-01T12:34:56.1234567Z",
  "level": 2,
  "message": "Request completed.",
  "exception": null,
  "traceId": "00-<traceId>-<spanId>-00",
  "logger": "ITSS.SimpleLogs.Middlewares.SerilogHttpLoggingEnrichmentMiddleware+Response",
  "StatusCode": 200,
  "Duration": 123
}

Additional fields for requests (Form, QueryString, Path, Method, Env, Hostname) and for body (Body).

Best practices and middleware order

  • Place the HTTP enrichment middleware early in the pipeline, after global exception handling and before routing/endpoints.
  • Set the correlation header (e.g., X-Correlation-Id) in UseNLogHttpLoggingEnrichmentMiddleware(..) / UseSerilogHttpLoggingEnrichmentMiddleware(..).

License

See LICENSE.txt. Usage is restricted to applications delivered by ITSS according to the relevant agreements.

Changelog

See CHANGELOG.md.

Product Compatible and additional computed target framework versions.
.NET 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.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
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
0.4.0 113 9/11/2025