Appouse.RequestLogging 1.4.3

There is a newer version of this package available.
See the version list below for details.
dotnet add package Appouse.RequestLogging --version 1.4.3
                    
NuGet\Install-Package Appouse.RequestLogging -Version 1.4.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="Appouse.RequestLogging" Version="1.4.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Appouse.RequestLogging" Version="1.4.3" />
                    
Directory.Packages.props
<PackageReference Include="Appouse.RequestLogging" />
                    
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 Appouse.RequestLogging --version 1.4.3
                    
#r "nuget: Appouse.RequestLogging, 1.4.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 Appouse.RequestLogging@1.4.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=Appouse.RequestLogging&version=1.4.3
                    
Install as a Cake Addin
#tool nuget:?package=Appouse.RequestLogging&version=1.4.3
                    
Install as a Cake Tool

Appouse.RequestLogging

NuGet

HTTP istek/yanıt loglama, korelasyon, aktif istek takibi ve istek iptal yönetimi kütüphanesi.

Özellikler

  • 🔍 Request/Response Loglama — Header, body, durum kodu, süre, hata bilgisi
  • 🔗 Correlation/Trace — X-Correlation-ID, OpenTelemetry TraceId/SpanId
  • 🐳 K8s Desteği — Pod, Namespace, Node, Container bilgileri otomatik
  • 📦 Arşivleme — Günlük/aylık/yıllık arşiv tablosu desteği
  • 🚫 İstek İptali — Aktif istekleri takip edip dışarıdan cancel edebilme
  • 🧩 Pluggable Store — InMemory veya Redis ile aktif istek takibi
  • 🗄️ Çoklu DB — PostgreSQL, SQL Server, MySQL, Oracle

Kurulum

dotnet add package Appouse.RequestLogging

Temel Kullanım

// Program.cs / Startup.cs
var cs = "Host=127.0.0.1;Username=app;Password=***;Database=logs";
var writer = new ChannelLogWriter(new PostgresLogWriter(cs));

services.AddRequestLogging(new RequestLoggingOptions
{
    Application = "Portal",
    Environment = "Prod",
    Writer = writer,

    // Properties – opsiyonel provider(lar)
    PropertyProviders = { ctx => new[] {
        new KeyValuePair<string,string>("appVersion","1.2.3"),
        new KeyValuePair<string,string>("region","eu-central")
    }},

    // Arşivleme
    EnableArchiver = true,
    ArchiveMode = ArchiveMode.Daily,          // Never/Daily/Monthly/Yearly
    HotRetention = TimeSpan.FromDays(7),      // aktif tabloda 7 gün kalsın
    ArchiveInterval = TimeSpan.FromMinutes(5),
    ArchiveBatchSize = 5000,
    ArchiveStore = new PostgresArchiveStore(cs)
});

// Middleware
app.UseRequestLogging();

Diğer DB'ler için sadece PostgresLogWriter yerine SqlServerLogWriter / OracleLogWriter / MySqlLogWriter verebilirsiniz. Aynı şekilde arşivleme tarafında da ilgili ArchiveStore sınıflarını kullanabilirsiniz.


Aktif İstek Takibi ve İptal Yönetimi

Aktif istekleri takip edip dışarıdan (admin panel, API) cancel edebilirsiniz. TraceIdentifier ile tanımlanan her istek, store'a kaydedilir ve istendiğinde iptal edilebilir.

InMemory (tek instance)

services.AddRequestLogging(new RequestLoggingOptions
{
    Application = "MyApp",
    Writer = writer,
    ActiveRequestStore = new InMemoryActiveRequestStore(),
    CancelCheckInterval = TimeSpan.FromSeconds(2)
});

Redis (dağıtık / multi-pod)

var redis = ConnectionMultiplexer.Connect("localhost:6379");

services.AddRequestLogging(new RequestLoggingOptions
{
    Application = "MyApp",
    Writer = writer,
    ActiveRequestStore = new RedisActiveRequestStore(redis, ttl: TimeSpan.FromHours(1)),
    CancelCheckInterval = TimeSpan.FromSeconds(1)
});

Aktif İstekler ve İptal API'si

[ApiController]
[Route("api/admin/requests")]
public class RequestManagementController : ControllerBase
{
    private readonly IActiveRequestStore _store;

    public RequestManagementController(IActiveRequestStore store) => _store = store;

    /// <summary>
    /// Şu an aktif olan istekleri listeler.
    /// </summary>
    [HttpGet("active")]
    public async Task<IActionResult> GetActiveRequests()
    {
        var list = await _store.GetActiveRequestsAsync();
        return Ok(list);
    }

    /// <summary>
    /// Belirtilen isteği iptal eder.
    /// </summary>
    [HttpPost("cancel/{traceId}")]
    public async Task<IActionResult> CancelRequest(string traceId)
    {
        var result = await _store.RequestCancelAsync(traceId);
        return result ? Ok(new { message = "İptal sinyali gönderildi." })
                      : NotFound(new { message = "Aktif istek bulunamadı." });
    }
}

