C# / .NET
Complete integration guide for ImmutableLog in C# / .NET. Automatic middleware for ASP.NET Core and Minimal API, or a typed HttpClient client for workers, BackgroundServices, and jobs. Sending is async and does not block the response.
Middlewares
Automatic integration via middleware in the ASP.NET Core pipeline, every HTTP request is captured without modifying any controller or endpoint. Click the framework to see the complete code.
Middleware via IMiddleware with InvokeAsync(HttpContext). Captures Response.StatusCode after next and sends the event asynchronously.
public async Task InvokeAsync(HttpContext ctx, RequestDelegate next)
{
var sw = Stopwatch.StartNew();
await next(ctx);
_ = EmitAsync(ctx, ctx.Response.StatusCode, sw.Elapsed);
}View full documentation →
Same middleware registered with app.UseMiddleware<>(). Set event and trail per endpoint via HttpContext.Items.
app.UseMiddleware<ImmutableLogMiddleware>();
app.MapPost("/payments", (HttpContext ctx) =>
{
ctx.Items["imtbl.eventName"] = "payment.created";
return Results.Ok();
});View full documentation →
Typed HttpClient client
Use ImmutableLogClient to send events directly to ImmutableLog without depending on the web pipeline. Ideal for workers, BackgroundService, queue consumers, and any .NET code that needs to record events.
// ImmutableLogClient.cs
using System.Net.Http.Json;
using System.Text.Json;
public sealed class ImmutableLogClient
{
private readonly HttpClient _http;
private readonly string _apiKey;
private readonly string _service;
private readonly string _env;
public ImmutableLogClient(HttpClient http, string apiKey, string service, string env)
{
_http = http;
_apiKey = apiKey;
_service = service;
_env = env;
}
public async Task SendEventAsync(
string eventName,
string kind, // "success" | "info" | "error"
object payload,
string? immutableTrail = null,
CancellationToken ct = default)
{
var requestId = Guid.NewGuid().ToString();
var trail = SanitizeTrail(immutableTrail);
// Todos os valores de meta precisam ser strings.
var meta = new Dictionary<string, string>
{
["type"] = kind,
["event_name"] = eventName,
["service"] = _service,
["request_id"] = requestId,
["env"] = _env,
};
if (trail is not null) meta["immutable_trail"] = trail;
var body = new
{
payload = JsonSerializer.Serialize(payload),
meta,
};
using var req = new HttpRequestMessage(HttpMethod.Post, "/v1/events")
{
Content = JsonContent.Create(body),
};
req.Headers.Add("Authorization", $"Bearer {_apiKey}");
// Idempotency-Key e OBRIGATORIO (sem ele a API responde 400).
req.Headers.Add("Idempotency-Key", $"{eventName}-{requestId}");
req.Headers.Add("Request-Id", requestId);
// Timezone do cliente - usado pelo dashboard para exibir os timestamps.
req.Headers.Add("X-Client-TZ", "America/Sao_Paulo");
req.Headers.Add("X-Client-Offset-Minutes", "-180");
if (trail is not null) req.Headers.Add("X-Imtbl-Trail", trail);
using var res = await _http.SendAsync(req, ct);
res.EnsureSuccessStatusCode();
}
// Normaliza o immutable_trail (trim, nao-vazio, max 256, sem ':').
// O servidor responde 400 invalid_immutable_trail se a regra for violada.
public static string? SanitizeTrail(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return null;
var v = value.Trim().Replace(":", "-");
if (v.Length > 256) v = v[..256];
return v;
}
}
// Program.cs - registro via IHttpClientFactory (typed client)
builder.Services.AddHttpClient("immutablelog", c =>
{
c.BaseAddress = new Uri(
Environment.GetEnvironmentVariable("IMTBL_URL") ?? "https://api.immutablelog.com");
c.Timeout = TimeSpan.FromSeconds(5);
});
builder.Services.AddSingleton(sp =>
{
var http = sp.GetRequiredService<IHttpClientFactory>().CreateClient("immutablelog");
return new ImmutableLogClient(http,
Environment.GetEnvironmentVariable("IMTBL_API_KEY") ?? "",
"my-service", "production");
});
// Uso (fire-and-forget - descarta a Task; capture exceções se precisar):
// _ = client.SendEventAsync("user.created", "success",
// new { user_id = "usr_123", plan = "pro" }, immutableTrail: "order-7782");Use IHttpClientFactory to reuse connections. For fire-and-forget, discard the Task with _ = ...; wrap in try/catch if you want to handle send failures.
Retry with exponential backoff
For high-availability production, add retry with exponential backoff. ImmutableLog returns 202 on success and 200 on an idempotent duplicate. Never retry on 429 (monthly limit reached).
// Retry em erros transitorios (nunca em 429).
public async Task SendWithRetryAsync(
string eventName, string kind, object payload,
string? trail = null, int maxAttempts = 3, CancellationToken ct = default)
{
var delay = TimeSpan.FromMilliseconds(500);
for (var attempt = 0; attempt < maxAttempts; attempt++)
{
try
{
await SendEventAsync(eventName, kind, payload, trail, ct);
return;
}
catch (HttpRequestException ex) when (ex.StatusCode == (System.Net.HttpStatusCode)429)
{
// 429 = limite mensal - nao fazer retry.
return;
}
catch (HttpRequestException) when (attempt + 1 < maxAttempts)
{
await Task.Delay(delay, ct);
delay *= 2; // 500ms -> 1s -> 2s
}
}
}Sensitive data hashing
Never send raw personal data (email, CPF, IP) to ImmutableLog. Use SHA-256 to generate a deterministic digest, traceable without exposing the original data.
using System.Security.Cryptography;
using System.Text;
// Faz o hash de dados sensiveis antes de enviar - nunca logue PII bruto.
static string Sha256Hex(string data)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(data));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
// Uso no payload do evento:
var payload = new
{
user_id = "usr_123",
email_hash = Sha256Hex("user@example.com"),
ip_hash = Sha256Hex("192.168.1.1"),
};meta fields
Beyond the payload, the meta object carries the fields the SIEM uses to normalize (ECS) and enrich the event. All meta values are strings.
| Field in meta | What it does in the SIEM |
|---|---|
event_name | The event label (e.g. http.GET.auth-me-user, Payment error), the identifier shown in the listing. Becomes event.action and derives event.category (e.g. a name with login → authentication). |
client_ip | Becomes source.ip with maximum precedence and provenance client_asserted. It is the only meta field that becomes source.ip. It must be a plain IP, without a port. See the section below. |
immutable_trail | Becomes imtbl.immutable_trail, which groups related events for investigation (e.g. one order, one user). |
type | Event severity: error / warning / info / success. Colors the badge in the listing. (event_type is accepted as a synonym.) |
http_method, http_status, http_route, log_level, environment, error_type, error_message | Sent by the middlewares, always as a string (including http_status, e.g. "200"). error_type and error_message only exist when there is an error. |
service, env, request_id | Metadata: indexed and queryable in the dashboard (search/filters). |
client_ip: end-user IP
The problem it solves
Between the browser and the core there are proxies/ALB. The IP the core sees on the connection is the previous hop (the client's backend or an AWS proxy), not the user's. Without action, source.ip would be the proxy IP, useless for geo, threat and IP-based detection. (Real example: XFF arrived as 44.192.13.3 (AWS) while the user was 179.110.4.205.)
The solution
The client's backend is the only one that sees the browser's real IP, so it forwards that IP in meta.client_ip when calling POST /v1/events.
How the SIEM handles it
- Validates it is an IP (v4/v6). A non-IP value is ignored, without dropping the event. An IP with a port (e.g.
1.2.3.4:5678) is also silently discarded. - Writes to
source.ipwith maximum precedence (see order below). - Stamps
imtbl.source_ip_origin = "client_asserted"; the UI shows the “User IP” badge. - Feeds GeoIP, threat intel and IP-based detection rules.
client_ipX-Forwarded-For (1º hop)X-Real-IPconnection IPProvenance and trust
client_ip is asserted by the tenant: the client's backend claims the IP, and it can be forged by whoever controls that backend. However it stays contained within the tenant (it never crosses another tenant's boundary). A threat/geo hit on a client_asserted value is a claim, not an edge observation.
How to obtain the IP in your backend
Try the candidates in order: the first IP from X-Forwarded-For (closest to the user), then X-Real-IP (if your proxy sets it) and finally the connection IP. Each candidate goes through a function that strips the port (1.2.3.4:5678, [2001:db8::1]:8080) and the brackets and checks that it is a real IP, without any DNS lookup. An invalid value (garbage, localhost, an IPv6 zone such as fe80::1%eth0) is ignored and the next candidate is tried. Send a plain IP, without a port, and if no candidate is a valid IP omit the client_ip key (meta does not accept null, and never send “unknown”).
Only behind a trusted proxy: reading the first IP from X-Forwarded-For is only safe when a trusted proxy or ALB sits in front of the application and overwrites or appends the header. Without a proxy, the client controls the header and can forge the IP, and the SIEM will promote that value to source.ip.
using System.Net;
static string? BareIp(string? value)
{
var v = (value ?? "").Trim();
if (v.StartsWith('['))
{
var end = v.IndexOf(']');
if (end < 0) return null;
var rest = v[(end + 1)..];
if (rest.Length > 0 && !(rest.Length > 1 && rest[0] == ':' && rest[1..].All(char.IsAsciiDigit))) return null;
v = v[1..end];
}
else if (v.Count(c => c == ':') == 1)
{
v = v[..v.IndexOf(':')]; // 1.2.3.4:5678 -> 1.2.3.4
}
// TryParse aceita formas curtas ("1" vira 0.0.0.1): exija 4 octetos ou um IPv6 (com ':').
if (v.Contains('%') || !IPAddress.TryParse(v, out var ip)) return null;
if (!v.Contains(':') && v.Count(c => c == '.') != 3) return null;
if (ip.IsIPv4MappedToIPv6) ip = ip.MapToIPv4(); // ::ffff:1.2.3.4 -> 1.2.3.4
return ip.ToString();
}
// Candidatos na ordem: 1o item do X-Forwarded-For, X-Real-IP, IP de conexao.
static string? ClientIp(HttpContext ctx)
{
var xff = ctx.Request.Headers["X-Forwarded-For"].ToString();
if (xff.Length > 0 && BareIp(xff.Split(',')[0]) is { } fromXff) return fromXff;
if (BareIp(ctx.Request.Headers["X-Real-IP"].ToString()) is { } fromXri) return fromXri;
return BareIp(ctx.Connection.RemoteIpAddress?.ToString());
}
var meta = new Dictionary<string, string> { ["event_name"] = "user.login" };
if (ClientIp(ctx) is { } ip)
meta["client_ip"] = ip; // sem IP valido, omita a chave (nunca "unknown")Payload example
{
"payload": "{\"user\":\"bob\",\"action\":\"login\"}",
"meta": {
"event_name": "user.login",
"client_ip": "179.110.4.205",
"immutable_trail": "user-bob"
}
}PII note: client_ip is PII and gets sealed into the immutable block (permanent). Decide consciously between forensic evidence and “right to be forgotten” before sending it.
This documentation reflects the current API behavior. For questions or advanced integrations, contact the support team.
