> For the complete documentation index, see [llms.txt](https://triton.pharos.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://triton.pharos.ai/triton-best-practices/context-and-related-objects.md). Agents can also search and read this documentation through its [MCP server](https://triton.pharos.ai/~gitbook/mcp).

# Context & Related Objects

Making every log carry enough context to debug from — what Triton captures for you automatically, what you should add, and what you must never log.

The gap between a useless log and a great one is context. `"Update failed"` tells you nothing. The same failure, tied to the three records involved, carrying the transaction id, the stack trace, the governor limits at the moment of failure, and a one-line human summary — that you can act on.

The encouraging part: Triton captures most of that for you. Your job is small and specific — add the business context the framework can't infer, and keep sensitive data out.

## What Triton captures automatically

When you hand a builder to `Triton.log(...)` (or any level method), the framework enriches it before buffering. You get, for free, on every Apex log:

* **Stack trace** — captured if you didn't set one.
* **Operation** — the class/method, derived from the stack trace.
* **Governor limits** — SOQL, DML, CPU, heap, and callout usage at log time.
* **Execution context** — for Apex logs, the trigger operation / batch size / async type.
* **Transaction id** — stamped from the current transaction (via `Triton.t`).
* **Request id and timestamp.**

So you don't hand-assemble any of that. Which means the context *you* add is a short list.

## What you should add

### Related objects — almost always

Relating a log to the records it's about is the single highest-value thing you can do. It powers the "Related Objects" view, drives correlation, and lets you pivot from a record to every log that touched it.

{% code lineNumbers="true" %}

```apex
// One record
Triton.info(Triton.t.summary('Account processed').relatedObject(accountId));

// Several
Triton.info(Triton.t
    .summary('Order processed')
    .relatedObjects(new Set<Id>{ order.Id, order.AccountId, order.OpportunityId }));
```

{% endcode %}

`.relatedObject(...)` takes an `Id` or a `String`; `.relatedObjects(...)` takes a `List` or `Set` of `Id` or `String`. Invalid ids are silently ignored, so you can pass loosely-typed collections without guarding every element.

{% hint style="success" %}
**Relate everything you know about.** The primary record, its parents, the children you touched. In a failure, the related objects are how support jumps straight from "this account is broken" to "here's exactly what happened to it."
{% endhint %}

### A human summary — always

`.summary()` is the one-line headline someone reads first. Make it for a human: `'Payment captured'`, not `'ok=true'`. Put the machine-readable specifics in `.details()`.

### Duration — for anything worth trending

For work whose speed matters — callouts, batch chunks, expensive queries — measure and attach it. It turns your logs into a performance dataset you can chart.

{% code lineNumbers="true" %}

```apex
Long t0 = System.now().getTime();
// ... work ...
Triton.info(Triton.t
    .summary('Rollup recalculation complete')
    .details('accounts=' + accounts.size())
    .duration(System.now().getTime() - t0));
```

{% endcode %}

{% hint style="info" %}
**Timing a whole method? Use a mark instead.** `Triton.startMark()` / `Triton.endMark()` time the stretch for you, publish the duration on a paired `Performance` record, and parent everything logged in between to that span — see [Performance Marks in Apex](https://triton.pharos.ai/common-apex-usage-patters/performance-marks.md). Hand-rolled timing like the snippet above stays the right tool when you want the duration on an *existing* log rather than a span of its own.
{% endhint %}

### Integration payloads — for callouts

When you log around a callout, attach the request/response with `.integrationPayload(...)`. It accepts either `HttpRequest`/`HttpResponse` or `RestRequest`/`RestResponse`.

{% code lineNumbers="true" %}

```apex
HttpResponse res = new Http().send(req);
Triton.info(Triton.t
    .summary('ERP sync callout complete')
    .details('status=' + res.getStatusCode())
    .integrationPayload(req, res));
```

{% endcode %}

{% hint style="warning" %}
**Sanitize payloads before attaching them.** Request/response bodies love to carry auth headers, tokens, and PII. Strip or mask anything sensitive before it lands in a durable log. See [Never log this](#never-log-this).
{% endhint %}

## Governor limits: automatic, with two knobs

Because limits are captured for you, you rarely call the limit methods directly. When you do want control:

* **`.withoutLimitInfo()`** — suppress limit capture on this log (e.g. a trivial, high-volume trace where you don't care).
* **`.withFullLimitInfo()`** — capture the *extended* set (aggregates, SOSL, future calls, queueable jobs, email invocations, push notifications, batch jobs) on top of the essentials. Reach for this when you're profiling a limit-heavy operation.

{% code lineNumbers="true" %}

```apex
// Profiling a heavy job — grab the full limit picture
Triton.info(Triton.t.summary('Heavy job checkpoint').withFullLimitInfo());
```

{% endcode %}

## Spans and tracing — for deep call chains

For tracing across a chain of calls (or mapping to OpenTelemetry-style spans), the builder exposes `.spanId(...)`, `.parentSpanId(...)`, `.traceable(true)`, and `.tracePoint()`. Most everyday logging doesn't need these — a transaction id already correlates your logs — but they're there when you need finer-grained parent/child structure within a trace. See the [TritonBuilder reference](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder.md) and [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing.md).

## User context

Triton associates the current user automatically. Override it only when you genuinely need to attribute a log to a different user (e.g. an integration user acting on behalf of someone):

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t.summary('Acted on behalf of user').userId(onBehalfOfUserId));
```

{% endcode %}

## Never log this

Logs are durable and broadly readable. Treat them as if they'll be reviewed in an audit — because they might be.

{% hint style="danger" %}
**Keep these out of logs entirely:**

* Passwords, session tokens, API keys, OAuth secrets, `Authorization` headers.
* Regulated PII and financial data — full card numbers (PAN), SSNs, health records.
* Anything you'd have to report if it leaked.

Log **identifiers and signals** instead: record ids, correlation ids, status codes, counts, durations. They make debugging possible without creating a liability.
{% endhint %}

## Putting it together

{% code lineNumbers="true" %}

```apex
public static void processOrder(Id orderId) {
    Long t0 = System.now().getTime();
    Triton.setTemplate(Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .area(TritonTypes.Area.OpportunityManagement)
        .relatedObject(orderId));

    try {
        Order ord = [SELECT Id, AccountId, OpportunityId, Status FROM Order WHERE Id = :orderId];

        // Relate parents, summarize for a human, keep details machine-readable
        Triton.info(Triton.t
            .summary('Order processing started')
            .details('status=' + ord.Status)
            .relatedObjects(new Set<Id>{ ord.AccountId, ord.OpportunityId }));

        // ... work ...

        Triton.info(Triton.t
            .summary('Order processing completed')
            .duration(System.now().getTime() - t0)
            .relatedObjects(new Set<Id>{ ord.AccountId, ord.OpportunityId }));

    } catch (Exception e) {
        Triton.logNow(Triton.t.exception(e));   // stack trace, limits, context all captured for you
        throw e;
    } finally {
        Triton.flush();
    }
}
```

{% endcode %}

## Related reading

* Every builder method: [Core Concepts → The Builder & Templates](https://triton.pharos.ai/core-concepts/builder-and-templates.md) and the [TritonBuilder reference](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder.md).
* Turning exceptions into rich error logs: [Exception Handling](https://triton.pharos.ai/triton-best-practices/exception-handling.md).
