TLog 1.0.9

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

About

TLog is a comprehensive structured logging and telemetry library for .NET 8 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 TLog library reference to your project.

Configuration

1. appsettings.json

Configure Serilog and TLogSettings in your appsettings.json.

{
   "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File",
      "Serilog.Sinks.Async"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Async",
        "Args": {
          "configure": [
            {
              "Name": "File",
              "Args": {
                "path": "logs/log.txt",
                "rollingInterval": "Day",
                "rollOnFileSizeLimit": true,
                "fileSizeLimitBytes": "10240000",
                "shared": true
              }
            }
          ]
        }
      }
    ]
  },
  "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" 
      ]
  }
}

2. Implement Context Provider (Optional)

To propagate context (like User ID or Transaction ID) into the logs, implement ITLogContextProvider.

using TLog.Context;

public class MyContextProvider : ITLogContextProvider
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyContextProvider(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public TContext GetCurrentContext()
    {
        var context = _httpContextAccessor.HttpContext;
        return new TContext
        {
            TransactionId = context?.TraceIdentifier ?? Guid.NewGuid().ToString(),
            Username = context?.User?.Identity?.Name ?? "Anonymous",
            // ... populate other fields
        };
    }
}

Setup & Integration

In your Program.cs, register TLog with the host builder.

using TLog.Extensions;
using Autofac;
using Autofac.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// 1. Register TLog
// This sets up Serilog, registers TLog services, and configures the Autofac container.
builder.AddTLog(builder.Configuration, containerBuilder =>
{
    Assembly assembly = typeof(Program).Assembly;

    // Register your Context Provider (optional)
    containerBuilder.RegisterType<MyContextProvider>().As<ITLogContextProvider>().InstancePerLifetimeScope();

    // Register your application services here
    // Use .AddLogInterceptor() to enable logging for a service
    containerBuilder.RegisterType<MyService>()
                    .As<IMyService>()
                    .InstancePerLifetimeScope()
                    .AddLogInterceptor();

   // Alternatively, you can enable logging for all controllers in an assembly
    containerBuilder.RegisterAssemblyTypes(assembly)
                    .Where(s => s.Name.EndsWith("Controller"))
                    .EnableClassInterceptors()
                    .AddLogInterceptor();

   // Or for MediatR handlers
    containerBuilder.RegisterAssemblyTypes(assembly)
                    .AsClosedTypesOf(typeof(IRequestHandler<,>))
                    .AsImplementedInterfaces()
                    .EnableInterfaceInterceptors()
                    .AddLogInterceptor()
                    .InstancePerDependency();
});

var app = builder.Build();
app.Run();

Note: Since TLog uses AutofacServiceProviderFactory, ensure your application is configured to use Autofac. The AddTLog method handles UseServiceProviderFactory for you.

Usage

Automatic Logging

Once registered with .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.

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.LogInformation("Processing started", nameof(Process));
            // ...
        }
        catch(Exception ex)
        {
            _logger.LogException(ex, nameof(Process));
        }
    }
}
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
1.0.9 408 11/28/2025
1.0.8 346 10/13/2025
1.0.7 222 10/9/2025
1.0.4 460 6/12/2024