TLogNET 1.0.3

dotnet add package TLogNET --version 1.0.3
                    
NuGet\Install-Package TLogNET -Version 1.0.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="TLogNET" Version="1.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TLogNET" Version="1.0.3" />
                    
Directory.Packages.props
<PackageReference Include="TLogNET" />
                    
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 TLogNET --version 1.0.3
                    
#r "nuget: TLogNET, 1.0.3"
                    
#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 TLogNET@1.0.3
                    
#: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=TLogNET&version=1.0.3
                    
Install as a Cake Addin
#tool nuget:?package=TLogNET&version=1.0.3
                    
Install as a Cake Tool

TLogNET

TLogNET is a comprehensive structured logging and telemetry library for .NET applications. It leverages Autofac for dependency injection and interception (AOP) and Serilog for high-performance, structured log output.

Features

  • Automatic Interception Logging (AOP): Automatically logs method entry, exit, exceptions, execution time, arguments, and return values for registered services without cluttering business logic.
  • Asynchronous Support: Full support for async/await patterns (Task and Task<T>).
  • Context Awareness: Captures contextual information such as TransactionId, Username, SiteCode, TenantId, etc., via TContext.
  • Manual Logging: Provides ILogWriter for manual logging when interception isn't applicable.
  • Sensitive Data Masking: Configurable masking of sensitive properties (e.g., passwords, tokens).
  • Filtering: Exclude specific assemblies, classes, or methods from logging via configuration.
  • Structured Output: Logs are written in a structured JSON format, making them easy to query in tools like Elasticsearch, Seq, or Splunk.

Dependencies

Installation

Add the TLogNET library reference to your project.

Install-Package TLogNET

Configuration

1. appsettings.json

Configure Serilog and TLogSettings in your appsettings.json.

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "logs/log-.txt",
          "rollingInterval": "Day"
        }
      }
    ]
  },
  "TLogSettings": {
    "ResponseSize": 1000,
    "ExcludeClasses": null,
    "ExcludeMethods": null,
    "ExcludeAssemblies": [
      "Microsoft.AspNetCore.Mvc.Core.dll",
      "Microsoft.AspNetCore.Mvc.ViewFeatures.dll"
    ],
    "SensitiveProps": [
      "token",
      "password",
      "pass",
      "pwd",
      "accountnum",
      "secure",
      "cardnumber"
    ]
  }
}

Setup & Integration

In your Startup.cs (for .NET Core versions supporting IServiceProvider return type in ConfigureServices):

using TLog.Extensions;
using Autofac;
using Autofac.Extras.DynamicProxy;

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // 1. Add other services
    services.AddMvc();

    // 2. Register TLog and your services
    // This sets up Serilog, registers TLog services, and configures the Autofac container.
    return services.AddTLog(Configuration, containerBuilder =>
    {
        // Register your application services here and enable logging
        containerBuilder.RegisterType<MyService>()
            .As<IMyService>()
            .EnableInterfaceInterceptors()
            .AddLogInterceptor();

        // Alternatively, you can enable logging for all controllers in a specific assembly
        containerBuilder.RegisterAssemblyTypes(Assembly.GetEntryAssembly())
            .Where(x => x.Name.EndsWith("Controller"))
            .EnableClassInterceptors()
            .AddLogInterceptor();

        // Register other services...
    });
}

Note: The AddTLog extension method builds and returns the AutofacServiceProvider, replacing the default service provider.

2. TContext Configuration

To ensure every log entry contains relevant context (like User ID, Transaction ID), you should populate the TContext scoped service at the beginning of the request using a Middleware.

Step 1: Create the Middleware

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using TLog.Context;

public class TLogContextMiddleware
{
    private readonly RequestDelegate _next;

    public TLogContextMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context, TContext tContext)
    {
        // Populate TContext from HttpContext
        tContext.TransactionId = context.TraceIdentifier;
        tContext.Username = context.User?.Identity?.Name ?? "Anonymous";
        // tContext.SiteCode = ...
        // tContext.TenantId = ...
        
        await _next(context);
    }
}

Step 2: Register Middleware in Startup.cs

public void Configure(IApplicationBuilder app)
{
    // Register before MVC or other middleware that generates logs
    app.UseMiddleware<TLogContextMiddleware>();
    
    app.UseMvc();
}

Usage

Automatic Logging

Once registered with .EnableInterfaceInterceptors().AddLogInterceptor(), any method call defined in the interface IMyService will be intercepted.

public interface IMyService
{
    Task<User> GetUserAsync(int id);
}

public class MyService : IMyService
{
    public async Task<User> GetUserAsync(int id)
    {
        // Logic...
        return await _repo.GetAsync(id);
    }
}

What gets logged:

  • Start: (Implicit) Tracking of start time.
  • End: Arguments, Return Value (serialized), Execution Time (ms), Exception (if any), Context Data (TContext).
Manual Logging

Inject ILogWriter to write logs manually with the same structure and context.

public class MyService
{
    private readonly ILogWriter _logger;

    public MyService(ILogWriter logger)
    {
        _logger = logger;
    }

    public void Process()
    {
        try
        {
            _logger.Information("Processing started", nameof(MyService), nameof(Process));
            // ...
        }
        catch(Exception ex)
        {
            _logger.Exception(ex, nameof(MyService), nameof(Process));
        }
    }
}
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  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 was computed.  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 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos 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
1.0.3 225 6/12/2024