# Introduction

Ship logs from your apps and backend into one central panel. Two ways to log: **automatic request logging** with one line of middleware, and **manual event logging** where you call the SDK yourself.

pinqloq is a logging service.

You only need a pinqloq account and a secret key to get started.

The SDK runs inside your backend and sends your logs to the panel. There are SDKs for **.NET**, **Node.js** (Express), **Go** (`net/http`), and **Ruby** (Rack). They share one wire protocol and one feature set, with an idiomatic API on each side. The worked examples further down use .NET names (`AddPinqloq`, `PinqloqLogEntry`, `Enqueue`); the **SDKs** section below gives the equivalent for each language, and the mapping is consistent (`enqueue`, `requestLogging`/`RequestLogging`/`Rack::RequestLogging`, `deviceIdentifier`/`DeviceIdentifier`/`device_identifier`, and so on).

## SDKs

Pick the SDK that matches your backend. The concepts (client, request-logging middleware, manual `enqueue`, buffered batched delivery, name- or attribute-based redaction) are identical; only the surface changes.

### .NET

```bash
dotnet add package pinqloq
```

```csharp
builder.Services.AddPinqloq(options =>
{
    options.SecretKey = builder.Configuration["Pinqloq:SecretKey"]!;
});

var app = builder.Build();
app.UsePinqloqRequestLogging();                    // automatic request logging

pinqloqClient.Enqueue(new PinqloqLogEntry          // manual event
{
    Event = "order_placed", DeviceIdentifier = "u-9821",
    LogSourceType = PinqloqLogSourceType.Backend
});
```

Redaction is attribute-based: `[PinqloqRedact]` on a field, `[PinqloqRedactEndpoint]` on an endpoint or controller.

### Node.js (Express)

```bash
npm install pinqloq
```

```ts
import { createPinqloq, PinqloqLogSourceType } from "pinqloq";

export const pinqloqClient = createPinqloq({
  secretKey: process.env.PINQLOQ_SECRET_KEY!
});

app.use(express.json());
app.use(pinqloqClient.requestLogging({ excludePaths: ["/health"] }));   // automatic

pinqloqClient.enqueue({                                           // manual event
  event: "order_placed", deviceIdentifier: "u-9821",
  logSourceType: PinqloqLogSourceType.Backend
});

process.on("SIGTERM", async () => { await pinqloqClient.shutdown(); process.exit(0); });
```

Redaction is name-based: pass `redactFields` and `redactPaths` to `requestLogging(...)`.

### Go (`net/http`)

```bash
go get github.com/pinqponq/pinqloq-go-sdk/v2
```

```go
pinqloqClient, err := pinqloq.New(pinqloq.Options{
    SecretKey: os.Getenv("PINQLOQ_SECRET_KEY"),
})
if err != nil {
    panic(err)
}
defer pinqloqClient.Shutdown(context.Background())

middleware := pinqloqClient.RequestLogging(pinqloq.RequestLoggingOptions{      // automatic
    ExcludePaths: []string{"/health"},
})
http.ListenAndServe(":8080", middleware(mux))

pinqloqClient.Enqueue(pinqloq.LogEntry{                            // manual event
    Event: "order_placed", DeviceIdentifier: "u-9821",
    LogSourceType: pinqloq.LogSourceTypeBackend,
}, nil, nil)
```

The middleware is a plain `func(http.Handler) http.Handler`, so it works with chi, gorilla/mux, `http.ServeMux`, or Gin via `gin.WrapH`. Redaction is name-based: `RedactFields`, `RedactPaths`.

### Ruby (Rack)

```bash
gem install pinqloq
```

```ruby
require "pinqloq"

PINQLOQ = Pinqloq.create(
  secret_key: ENV.fetch("PINQLOQ_SECRET_KEY")
)

use Pinqloq::Rack::RequestLogging,                                 # automatic
    logger: PINQLOQ.logger,
    exclude_paths: ["/health"]

PINQLOQ.enqueue(                                                   # manual event
  Pinqloq::LogEntry.new(
    event: "order_placed", device_identifier: "u-9821",
    log_source_type: Pinqloq::LogSourceType::BACKEND
  )
)

at_exit { PINQLOQ.shutdown }
```

