Aiursoft.ClickhouseLoggerProvider 10.0.16

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

Aiursoft ClickHouse SDK & Logger Provider

MIT licensed Pipeline stat Test Coverage NuGet version (Aiursoft.ClickhouseSdk) Man hours

A high-performance, textbook-grade ClickHouse integration suite for .NET applications. It provides an effortless way to interact with ClickHouse using a "DbContext" style pattern and a high-performance logging provider for the standard Microsoft.Extensions.Logging infrastructure.

Why Aiursoft.ClickhouseSdk?

ClickHouse is a column-oriented database that excels at analytical processing but requires specific patterns for optimal performance (e.g., bulk writes instead of single-row inserts). This SDK abstracts these complexities:

  1. Buffered Bulk Writing: Automatically buffers entities and uses ClickHouseBulkCopy for massive throughput.
  2. Automatic Schema Management: No need to manually create tables or databases. The SDK handles it on startup.
  3. Schema Evolution: Automatically detects and adds missing columns to your tables as your data models evolve.
  4. Resilient Logging: A specialized ILogger provider that won't block your application during log flushes.

Installation

You can install the core SDK or the logger provider via NuGet:

# Core SDK for database interaction
dotnet add package Aiursoft.ClickhouseSdk

# Specialized logger provider
dotnet add package Aiursoft.ClickhouseLoggerProvider

Configuration

Both projects share a common configuration structure. You can configure them via appsettings.json:

{
  "Clickhouse": {
    "ConnectionString": "Host=localhost;Protocol=http;Port=8123;Database=MyBusinessDb;User=default;Password=password",
    "Enabled": true,
    "TableName": "AppLogs" 
  }
}
  • ConnectionString: Standard ClickHouse connection string.
  • Enabled: Global switch to enable/disable ClickHouse features.
  • TableName: Used by the Logger Provider to specify the target log table.

Project 1: Aiursoft.ClickhouseSdk (Core)

The core SDK provides the base infrastructure for high-performance ClickHouse communication.

1. Define your Entity

Create a POCO class that matches your table schema.

public class MyEntity
{
    public Guid Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int Value { get; set; }
    public DateTime CreatedAt { get; set; }
}

2. Create your DbContext

Inherit from ClickhouseDbContext. Use ClickhouseSet<T> to define your tables.

using Aiursoft.ClickhouseSdk;
using Aiursoft.ClickhouseSdk.Abstractions;

public class MyDbContext : ClickhouseDbContext
{
    public ClickhouseSet<MyEntity> MyEntities { get; }

    public MyDbContext(IOptionsMonitor<ClickhouseOptions> options) : base(options)
    {
        // Parameter 1: Connection factory (inherited from ClickhouseDbContext)
        // Parameter 2: Table Name
        // Parameter 3: Mapper (converts your object to an object array for ClickHouse)
        MyEntities = new ClickhouseSet<MyEntity>(GetConnection, "MyBusinessTable", entity => new object[] 
        {
            entity.Id,
            entity.Name,
            entity.Value,
            entity.CreatedAt
        });
    }

    public override async Task SaveChangesAsync()
    {
        // Flush all buffered entities in this set
        await MyEntities.SaveChangesAsync();
    }
}

3. Registration and Initialization

Register your context in Program.cs and initialize the schema.

var builder = Host.CreateApplicationBuilder(args);

// 1. Bind configuration
builder.Services.Configure<ClickhouseOptions>(builder.Configuration.GetSection("Clickhouse"));

// 2. Register DbContext
builder.Services.AddSingleton<MyDbContext>();

using var host = builder.Build();

// 3. Initialize the table schema on startup
// This ensures the DB and table exist, and columns match your entity properties.
await host.Services.InitClickhouseTableAsync<MyEntity>("MyBusinessTable", "CreatedAt"); 

await host.RunAsync();

4. Basic Operations

public class MyService(MyDbContext dbContext)
{
    public async Task ProcessData()
    {
        // Add to local buffer (non-blocking)
        dbContext.MyEntities.Add(new MyEntity 
        { 
            Id = Guid.NewGuid(), 
            Name = "Sample", 
            Value = 100, 
            CreatedAt = DateTime.UtcNow 
        });

        // Bulk upload all buffered entities to ClickHouse
        await dbContext.SaveChangesAsync();
    }
}

Project 2: Aiursoft.ClickhouseLoggerProvider

A high-performance provider that redirects ILogger output to ClickHouse. It uses an internal buffer and background worker to ensure logging doesn't slow down your request pipeline.

1. Registration

Add the provider to your logging configuration.

builder.Logging.AddClickhouse(options => 
{
    builder.Configuration.GetSection("Clickhouse").Bind(options);
});

2. Initialization

Initialize the logging table at startup.

// This creates the 'AppLogs' table (defined in TableName config) 
// using 'EventTime' as the primary sort key.
await host.Services.InitLoggingTableAsync();

3. Usage

Simply use the standard ILogger interface.

public class MyService(ILogger<MyService> logger)
{
    public void DoWork()
    {
        logger.LogInformation("Work started at {Time}", DateTime.UtcNow);
        try 
        {
             // ...
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "An error occurred!");
        }
    }
}

Advanced Details

Schema Evolution

The InitClickhouseTableAsync<T> method performs the following:

  1. Database Creation: CREATE DATABASE IF NOT EXISTS.
  2. Table Creation: CREATE TABLE IF NOT EXISTS using the MergeTree engine.
  3. Column Alignment: For every property in your entity T, it executes ALTER TABLE ... ADD COLUMN IF NOT EXISTS. This means you can add new properties to your C# class, and the SDK will automatically add the corresponding columns in ClickHouse on the next application start.

Data Types Mapping

The SDK automatically maps C# types to ClickHouse types:

  • stringString
  • intInt32
  • DateTimeDateTime
  • GuidUUID
  • boolUInt8

Performance Note

ClickHouse prefers large batch writes. While ClickhouseSet<T>.Add() is extremely fast (just adds to a local list), calling SaveChangesAsync() frequently with few items can be inefficient for ClickHouse. It is recommended to call SaveChangesAsync() periodically or after a significant number of items have been added.

The ClickhouseLoggerProvider handles this automatically by flushing logs in the background every few seconds.


How to Contribute

We welcome contributions! Please follow these steps:

  1. Fork the repository.
  2. Create a feature branch.
  3. Ensure all code passes lint.sh and all tests pass.
  4. Submit a Pull Request.

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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 (2)

Showing the top 2 NuGet packages that depend on Aiursoft.ClickhouseLoggerProvider:

Package Downloads
Aiursoft.ClickhouseSample

Package Description

Aiursoft.Translate

Nuget package of 'Translate' provided by Aiursoft

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.0.16 215 3/29/2026
10.0.13 79 3/29/2026
10.0.11 80 3/29/2026
10.0.10 82 3/26/2026
10.0.8 72 3/26/2026
10.0.6 86 3/26/2026