ActiveRequestEntry Alanları

Alan Tip Açıklama
TraceIdentifier string HTTP istek tanımlayıcısı (cancel için anahtar)
CorrelationId string? X-Correlation-ID
TraceId / SpanId string? OpenTelemetry izleme kimlikleri
Scheme string? http / https
Host / Port string? / int? Hedef host bilgisi
Method string? HTTP metodu (GET, POST, vb.)
Path string? İstek yolu
RouteTemplate string? MVC route pattern (ör: api/users/{id})
QueryString string? URL sorgu parametreleri
RequestContentType string? İçerik tipi
RequestContentLength long? Body boyutu
ClientIp string? İstemci IP adresi
ClientUserAgent string? Tarayıcı / istemci bilgisi
StartedAt DateTimeOffset İstek başlangıç zamanı
ElapsedMs long Geçen süre (ms, hesaplanmış)
Application string? Uygulama adı
Environment string? Ortam (Prod, Staging, vb.)
MachineId string? Makine kimliği
PodName string? Kubernetes pod adı
IsCancelRequested bool İptal istendi mi?
CancelRequestedAt DateTimeOffset? İptal istek zamanı

Nasıl Çalışır?

  1. İstek geldiğinde middleware ActiveRequestStore.RegisterAsync() ile kaydeder
  2. Arka planda periyodik olarak (CancelCheckInterval) cancel kontrolü yapar
  3. Admin RequestCancelAsync(traceId) çağırdığında sinyal store'a yazılır
  4. Polling döngüsü sinyali yakalar → CancellationToken iptal edilir → pipeline durur
  5. Log kaydına IsCancelled=true, CancelRequestTime yazılır, HTTP 499 döner
  6. İstek bittiğinde UnregisterAsync() ile listeden çıkar

Correlation / TraceId

  • İstek header'ında X-Correlation-ID varsa korunur, yoksa oluşturulup yanıta da eklenir.
  • IHttpClientFactory ile oluşturulan HttpClient'lere CorrelationHandler otomatik eklenir.
  • Mikroservisler arası Correlation ID yayılımı otomatiktir.
// IHttpClientFactory ile kullanım (CorrelationHandler otomatik eklenir)
var client = httpClientFactory.CreateClient("MyApiClient");
var response = await client.GetAsync("https://api.hedef.com/endpoint");

Attribute Kullanım Örneği

[LogFlatten]
public class LoginRequest
{
    public string UserName { get; set; }
    [LogMask("******", keepLast:2)] public string Password { get; set; }
    [LogIgnore] public byte[]? AvatarBytes { get; set; }
    [LogRename("phone")] public string? PhoneNumber { get; set; }
}

Custom Property Ekleme

RequestLogProperties.Add(HttpContext, "orderId", orderId.ToString());
RequestLogProperties.Add(HttpContext, "featureFlag", flag);

DB Desteği

Veritabanı Writer ArchiveStore
PostgreSQL PostgresLogWriter PostgresArchiveStore
SQL Server SqlServerLogWriter SqlServerArchiveStore
MySQL MySqlLogWriter MySqlArchiveStore
Oracle OracleLogWriter OracleArchiveStore

İpuçları

  • K8s'de HOSTNAME genelde pod adıdır. KUBERNETES_* env değişkenlerini Downward API ile enjekte edip otomatik toplanır.
  • Büyük gövde/loglarda sadece hash tutup *_preview kolonlarını boş bırakabilirsiniz.
  • Yetki/çerez gibi header'lar MaskHeaders ile otomatik maske edilir.
  • Performans için writer'ı ChannelLogWriter ile sarmalayın.
  • ActiveRequestStore = null ise aktif istek takibi ve iptal özelliği devre dışıdır (varsayılan).
  • Retention için ayrı bir cron job ile DELETE FROM request_log_archive WHERE timestamp_utc < now() - interval '30 days' benzeri bir temizlik çalıştırın. Log tablosu 7 gün, arşiv tablosu 1 ay tutabilir. Cron job arşiv tablosundan eski kayıtları siler.

Paketleme

# Otomatik versiyon artırım + NuGet paketi oluşturma
.\pack.bat

.\pack.bat                      # varsayılan: --patch  (1.4.2 → 1.4.3)
.\pack.bat --patch              # sadece patch          (1.4.2 → 1.4.3)
.\pack.bat --minor              # sadece minor          (1.4.2 → 1.5.2)
.\pack.bat --major              # sadece major          (1.4.2 → 2.4.2)
.\pack.bat --major --minor      # ikisi birden          (1.4.2 → 2.5.2)
.\pack.bat --minor --patch      # ikisi birden          (1.4.2 → 1.5.3)
.\pack.bat --major --minor --patch  # hepsi             (1.4.2 → 2.5.3)


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 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. 
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.5.3 129 4/13/2026
1.4.3 121 4/11/2026