> 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/core-concepts/builder-and-templates.md).

# The Builder & Templates

The TritonBuilder fluent API and the template pattern — how to describe a log, stamp shared fields onto every log, and keep your logging code DRY.

Every Triton log is described by a **builder** — a small, fluent object that you chain method calls onto until it captures everything you want on the record. Then you hand it to `Triton`. This page is about building logs well: the builder itself, the handful of methods you'll use constantly, and the template pattern that keeps you from repeating yourself.

## The builder

Grab a builder with `Triton.makeBuilder()` and chain away. Each method returns the builder, so it reads like a description of the log:

{% code lineNumbers="true" %}

```apex
TritonBuilder b = Triton.makeBuilder()
    .category(TritonTypes.Category.Apex)
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.Accounts)
    .summary('Recalculated rollups')
    .details('Processed 240 accounts in 1.2s')
    .level(TritonTypes.Level.INFO);

Triton.log(b);
```

{% endcode %}

`Triton.makeBuilder()` hands back a builder that already has its category set to `Apex`, since that's what you're logging from most of the time. Override it with `.category(...)` whenever you need to.

### The methods you'll actually use

The builder has a large surface, but day to day it comes down to a small set:

| Method                                         | Sets                          | Notes                                                                                                           |
| ---------------------------------------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `.category(...)` / `.type(...)` / `.area(...)` | Classification                | See [Enums](https://triton.pharos.ai/core-concepts/enums.md). `type` and `area` accept an enum or a raw string. |
| `.summary(String)`                             | The one-line headline         | The first thing you read on the record. Keep it human.                                                          |
| `.details(String)`                             | The long form                 | Stack traces, payloads, context dumps.                                                                          |
| `.level(...)`                                  | Severity                      | Or use the shorthand `.error()` / `.warning()` / `.info()` / `.debug()` / `.fine()` / `.finer()` / `.finest()`. |
| `.exception(Exception e)`                      | Everything about an error     | One call — see below.                                                                                           |
| `.relatedObject(Id)` / `.relatedObjects(...)`  | Records this log is about     | Powers the "Related Objects" view. Each call replaces the set, so pass every id in one call.                    |
| `.attribute(field, value)`                     | Any field, standard or custom | The escape hatch — see [Custom attributes](#custom-attributes).                                                 |

### `.exception()` — the one you'll reach for most

When you're logging an error, don't set the type, summary, stack trace, and details by hand. `.exception(e)` does all of it — it pulls the type from the exception (falling back to `Backend`), sets the level to `ERROR`, copies the message into the summary, captures the stack trace and details, and flags the log for issue creation:

{% code lineNumbers="true" %}

```apex
try {
    chargeCard(payment);
} catch (Exception e) {
    Triton.error(Triton.t.area(TritonTypes.Area.OpportunityManagement).exception(e));
}
```

{% endcode %}

That's the entire error-logging pattern. Set the area (or let a template do it), pass the exception, done.

The issue follows the final level. Downgrade the log — `Triton.warning(Triton.t.exception(e))` — and you keep the exception detail, but the issue is withdrawn. Chain `.createIssue()` if you want one anyway: an explicit request stands at any level.

### `.dmlResults()` — logging bulk DML outcomes

When you run partial-success DML (`Database.insert(records, false)`), pass the results straight to the builder. It tallies successes and failures, collects the failed ids, and formats the error messages for you:

{% code lineNumbers="true" %}

```apex
List<Database.SaveResult> results = Database.insert(accounts, false);
Triton.warning(Triton.t
    .area(TritonTypes.Area.Accounts)
    .dmlResults(results));
```

{% endcode %}

It understands `SaveResult`, `DeleteResult`, `UpsertResult`, `UndeleteResult`, and `MergeResult`. When a row failed, it sets the Type to `DMLResult`, writes a summary such as `DML Operation (Save) Failed: 2 of 200 records failed.` (so set any summary of your own **after** it), and requests an issue — which `Triton.warning(...)` withdraws, because the log ends below ERROR. When every row succeeded, or the list is null or empty, nothing is logged at all, so there's no `if` to write around it.

## Templates: stop repeating yourself

Look at the examples above and you'll notice the same fields showing up over and over — category, area, maybe a related object. A **template** is a builder you configure once and reuse for every log after that.

Set it once, early (in a trigger handler constructor, at the top of a batch `execute`, wherever your unit of work begins):

{% code lineNumbers="true" %}

```apex
Triton.setTemplate(Triton.makeBuilder()
    .category(TritonTypes.Category.Apex)
    .area(TritonTypes.Area.OpportunityManagement));
```

{% endcode %}

Then start every log from the template with `Triton.t`:

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t.summary('Fetched 40 opportunities'));
Triton.error(Triton.t.summary('Sync failed').exception(e));
```

{% endcode %}

`Triton.t` is shorthand for `Triton.fromTemplate()`. Each call hands you a **fresh clone** of the template with the current transaction id already stamped on it — so the shared fields (category, area) come along automatically, but per-log fields (summary, details, exception) never leak from one log into the next.

{% hint style="info" %}
**Why clone?** If `Triton.t` returned the same builder every time, the summary from one log would bleed into the next. Cloning means the template is a stamp, not a shared mutable object. A couple of fields are intentionally *not* cloned (like the full summary and captured execution context) precisely because they're per-log values.
{% endhint %}

## Custom attributes

The builder has typed methods for the common fields, but you can set **any** field on the `pharos__Log__c` record — standard or custom — with `.attribute()`:

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.t
    .summary('Order processed')
    .attribute('My_Custom_Field__c', orderNumber));
```

{% endcode %}

### Prefer named methods over raw strings

`.attribute('My_Custom_Field__c', value)` works, but sprinkling field API names through your code is fragile. The better pattern — and the one Triton uses internally — is to add a typed method to `TritonBuilder` for each custom attribute you care about. If you open `TritonBuilder.cls`, you'll see it declares its field names as constants at the top:

{% code lineNumbers="true" %}

```apex
public static final String APEX_NAME = 'pharos__Apex_Name__c';
public static final String DURATION = 'pharos__Duration__c';
public static final String ACTION = 'Action__c';
// ...
```

{% endcode %}

Follow the same approach for your org. Declare the constant once, then add a small method:

{% code lineNumbers="true" %}

```apex
public static final String ORDER_NUMBER = 'Order_Number__c';

/**
 * Tag this log with the order it relates to.
 */
public TritonBuilder orderNumber(String value) {
    this.attribute(ORDER_NUMBER, value);
    return this;
}
```

{% endcode %}

Now your logging code is clean, type-friendly, and self-documenting:

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t.summary('Order processed').orderNumber(orderNumber));
```

{% endcode %}

You get autocomplete, a single place to change the field name, and a fluent API that matches the rest of the builder. It's a little more up-front effort for a lot less fragility later.

## What's next

* Severity and how to tune it per environment: [Log Levels](https://triton.pharos.ai/core-concepts/log-levels.md).
* When logs actually publish, and how to conserve platform events: [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing.md).
* Correlating logs across LWC → Apex → Flow, and span-based tracing: [End-to-End Logging](https://triton.pharos.ai/end-to-end.md).
