TAF.Kibana.SDK
1.5.0
dotnet add package TAF.Kibana.SDK --version 1.5.0
NuGet\Install-Package TAF.Kibana.SDK -Version 1.5.0
<PackageReference Include="TAF.Kibana.SDK" Version="1.5.0" />
<PackageVersion Include="TAF.Kibana.SDK" Version="1.5.0" />Directory.Packages.props
<PackageReference Include="TAF.Kibana.SDK" />Project file
paket add TAF.Kibana.SDK --version 1.5.0
#r "nuget: TAF.Kibana.SDK, 1.5.0"
#:package TAF.Kibana.SDK@1.5.0
#addin nuget:?package=TAF.Kibana.SDK&version=1.5.0Install as a Cake Addin
#tool nuget:?package=TAF.Kibana.SDK&version=1.5.0Install as a Cake Tool
TAF Kibana SDK
Official .NET SDK for TAF Kibana logging and analytics platform. Provides a fluent API for log management, searching, metrics, and real-time monitoring.
Installation
dotnet add package TAF.Kibana.SDK
Quick Start
Configuration
Add to your appsettings.json:
{
"KibanaClient": {
"BaseUrl": "https://your-kibana-instance.com/api",
"ApiKey": "your-api-key",
"TimeoutSeconds": 30,
"MaxRetryAttempts": 3,
"BulkBatchSize": 1000
}
}
Dependency Injection
using TAF.Kibana.SDK.Extensions;
// In Program.cs or Startup.cs
services.AddTafKibanaClient(Configuration);
// Or with inline configuration
services.AddTafKibanaClient(options =>
{
options.BaseUrl = "https://your-kibana-instance.com/api";
options.ApiKey = "your-api-key";
});
Usage Examples
Basic Usage
public class LoggingService
{
private readonly ITafKibanaClient _kibanaClient;
public LoggingService(ITafKibanaClient kibanaClient)
{
_kibanaClient = kibanaClient;
}
public async Task LogEventAsync()
{
// Write a log entry
await _kibanaClient.Logs.WriteAsync(new LogEntry
{
Level = "Information",
Message = "User logged in",
TenantId = tenantId,
ApplicationId = appId
});
}
}
Fluent Search API
// Search for error logs in the last 24 hours
var results = await _kibanaClient.Query()
.ForTenant(tenantId)
.InLastHours(24)
.WithLogLevel("Error", "Critical")
.ContainingText("database connection")
.OrderBy(x => x.Timestamp, SortDirection.Descending)
.Take(100)
.ExecuteAsync<LogEntry>();
// Stream large result sets
await foreach (var log in _kibanaClient.Query()
.ForTenant(tenantId)
.InDateRange(startDate, endDate)
.StreamAsync<LogEntry>())
{
ProcessLog(log);
}
Aggregations and Analytics
// Get log statistics with aggregations
var stats = await _kibanaClient.Query()
.ForTenant(tenantId)
.InLastDays(7)
.WithAggregation(agg => agg
.Terms("by_level", "level", size: 10)
.DateHistogram("over_time", "timestamp", "1h")
.Average("avg_response", "responseTime"))
.ExecuteAsync<LogEntry>();
// Get metrics
var metrics = await _kibanaClient.Metrics.GetTimeSeriesAsync(
metric: "response_time",
from: DateTime.UtcNow.AddDays(-7),
to: DateTime.UtcNow,
interval: "1h");
Bulk Operations
// Bulk indexing with fluent API
var result = await _kibanaClient.Bulk()
.IndexMany(logEntries)
.WithBatchSize(500)
.ContinueOnError(true)
.WithRefresh(RefreshPolicy.WaitFor)
.ExecuteAsync();
Console.WriteLine($"Indexed {result.SuccessfulOperations} of {result.TotalOperations} documents");
Real-time Monitoring
// Subscribe to real-time log stream
var subscription = await _kibanaClient.Realtime.SubscribeToLogsAsync(
filter: query => query
.ForTenant(tenantId)
.WithLogLevel("Error"),
onEvent: logEvent =>
{
Console.WriteLine($"New error: {logEvent.Message}");
});
// Tail logs
await foreach (var log in _kibanaClient.Realtime.TailLogsAsync(
filter: q => q.ForTenant(tenantId),
initialLines: 100))
{
Console.WriteLine($"[{log.Timestamp}] {log.Level}: {log.Message}");
}
Alert Management
// Create alert rule
var rule = await _kibanaClient.Alerts.CreateRuleAsync(new AlertRuleDefinition
{
Name = "High Error Rate",
Description = "Alert when error rate exceeds threshold",
TenantId = tenantId,
Severity = AlertSeverity.High,
CheckInterval = TimeSpan.FromMinutes(5),
Condition = new AlertCondition
{
Type = AlertConditionType.Query,
Query = q => q.WithLogLevel("Error"),
Operator = ComparisonOperator.GreaterThan,
Threshold = 100,
TimeWindow = TimeSpan.FromMinutes(5)
},
NotificationChannels = new[] { "email", "slack" }
});
// Get alert history
var alerts = await _kibanaClient.Alerts.GetAlertHistoryAsync(
ruleId: rule.Id,
from: DateTime.UtcNow.AddDays(-7));
Advanced Queries
// Complex field queries with expressions
var results = await _kibanaClient.Query()
.ForTenant(tenantId)
.Where<LogEntry>(x => x.Level == "Error" && x.ResponseTime > 1000)
.WhereField("environment", SearchOperator.In, new[] { "production", "staging" })
.WhereField("statusCode", SearchOperator.Between, new { from = 400, to = 599 })
.WithHighlighting("message", "stackTrace")
.WithCaching(TimeSpan.FromMinutes(5))
.ExecuteAsync<LogEntry>();
// Export search results
var export = await _kibanaClient.Search.ExportAsync(
request: queryBuilder.Build(),
format: ExportFormat.Csv);
File.WriteAllBytes("logs.csv", export.Data);
Features
- Fluent API: Intuitive query building with IntelliSense support
- Resilience: Built-in retry policies and circuit breaker patterns
- Streaming: IAsyncEnumerable support for processing large datasets
- Real-time: WebSocket-based real-time log streaming and monitoring
- Bulk Operations: Efficient bulk indexing with progress tracking
- Caching: Query result caching for improved performance
- Type Safety: Strongly-typed API with generic support
- Compression: Automatic request/response compression
- Health Checks: Built-in health check support
Configuration Options
| Option | Description | Default |
|---|---|---|
| BaseUrl | Kibana API base URL | https://localhost:44356/ |
| ApiKey | API key for authentication | - |
| TimeoutSeconds | Request timeout in seconds | 30 |
| MaxRetryAttempts | Maximum retry attempts | 3 |
| RetryDelayMilliseconds | Delay between retries | 1000 |
| EnableLogging | Enable debug logging | false |
| BulkBatchSize | Batch size for bulk operations | 1000 |
| EnableCompression | Enable request compression | true |
| CircuitBreakerThreshold | Circuit breaker threshold | 5 |
| CircuitBreakerTimeoutSeconds | Circuit breaker timeout | 60 |
Advanced Configuration
Custom HTTP Client
services.AddTafKibanaClientWithCustomHttp(
options => options.BaseUrl = "https://api.example.com",
httpBuilder => httpBuilder
.AddHttpMessageHandler<CustomAuthHandler>()
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
Proxy = new WebProxy("http://proxy:8080")
}));
With Health Checks
services.AddTafKibanaClientWithHealthChecks(Configuration);
// In health check endpoint
app.MapHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
License
MIT
Support
For issues and feature requests, please contact the TechAppForce development team.
| Product | Versions 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. |
-
net8.0
- Microsoft.Extensions.Configuration.Abstractions (>= 9.0.8)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Http.Polly (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.3)
- Microsoft.Extensions.Options (>= 8.0.0)
- Polly (>= 8.0.0)
- Polly.Extensions.Http (>= 3.0.0)
- System.Text.Json (>= 9.0.8)
- TAF.Infra.Contract (>= 1.11.5)
- TAF.Infra.MassTransit (>= 2.2.21)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on TAF.Kibana.SDK:
| Package | Downloads |
|---|---|
|
TAF.Kibana.SDK.Serilog
Serilog sink that ships log events to TAF Kibana via the TAF.Kibana.SDK. Version 1.5.5 closes a gap where HttpRequestAuditMiddleware audit docs were silently dropped when Kibana was down. RequestAuditEmitter now appends the LogEntry to the shared IDiskBuffer on WriteAsync failure (or exception) â€" the sink's existing drain loop replays the doc once Kibana is reachable again. Buffer dependency is optional: the emitter falls back to a LogWarning if IDiskBuffer is not registered (i.e. AddTafHttpRequestAudit used without AddTafKibanaSerilog). Version 1.5.4 merges dev-branch DiskBuffer hardening into the 1.5.x audit-middleware lineage: DrainAsync now tracks attempts in an in-memory dictionary keyed by line content (instead of a counter persisted on each BufferedBatch) so eviction-during-drain no longer resurrects evicted lines from a stale snapshot, the write-back step re-reads the current file under the gate, and the per-line poison cap (KibanaSinkDefaults.MaxBufferReplayAttempts = 5) drops permanently-rejected payloads after the threshold. Attempt counters are pruned at the end of each drain to bound memory growth. The 1.5.x feature surface (audit middleware, IRequestSnapshotBuilder/IRequestAuditEmitter split, IBusContextProvider, HttpLoggingEnricherMiddleware) is preserved. Version 1.5.3 cleans up the audit feature internals â€" splits HttpRequestAuditMiddleware into IRequestSnapshotBuilder (HTTP context interpretation) and IRequestAuditEmitter (Kibana dispatch), with payload-to-LogEntry mapping in RequestAuditLogEntryMapper. Adds CorrelationId to audit doc Properties (read from X-Correlation-ID response header). Now uses IBusContextProvider for BusContext resolution (DIP). Version 1.5.1 added HttpRequestAuditMiddleware: emits ONE audit document per HTTP request directly via IKibanaClient.Logs.WriteAsync, bypassing Serilog so request body, response body, query string, status code, and elapsed time land in the same ES document. Register with AddTafHttpRequestAudit / UseTafHttpRequestAudit. The original HttpLoggingEnricherMiddleware remains for LogContext enrichment of internal trace logs. Version 1.4.0 added HttpLoggingEnricherMiddleware that captures the HTTP query string, request body, and response body as Serilog properties. Includes a RedactResponseBody hook so consumers can drop heavy fields from read-style responses (e.g. CRUD's /select empties the top-level result array before logging). Provides batched delivery, disk-buffer resilience, secret scrubbing, and BusContext-aware tenant routing. |
GitHub repositories
This package is not used by any popular GitHub repositories.