Works with Rails, Sinatra, Hanami, Grape, or a bare Rack app. Redaction is name-based: `redact_fields`, `redact_paths`.

### Before you start

| You need | What to do |
| --- | --- |
| A pinqloq account | Sign up at [pinqloq.pinqponq.io](https://pinqloq.pinqponq.io). |
| A project with a secret key | Create a project in the dashboard. Your secret key is generated when you create the project. See [Create a project](#dashboard-setup). |

### Two ways to log

- **Automatic request logging** - One line of middleware logs every HTTP request. It captures the method, path, status, and duration automatically.
- **Manual event logging** - Call the SDK yourself to log business events, exceptions, HTTP requests, or client events forwarded through your backend. You choose the collection, source, and fields.

## Client events

Send events from a client app to pinqloq through your own backend.

A client (phone, browser, or POS device) must never hold the secret key. The client sends events to an endpoint you create on **your** backend. Your backend then uses its pinqloq SDK to forward those events to pinqloq. The secret key stays on your server.

> **This is manual logging with a Device source** - Client logging uses the same [Enqueue](#http-custom) as backend logging. Set `LogSourceType` to `Device` and use a separate collection. If you also run [automatic request logging](#http-builtin), exclude this endpoint. Otherwise the same request is logged twice.

### How a client log travels

1. **Client app → your backend** - The app posts the event to an endpoint you own. See [In your client app](#client-app).
2. **Your backend receives it** - Your backend receives the client's payload on an endpoint you define.
3. **Your backend → pinqloq** - The SDK ships the event to pinqloq. See [Custom logging](#http-custom).

## In your client app

The app's only job is to send the event to your backend.

The client never calls pinqloq directly. It posts the event and any extra context to an endpoint on your backend. You decide what to include in the payload.

### Example request to your backend

```bash
curl -X POST https://your-backend.example.com/logs \
  -H "Content-Type: application/json" \
  -d '{ "event": "checkout_completed", "orderId": "A-1042", "screen": "cart" }'
```

> **Never ship the secret key** - The pinqloq secret key is a server credential. Keep it out of mobile bundles, browser code and anything a user can inspect. The client only ever talks to your backend.

## Custom logging

Take your pinqloq client (`IPinqloqLogger` in .NET, the client itself in Node, Go, and Ruby) and call `enqueue` from anywhere in your backend. You build the log entry yourself and decide which fields to include. Use the `Backend` source for backend events and the `Device` source to forward events from a client app.

### Before you start

1. **Create a project** - See [Create a project](#dashboard-setup).
2. **Create a collection** - See [Create a collection](#collection-setup). You will use its name as `CollectionName` in the SDK.
3. **Create the client** - `AddPinqloq(...)` / `createPinqloq(...)` / `pinqloq.New(...)` / `Pinqloq.create(...)`. See [SDK configuration](#configuration).

What are you logging?

Use `LogSourceType.Backend` for any event that originates on your backend: a business event, an exception, a background job result, an HTTP request, or anything else you want to log manually. You can call `Enqueue` from a controller, a service, a background job, or a middleware.

> **Logging HTTP requests via custom logging** - You can use custom logging to log HTTP requests. There are no restrictions. However, to ensure the log panel displays them correctly, include the following keys inside `Detail`: `RequestMethod`, `ResponseCode`, `InputJson`, and `OutputJson`. You can optionally also include `RequestHeaders` and `ResponseHeaders` to capture request/response headers, matching what the built-in middleware produces. Missing any of these will not cause an error, but the panel will not be able to render the request details view for that entry.

```csharp
pinqloqClient.Enqueue(new PinqloqLogEntry
{
    Event            = "order_placed",
    DeviceIdentifier = "u-9821",
    LogLevel         = PinqloqLogLevel.Information,
    LogSourceType    = PinqloqLogSourceType.Backend,
    Metadata         = new()
    {
        ["userId"]   = "u-9821",
        ["tenantId"] = "t-502"
    },
    Detail           = new()
    {
        ["orderId"]      = "A-1042",
        ["totalAmount"]  = "149.99"
    }
},
onFailed: (entry, error) => Console.WriteLine($"Log failed: {error.Reason}"),
onSent:   entry => Console.WriteLine("Log sent"));
```

Use `LogSourceType.Device` when your backend is forwarding an event that originated on a client. The client can be a mobile app, a web app, or any other device. Create a separate collection for these logs so they stay separate from your backend logs. See [In your client app](#client-app) for the client-side code.

```csharp
pinqloqClient.Enqueue(new PinqloqLogEntry
{
    Event            = "order_placed",
    DeviceIdentifier = "device-8f3a12",
    LogLevel         = PinqloqLogLevel.Information,
    LogSourceType    = PinqloqLogSourceType.Device,
    CollectionName   = "client_logs",
    Metadata         = new()
    {
        ["battery"]     = "72%",
        ["networkType"] = "wifi"
    },
    Detail           = new()
    {
        ["orderId"]    = "A-1042",
        ["itemCount"]  = "3"
    }
},
onFailed: (entry, error) => Console.WriteLine($"Log failed: {error.Reason}"),
onSent:   entry => Console.WriteLine("Log sent"));
```

> **Field reference** - `Event` is always required. Without it the entry is skipped. `DeviceIdentifier` is optional and has no global option: set it per entry, or per request through the [built-in middleware](#http-builtin); an entry that leaves it empty is stored without one. `Date` is optional. If not set, it is assigned when the log is queued. `CollectionName` is optional. If not set, it falls back to `ApiLogsCollectionName` from [SDK configuration](#configuration); if both are empty, the server resolves it (single-collection keys only).

### PinqloqLogEntry fields

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `Event` | string | required | Log title shown in the panel. Cannot be empty. Entries without it are dropped; the rest of the batch is sent. Stored as a fixed, indexed field. |
| `LogLevel` | PinqloqLogLevel | Information | Debug, Information, Warning, Error, Fatal. |
| `LogSourceType` | PinqloqLogSourceType | Backend | `Backend` for backend events, `Device` for client events forwarded through your backend. |
| `CollectionName` | string? | null | Target collection. Falls back to `ApiLogsCollectionName` when unset. If neither is set, the server resolves it (single-collection keys only). |
| `Date` | DateTimeOffset? | null | When the event happened. Optional: if not set, the SDK assigns the timestamp when the log is queued. You can set it manually to override it. |
| `Path` | string? | null | Optional request path (e.g. an HTTP endpoint path). Stored as a fixed, indexed field. The [built-in middleware](#http-builtin) fills it automatically; on a manual entry it stays null unless you set it. |
| `Metadata` | Dictionary<string,string>? | null | Short searchable key-value pairs shown in the panel. Keep values brief. |
| `Detail` | Dictionary<string,string>? | null | Larger diagnostic data such as stack traces or full request bodies. |
| `DeviceIdentifier` | `string?` | null | Optional unique identifier (device, user, or instance). Set it per entry; there is no global option to fall back to. The [built-in middleware](#http-builtin) fills it from the per-request resolver or the `device-identifier` header. An entry without one is stored as `null`. |
| `AppVersionName` | string? | null | Optional version label. Falls back to the global `AppVersionName` option when unset; if that is also unset, the SDK sends `null` (not `""`) and the server stores it as absent. |
| `CorrelationId` | string? | null | Optional identifier that ties together the logs of one request or flow. The [built-in middleware](#http-builtin) fills it automatically. |

### Which method to call

| Method | Delivery | Use it for |
| --- | --- | --- |
| `Enqueue(entry)` | Buffered, batched | Use for most cases. Non-blocking; returns `false` if the queue is full. Pass an optional `onFailed` callback to react to drops or rejections. See [Delivery callbacks](#configuration). |
| `Enqueue(entries)` | Buffered, batched | Same as above, but queues a whole list in one call. Returns the number of entries accepted into the queue. |

> **Don't need custom fields?** - Skip writing the call yourself and go straight to [Built-in middleware →](#http-builtin)

## Built-in middleware

One line, a fixed template, every request logged.

Add the request-logging middleware once at startup to log every request: `app.UsePinqloqRequestLogging()` (.NET), `app.use(pinqloqClient.requestLogging())` (Node), `pinqloqClient.RequestLogging(...)` wrapping your handler (Go), `use Pinqloq::Rack::RequestLogging` (Ruby). The SDK fills in all fields automatically.

Use the built-in middleware when you want zero per-request code and complete coverage of every HTTP request with no extra effort. It is the right choice for most applications.

> **How response capture works** - To capture the response body, the middleware wraps the response stream with a buffer before the request travels down the pipeline. The response is written into memory first, then flushed to the client. This adds a small allocation per request. If your application is latency-sensitive or you prefer not to insert middleware into the pipeline, use [custom logging](#http-custom) instead and call `Enqueue` directly at the point where you already have the data you need.

### Before you start

1. **Create a project** - See [Create a project](#dashboard-setup).
2. **Create a collection** - See [Create a collection](#collection-setup). You will use its name as `ApiLogsCollectionName`.
3. **Set `ApiLogsCollectionName` in SDK configuration** - Optional if your secret key allows a single collection; the server resolves it automatically. Required if the key allows more than one. See [SDK configuration](#configuration).
4. **Add the middleware** - To skip certain paths (health checks, Swagger, endpoints you log manually), use `ExcludePaths`. Matching is segment-based and case-insensitive: `/api` matches `/api/orders` but not `/apixyz`.

### Advanced usage

Use `AddMetadata` or `AddDetail` to add custom fields to your logs. Each callback receives the `HttpContext` and runs once per request. If a callback returns null or throws, that key is skipped. Your keys do not overwrite built-in fields. The only exception is `event` (the panel title, the fixed `Event` field). It defaults to `"{method} {path}"`. To override it, use `AddMetadata("event", …)`; the middleware reads it back before sending, so your override lands on the entry's `Event` field rather than staying in `Metadata`.

Use `SetDeviceIdentifier` to resolve `DeviceIdentifier` per request (for example from a claim, header, or trace id). Use `SetAppVersionName` to set the version label per request. When the device-identifier callback returns null or empty the middleware falls back to the `device-identifier` header; the app-version callback falls back to the global `AppVersionName` option.

```csharp
app.UsePinqloqRequestLogging(options =>
{
    // Optional: the middleware already reads the "device-identifier" header. Use SetDeviceIdentifier only to override it.
    options.SetDeviceIdentifier(ctx => ctx.User.FindFirst("sub")?.Value);
    // Optional per-request version label; falls back to the global AppVersionName option
    options.SetAppVersionName(ctx => ctx.Request.Headers["X-App-Version"]);

    options.AddMetadata("userId", ctx => ctx.User.FindFirst("sub")?.Value);

    options.AddDetail("userAgent", ctx => ctx.Request.Headers.UserAgent);
    // Override the default event title (lands on the Event field, not Metadata)
    options.AddMetadata("event", ctx => ctx.Request.Path);
});
```

> **How the middleware resolves DeviceIdentifier** - The middleware resolves `DeviceIdentifier` in this order: `SetDeviceIdentifier` (overrides everything), then the `device-identifier` request header. There is no global option after that: if neither yields a value the request is still logged, without a `DeviceIdentifier`. Guarantee a value with `SetDeviceIdentifier(ctx => ctx.Request.Headers["device-identifier"].FirstOrDefault() ?? Environment.MachineName)`.

> **How the middleware resolves CorrelationId** - The middleware resolves `CorrelationId` in this order: the caller's `correlation-id` request header (case-insensitive), then `HttpContext.TraceIdentifier`. There is no override option and no global fallback. A caller that already sends its own correlation id keeps it end to end.

### What gets logged

Each request becomes one log. The fixed `Event` field (the log title) is set to `"{method} {path}"` (e.g. `GET /api/orders/42`), and the fixed `Path` field is set to the request path. Both are stored as indexed fields, not inside `Metadata`. The level comes from the response status. The rest of the request details go into `Metadata`:

| Status | Level | Metadata |
| --- | --- | --- |
| 2xx / 3xx | Information | `method`, `statusCode`, `durationMs` |
| 4xx | Warning |
| 5xx | Error |

`Detail` carries `InputJson`, `OutputJson`, `RequestHeaders` and `ResponseHeaders`, each truncated at 32 KB. The panel reads the endpoint's title and path from the fixed `Event` and `Path` fields and its status from `Metadata`, where the middleware writes `RequestMethod` and `ResponseCode` alongside the shorter `method`, `statusCode` and `durationMs`. Bodies and headers both reach the panel. Credential headers such as `Authorization`, `Cookie` and `X-Api-Key` are masked automatically, everything else is not, so exclude paths that carry secrets or PII.

> **Need to mask sensitive fields?** - See [Redacting sensitive values →](#redacting-sensitive-values)

## Create a project

The dashboard is at [pinqloq.pinqponq.io](https://pinqloq.pinqponq.io). Create a project here to get your secret key.

1. **Create a project** - A secret key belongs to a project. You may want to use one project per environment to keep production and development logs separated.
2. **Copy the secret key** - Store it in user-secrets, an environment variable, or a secret manager. Never put it in client apps or front-end code.

## Create a collection

A collection is a named bucket where logs are stored in the panel. You need at least one before you can send logs.

1. **Create a collection** - Open the dashboard, go to your project, and create a collection.
2. **Copy the collection name** - You will use this name in your SDK configuration as `ApiLogsCollectionName`, or set it per log entry as `CollectionName`.

Collections can be edited, disabled, or deleted from the dashboard. A key can write only to collections allowed for its project; logging to another collection returns `403 Forbidden`.

## Dashboard panel

After the SDK starts sending logs, use the dashboard panel to read them, manage who can see them, and control active panel sessions.

### View logs

1. **Open the log panel** - Go to [pinqloq-panel.pinqponq.io](https://pinqloq-panel.pinqponq.io) and sign in with the panel account created from the dashboard.
2. **Choose a project and collection** - Logs are grouped by project and collection. Pick the collection name you configured in `ApiLogsCollectionName` or sent on each log entry.
3. **Filter and inspect logs** - Use the panel filters to narrow logs by collection, level, source, event, path, device, or time range. New logs may appear after the SDK batch delay.

### Manage panel users

| Action | How it works |
| --- | --- |
| Invite user | Open `Team Members`, choose `Invite User`, enter the email, set an initial password, and select the collections this user can access. Passwords must be at least 8 characters. |
| Set admin password | For an admin or owner account, use `Edit` to set or reset the panel password. This gives the admin access to the live log panel. |
| Edit permissions | For regular users, use `Edit` to change collection access. Users can only see the collections selected for them. |
| Deactivate user | Use the active/inactive badge to disable a non-admin user without deleting the account. Admin and owner accounts cannot be disabled from this control. |
| Delete user | Remove a non-admin user when they should no longer have panel access. Admin and owner accounts are protected from deletion in this screen. |

### Sessions and devices

Each panel user can have up to **3 active sessions**. A session is shown as an active device in the user's `Devices` panel. If a user reaches the session limit, remove an old device to free a slot before signing in again.

### Plan limits

| Limit | Included usage |
| --- | --- |
| Projects | You can create as many projects as you need. |
| Collections | You pay for two things: how long each collection keeps its logs, and logs above 5 GB per project. Opening collections and projects is free, and a project can have as many collections as you need. |
| Retention | Each collection has its own retention and pays for it on its own. 3 days are free. A longer retention costs $2 to $48 per month for that collection, up to a maximum of 364 days. |
| Log ingest | Each project includes 5 GB of logs in each billing period, counted over all of its collections. Every started GB above 5 GB costs $0.50 and is charged at the end of the billing period. The account's admins get an e-mail when a project passes 5 GB. If a project reaches 10 GB in a billing period while the balance does not cover the extra GB charged so far, its logs return HTTP 429 until the balance is topped up. 1 GB is 1024 × 1024 × 1024 bytes. |
| Panel sessions | Each panel user can have up to 3 active sessions. |

The dashboard is used to create projects, collections, keys, and panel users. The log panel at [pinqloq-panel.pinqponq.io](https://pinqloq-panel.pinqponq.io) is where those users sign in to view logs.

## MCP server

Ask an AI assistant about your logs instead of opening the panel. The MCP server connects Claude, Cursor, or any other Model Context Protocol (MCP) client to your logs.

The MCP server is read-only. It reads your logs through the same panel API the log panel itself uses. It cannot write logs, and it cannot change any project, collection, or user in your dashboard.

### What you can ask

| Tool | What it does |
| --- | --- |
| `get_logs` | Fetch logs. Filter by collection, level, event, path, device, app version, or time range. |
| `search_logs` | Search logs by text, across event, path, device identifier, metadata, and detail fields. |
| `get_collections` | List the collections your key can access. |
| `get_error_summary` | Group the errors in a time range and show which ones happen most. |

### Example prompts

Ask in plain language. The assistant picks the tool and the arguments for you.

| You ask | What runs |
| --- | --- |
| "Show me today's errors" | `get_logs(level="error", startTime="today")` |
| "What's failing the most in the last hour?" | `get_error_summary(timeRange="1h")` |
| "Search the logs for NullReferenceException" | `search_logs(query="NullReferenceException")` |
| "Which collections can I see?" | `get_collections()` |

> **It can find a bug and fix it** - Ask for more than a report: _"Find why checkout is failing, and fix it."_ The assistant calls `search_logs` or `get_error_summary` to find the failing log entry, reads the stack trace in its `detail` field, opens the matching file in your project, and makes the fix. The same assistant session that reads your logs also has your code open.

### Before you start

1. **Generate an MCP key** - Open the dashboard and go to the `MCP Key` tab to generate one company-wide key, or open `Users` to generate a key for one member instead.
2. **Add the key to your AI client** - Add the MCP server to your client's configuration, with your key in the `secret_key` header.

> **Company key or member key?** - A company key, from the `MCP Key` tab, reaches every collection in the company. Give it only to admins. A member key, generated from `Users`, reaches only the collections that member is allowed. These are the same collections they see when they sign in to the log panel themselves. If a member's collection access changes, their key updates with it.

> **Treat an MCP key like a password** - Whoever holds a key can read every log in its collections. Don't share a company key with someone who should only see a few collections. Generate them a member key instead. If a key leaks, revoke it and generate a new one.

## SDK configuration

> The options below are shown with .NET names and an `appsettings.json` binding. Node, Go, and Ruby take the same options with idiomatic casing (`apiLogsCollectionName` / `APILogsCollectionName` / `api_logs_collection_name`) and read the secret from an environment variable or secret manager instead of `appsettings.json`. See the [SDKs](#sdks) section for each language's `create`/`New` call.

Add the `pinqloq` package, then create the client once at startup.

```bash
dotnet add package pinqloq
```

`SecretKey` is required. Set `ApiLogsCollectionName` when you use the built-in middleware or want a default collection. Logs without a `CollectionName` fall back to this value. There is no global device-identifier option: set that field per entry, or per request through the built-in middleware.

```csharp
builder.Services.AddPinqloq(options =>
{
    options.SecretKey             = builder.Configuration["Pinqloq:SecretKey"]!;
    options.ApiLogsCollectionName = builder.Configuration["Pinqloq:ApiLogsCollectionName"]!;
    options.AppVersionName        = builder.Configuration["Pinqloq:AppVersionName"];
    options.BatchSize             = 200;
    options.FlushInterval         = TimeSpan.FromSeconds(2);
    options.QueueCapacity         = 10000;
    options.HttpTimeout           = TimeSpan.FromSeconds(10);
});
```

Add a matching `Pinqloq` section to `appsettings.json` so these values resolve at runtime (see **From appsettings.json** below).

### Options

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| SecretKey | `string` | required | Your API secret, sent as the `X-Secret-Key` header. |
| ApiLogsCollectionName | `string?` | null | Collection for the built-in pinqloq middleware and for logs without a `CollectionName`. Optional for single-collection keys; required when the key allows several. |
| AppVersionName | `string?` | null | Optional version label, applied to any log that doesn't set its own. |
| BatchSize | `int` | 200 | Max logs per batch. |
| FlushInterval | `TimeSpan` | 2s | Max wait before a partial batch is sent. |
| QueueCapacity | `int` | 10000 | In-memory queue size. When full, new logs are dropped. |
| HttpTimeout | `TimeSpan` | 10s | Per-request HTTP timeout. |

### From appsettings.json

Bind the options from configuration to keep the secret out of source code:

```appsettings.json
{
  "Pinqloq": {
    "SecretKey": "lgl_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "ApiLogsCollectionName": "myapp_api_logs",
    "AppVersionName": "1.0.0"
  }
}
```

```csharp
builder.Services.AddPinqloq(options =>
    builder.Configuration.GetSection("Pinqloq").Bind(options));
```

### Delivery callbacks

`Enqueue` takes two optional callbacks. Pass only the ones you need. Most code only uses `onFailed`:

With `Enqueue` (fire and forget, batched in the background):

```csharp
pinqloqClient.Enqueue(entry,
    onFailed: (failedEntry, error) =>
        _logger.LogError(error.Exception,
            "Pinqloq log failed: {Reason} ({Status}) - {Message}",
            error.Reason, error.StatusCode, error.Message),
    onSent: sentEntry => { /* optional: metrics, tracing, etc. */ });
```

`onSent` runs once the log reaches the server. `onFailed` runs when the log is dropped or rejected. If the in-memory queue is full, `onFailed` fires immediately with reason `QueueFull` and `Enqueue` returns `false`.

`onFailed` gives you a `PinqloqLogError`:

| Field | Type | Description |
| --- | --- | --- |
| Reason | `PinqloqLogFailureReason` | Why it failed: `Unauthorized`, `Forbidden`, `MissingCollection`, `QueueFull`, `HttpError`, `Timeout`, `Network`, or `Unknown`. |
| StatusCode | `int?` | The HTTP status when the server responded; `null` for non-HTTP failures. |
| Message | `string` | A plain-text description of what went wrong. Always present. |
| Exception | `Exception?` | The underlying exception when one was thrown; otherwise `null`. |

> Callbacks are optional. If you skip them, failures are still written to your application log, throttled, with the server's response. The [built-in pinqloq middleware](#http-builtin) logs every request for you and has no call site, so its failures only go to the application log.

### Production notes

> **Keep the secret key server-side** - It's a server credential. Store it in user-secrets, environment variables, or a secret manager. Never put it in client apps, mobile bundles, or front-end code.

| Do | Why |
| --- | --- |
| Separate environments | Use different collections and keys for prod and dev so test data stays out of production. |
| Don't log secrets or PII | Strip passwords, tokens, auth headers and personal data. Mask anything you must keep. |
| Trim large values | Truncate big request/response bodies. Oversized batches are rejected. |
| Use Enqueue for high volume | Non-blocking and batched. It is the right choice for most logging scenarios. |

### Types & enums

A `PinqloqLogEntry` uses two enums. In C# you pass the enum value. On the raw HTTP payload, `logLevel` is a number and `logSourceType` is a string.

| `PinqloqLogLevel` | When to use |
| --- | --- |
| Debug | Verbose diagnostics. |
| Information | Normal flow (the default). |
| Warning | Recoverable issues. |
| Error | Failures. |
| Fatal | Unrecoverable failures. |

| `PinqloqLogSourceType` | Meaning |
| --- | --- |
| Backend | The log originated on your backend. Use this for backend events (the default). |
| Device | The log originated on a client/device. Set this for [client logging](#client-logging). |

On the raw payload, `logLevel` is the number `1–5` and `logSourceType` is the string `"Backend"` / `"Device"` (case-insensitive).

## Troubleshooting

| Symptom | Cause & fix |
| --- | --- |
| 401 Unauthorized | Missing or wrong secret key. Check `SecretKey` and the value you copied from the dashboard. It is also returned while the account's log intake is suspended for an unpaid charge or after the subscription has ended. |
| 403 Forbidden | The collection isn't allowed for your key. The SDK drops logs for that collection and writes one throttled error to your app logs; other collection groups continue. Add the collection to your project, or log to an allowed one. |
| 400 Bad Request | The key allows multiple collections but no collection name was sent, `logSourceType` is invalid, or the required `Event` field is empty. Set `ApiLogsCollectionName` or a per-entry `CollectionName`, and make sure every log has an `Event`. Details are in your app logs. |
| 429 Too Many Requests | Either the ingest rate limit (requests per minute) was reached, or the project reached 10 GB in the billing period while the balance does not cover its extra GB. Honour `Retry-After`. After a top-up that covers the extra GB, the project accepts logs again within 5 minutes. |
| A single entry is missing | Entries with an empty `Event` are skipped server-side; the rest of the batch is stored. Set `Event` on every entry. A missing `DeviceIdentifier` never drops an entry — it is optional and stored as `null`. |
| Logs not in the panel | Batches send every ~2s or at `BatchSize`. Allow a short delay. Check the collection name and let the host shut down gracefully so the dispatcher can drain remaining logs. |
| Middleware does nothing | Make sure `UsePinqloqRequestLogging()` is registered early, before any middleware that ends the request. |
| Same event logged twice | You log an endpoint manually and also run the built-in pinqloq middleware, so the request is captured by both. Exclude that path: `UsePinqloqRequestLogging(o => o.ExcludePaths("/api/client-events"))`. |
| Logs dropped under load | The in-memory queue is full. Raise `QueueCapacity` or lower `FlushInterval`. |

## Redacting sensitive values

Sensitive values like passwords, tokens, and card numbers shouldn't end up in your logs.

### What is masked without you doing anything

Some names are never logged, in headers or in JSON bodies, whatever else you configure: `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, `X-Secret-Key`, `X-Auth-Token`, `X-Access-Token`, `X-Csrf-Token`, `X-Xsrf-Token`, `secret_key`, `password`, `newPassword`, `oldPassword`, `currentPassword`, `passwordConfirmation`, `confirmPassword`, `secret`, `secretKey`, `clientSecret`, `apiKey`, `accessToken`, `refreshToken`, `idToken`, `token`, `otp`, `otpCode`, `verificationCode`, `pin`, `privateKey`, `cardNumber`, `cvv`, `cvc`, `securityCode`, `iban`, `ssn`.

Matching ignores case and applies at any depth, including inside arrays. There is no way to turn it off: a field genuinely called `token` that is not a credential will be masked too, which is the trade we chose over shipping a real one. It is a floor, not a substitute for the attributes below: it cannot know that your `taxNumber` or `patientId` is sensitive.

### Masking your own fields

Add one of two attributes to your code and pinqloq masks them automatically; no other changes needed. This works with MVC controllers, not with minimal API endpoints (`app.MapGet`/`MapPost`); on a minimal API only the list above applies, so mask anything else yourself before it reaches a log.

Add `[PinqloqRedact]` above a single field to hide just that field's value, wherever it shows up, even when it's nested inside another object. Everything else in the request and response is still logged as usual.

```csharp
public class AuthResponse
{
    [PinqloqRedact]
    public string Token { get; set; } = "";

    public string UserId { get; set; } = "";
}
```

Add `[PinqloqRedactEndpoint]` above an entire endpoint, or above the whole controller to cover every endpoint in it, to hide everything it sends and receives: every field, every header. Use it for endpoints that only ever handle sensitive data, like payments or password resets.

```csharp
[ApiController]
[Route("api/user")]
public class UserController : ControllerBase
{
    [HttpPost("Auth")]
    public AuthResponse Auth([FromBody] AuthRequest request) => ...;

    [PinqloqRedactEndpoint]
    [HttpPost("Payment")]
    public IActionResult Payment([FromBody] PaymentRequest request) => ...;
}
```

Log for `Auth`:

```json
{ "token": "*****REDACTED*****", "userId": "64" }
```

Log for `Payment` (every value masked, including headers):

```json
{ "cardNumber": "*****REDACTED*****", "amount": "*****REDACTED*****" }
```

`[PinqloqRedact]` only works on JSON bodies. If a request or response isn't JSON (form data, plain text), the field you marked is logged as-is, unmasked. `[PinqloqRedactEndpoint]` doesn't have this gap: a non-JSON body is still replaced with a single masked value, so it's always protected.

> **Using redaction from your own middleware** - If you have your own request-logging middleware instead of `UsePinqloqRequestLogging`, call `PinqloqRedaction.Resolve(httpContext)` directly. It runs the same reflection (cached per action) and returns a `PinqloqRedactionPlan` with `RedactAll`, `HasRedactions`, and `ShouldRedact(name)`. Resolve it once per request and reuse it for every field you check.
