> This is part 1 of 2 of the full documentation (pages 1–100 of 131).
> The content is paginated: fetch every part to see all of it.
> Next part: https://triton.pharos.ai/llms-full.txt/1
> Page index: https://triton.pharos.ai/llms.txt

> Agents can also search and read this documentation through its [MCP server](https://triton.pharos.ai/~gitbook/mcp).

# About Pharos Triton

Just as the mighty Triton delivered important messages from the deep, Pharos Triton sends you crucial insights from the depths of your Salesforce automation.

{% embed url="<https://app.arcade.software/share/QwpFqaCj9KfWB26kQe4z>" %}
*Pharos Triton Intro*
{% endembed %}

***

## Ready to Dive In?

{% content-ref url="/pages/3FhR0oQeNx4BVfQjJlTN" %}
[Installing Pharos Triton](https://triton.pharos.ai/installing-pharos-triton)
{% endcontent-ref %}

## Why Logging?

If you've spent any time on the Salesforce platform, you know that, by default, it doesn't generate logs in its standard setup. You also know that exception emails and debug logs don't quite cut it when you're trying to run and troubleshoot an org — the former is unmanageable, the latter is short-lived and limited. For all its complexity, the platform offers no built-in answer to a common engineering problem: **what went wrong, when, and how.**

Troubleshooting a non-trivial automation without logs is like stumbling around a dark room hoping to trip over the problem and magically land on a solution. It's slow, frustrating, and hazardous to one's mental state.

So many engineers took matters into their own hands: if Salesforce won't keep logs for us, we'll keep them ourselves. That's how logging frameworks were born, and over the years they've become something thousands of developers and admins across the ecosystem quietly rely on every day.

## Pharos vs Pharos Triton

You might be wondering how Pharos and Pharos Triton relate. If it's all Greek to you, allow us to elaborate.

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-1094a2c817e3e712c65c6cb280d4fb8ff67b8429%2Fimage%20(20).png?alt=media" alt=""><figcaption><p><em>The Mighty Triton - Messenger From the Depths Of the Sea</em></p></figcaption></figure>

### Pharos

Pharos is a Salesforce-native observability platform, composed of several layers: tracking, awareness, action, collaboration, and resolution. It does far more than create logs — it's an entire suite that runs on log data: notifications, analytics, grouping, monitoring, and issue tracking. Pharos can even generate log records automatically from certain Salesforce system events, and there's quite a bit of data in those.

But system events aren't the only way to feed the platform. That's where Triton comes in.

### Pharos Triton

Pharos Triton is the ingestion component of the broader Pharos platform. It's responsible for capturing log data from your own automation — Apex, LWC, Flows, custom REST APIs, even emails. In the diagram below, note the section on the bottom right in blue. That's Pharos Triton.

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-38ce31cfb55ea6e82f210e8ff52cac18f79166f5%2FPharos%20Observability%20Platform%20(1).png?alt=media" alt=""><figcaption><p><em>Components of the Pharos Observability Platform and Pharos Triton</em></p></figcaption></figure>

## What Exactly Does Pharos Triton Do?

Simply put, Pharos Triton is a logging framework for all things Salesforce. It lets you create logs from your automation — code or declarative — where a single log record can carry any useful data point: debug info, warnings, integration payloads, governor-limit stats. If you can capture it, you can log it.

The mechanics are deliberately simple. As of [2.0](https://triton.pharos.ai/release-notes/2.0), Triton exposes a **static, builder-first API**: you describe a log with a fluent builder and hand it to `Triton`, which keeps the running state of your transaction for you.

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t
    .area(TritonTypes.Area.OpportunityManagement)
    .summary('Recalculated rollups'));
```

{% endcode %}

That same builder scales up to partial-DML capture, integration payloads, and governor-limit tracking — all covered in [Core Concepts](https://triton.pharos.ai/core-concepts). Because Triton persists logs through platform events, it can also act as a connector: ingest data from an external system like MuleSoft, shape it into a log record, and feed it into the rest of the Pharos platform.

## One Transaction, End to End

A single click in the UI almost never stays in one place. A user presses a button in a Lightning Web Component, that calls an Apex controller, the controller commits a record, and the DML fires off an autolaunched Flow. Four contexts, one intent — and, without help, four disconnected piles of logs.

Triton's defining capability is turning those piles into **one story**. It correlates logs across LWC, Apex, and Flow using a shared **transaction id**, so when you open a log in Pharos you can follow the whole chain from the button press to the Flow that failed three hops later.

* **A transaction id that travels.** The id can ride along explicitly (pass it from LWC into Apex) or automatically through the [platform cache](https://triton.pharos.ai/end-to-end/transactions-and-cache) — so it survives the hops between contexts without you threading it everywhere.
* **Spans for structure.** On top of correlation, `spanId` / `parentSpanId` add parent-child nesting *within* a transaction, turning a flat list of logs into a tree: the click, the backend call it triggered, and the step that call ran inside.
* **Errors that come along for free.** Unhandled Flow errors are captured and correlated automatically — no fault path required — so nothing in the chain goes dark.

{% content-ref url="/pages/yOdpD3VSNncFGaebUTPF" %}
[End-to-End Logging](https://triton.pharos.ai/end-to-end)
{% endcontent-ref %}

## Built for AI-Assisted Development

Instrumenting an existing codebase by hand is the least glamorous job in engineering. Triton 2.0 ships alongside a set of [**instrumentation skills**](https://triton.pharos.ai/instrumentation-skills) — portable, agent-agnostic playbooks that any AI coding agent (Claude Code, Cursor, Copilot, and others) can follow to add convention-following logging to your Apex, LWC, and Flows.

Point an agent at a file — or an entire org — and it reads the code, infers the right structure, and proposes instrumentation, always behind a **human-in-the-loop diff review** so nothing is written until you approve it. It's the tedious 90% of a logging rollout, automated, without giving up control.

And instrumentation is only half the story. Because Triton produces **structured, classified, correlated** log data — not free-text `System.debug` noise — it gives AI tooling a clean, machine-readable signal to reason over when analyzing failures and behavior across your org.

{% content-ref url="/pages/PW2a4ljzASpISTDPbZF3" %}
[Instrumentation Skills](https://triton.pharos.ai/instrumentation-skills)
{% endcontent-ref %}

## IT-Friendly: The First Step Toward OpenTelemetry

Salesforce is too often an observability island, cut off from the tracing standards the rest of IT runs on. Getting off that island starts with capturing your automation in a shape the wider world understands — and that's exactly what Triton does. Its tracing model — a **transaction id** that correlates a whole operation, plus **spans** and **parent spans** that add parent-child structure — maps directly onto the vocabulary platform teams already speak:

| OpenTelemetry concept | Triton 2.0 equivalent                                   |
| --------------------- | ------------------------------------------------------- |
| **Trace**             | The transaction id correlating one end-to-end operation |
| **Span**              | `Span_Id__c`, set via `.spanId(...)`                    |
| **Parent span**       | `Parent_Span_Id__c`, set via `.parentSpanId(...)`       |

Instrumenting with Triton is the concrete first step of the OpenTelemetry journey: you capture your telemetry once, at the source, in a model that already speaks OTel's language — so the data is ready to travel beyond Salesforce when you are.

{% hint style="info" %}
**A foundation, not the finish line.** Triton isn't an OpenTelemetry SDK, and it doesn't need to be — its job is to produce OTel-shaped telemetry at the source, which is the hard part. From there, bridging that data into a broader OpenTelemetry pipeline is a natural next step on the Pharos platform. See [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) for the full mapping.
{% endhint %}

## How Does Pharos Triton Compare to Other Logging Frameworks?

On features and functionality, Pharos Triton is a top-tier logging framework. If you're familiar with the Nebula logger library, you'll find Triton just as powerful and easier to navigate and extend. Like Nebula, it uses platform events to persist logs and offers ready-made interfaces for Apex, LWC, and Flow.

What really sets Triton apart is that it isn't just a log utility — it's the front door to a full observability platform. You get automated error capture, fingerprinting and categorization, issue tracking, and pre-built dashboards to analyze log data, plus Slack and Teams notifications. And unlike Nebula, Pharos is a commercial solution, so you get real support for any issues you hit — even on the free tier.

## Is Pharos Triton Free?

The short answer is yes. The Pharos platform [is offered in multiple editions](https://pharos.ai/pricing), including a free tier, and the Triton component works with any of them. It's just a matter of choosing how much observability functionality you want. You can absolutely run Triton on Pharos Free with no loss of logging capability.

## Logging Use Cases

The world of logging is vast, and what you can achieve is really only limited by your imagination. That said, here are the common directions teams take on their logging journey.

### Troubleshooting

Troubleshooting is about finding the root cause of a problem you know is happening: something isn't working, but you don't know where it originates. The range of "troubles" one can "shoot" is enormous — from user errors to automation failures — and the idea is the same throughout: the data in your logs tells you why the execution went the way it did.

**Primary beneficiaries:** developers, admins, and ultimately end users

### Profiling

Sometimes there's no outright failure — just a performance drag on an LWC page, a Flow, or an Apex trigger, or you're creeping toward (or hitting) governor limits. Here it's invaluable to see resource consumption broken down by each step: SOQL queries, CPU time, execution time, callout time, and more.

**Primary beneficiaries:** developers, admins, end users

### Tracing

In more advanced territory, you find yourself navigating complex, multi-step transactions — a screen Flow that commits a record, which fires an Apex trigger, which launches an autolaunched Flow. Tracing records every step so you can confirm the order of operations is what you expect. With Triton's transaction id and spans, that trace spans LWC, Apex, and Flow — and maps cleanly onto [OpenTelemetry](https://triton.pharos.ai/end-to-end/spans-and-tracing) concepts your platform team already knows.

**Primary beneficiaries:** developers, admins, platform/IT teams

### Auditing

Some organizations have strict compliance requirements around key areas — a financial institution, say, tracking every step of a complex financial exchange. But auditing is valuable even without a compliance mandate: it's how you confirm that what you *expect* to happen actually does. A closed opportunity that kicks off external provisioning, order creation, and outbound comms deserves an audit trail for every step — it's how you catch silent disconnects before they become disasters.

**Primary beneficiaries:** business, operations, legal

### User Experience

This one is about adoption. Are your users reaching the end of your screen Flows? Where are the time-consuming steps in that custom LWC they live in all day? Where do people drop off in your application process? Analyzing the log trail of real user interactions surfaces answers that are otherwise unavailable — or extremely hard to get through traditional UX studies.

**Primary beneficiaries:** UX designers, admins, end users

### AI-Assisted Analysis

Structured logs aren't just for humans reading a dashboard. Because Triton output is classified and correlated, it's a clean signal for AI tooling — feeding automated triage, anomaly spotting, and root-cause analysis, and closing the loop with the [instrumentation skills](https://triton.pharos.ai/instrumentation-skills) that produced it in the first place.

**Primary beneficiaries:** developers, admins, platform/IT teams


# Installing Pharos Triton

Your journey into logging starts here! This article details how to set up the Pharos Triton tools so you can incorporate logging into your own code base.

## 1. Installing and Configuring Pharos <a href="#h_01hswdbmj3y683vqpc8npwc2f2" id="h_01hswdbmj3y683vqpc8npwc2f2"></a>

First, install the Pharos managed package, which includes the observability platform. There are several options:

* Signup for Pharos Free edition [from our website](https://pharos.ai/pricing/102).
* Sign up for a paid edition trial by visiting our [AppExchange listing here](https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3A00000FMhhvUAD).

Next, complete the basic configuration steps. Please refer to [the Pharos quick start](https://docs.pharos.ai/configuration-guide/quick-start). The entire process shouldn't take more than 10 minutes of your time, depending on how quickly the package installs in your org.

{% hint style="warning" %}
**Triton 2.0 requires Pharos 2.284.5 or later.** Upgrade Pharos before you install or deploy Triton.
{% endhint %}

{% hint style="info" %}
Pharos Free Edition is indeed **free.** Completely. Now and forever. No hidden fees. This is our contribution to the Salesforce community and we will stand by it.
{% endhint %}

## 2. Deploy Pharos Triton <a href="#id-01hswedx82r2bk16vnnmd9vnjv" id="id-01hswedx82r2bk16vnnmd9vnjv"></a>

There are 2 delivery methods. We recommend option A for its simplicity.

{% hint style="warning" %}
**Already running Triton 1.x?** The 2.0 install fails while any Apex in the org still calls 1.x. Follow [Upgrading an Org from 1.x](https://triton.pharos.ai/migration/upgrading-an-org) before you install.
{% endhint %}

* **Option A:** Deploy via an unlocked package
  * [Sandbox install link](https://resources.pharos.ai/pharos-triton-sandbox)
  * [Production (non-sandbox) install link](https://resources.pharos.ai/pharos-triton-prod)\\
* **Option B:** Visit us at [this Github repo](https://resources.pharos.ai/pharos-triton-github). The code is available and free for all to use and modify as necessary. Feel free to utilize your favorite IDE or deployment tool to release the logger code in all environments as necessary. We recommend that the log util is deployed to production once it has been vetted through your development process. As your sandboxes are refreshed the log util will become available there as well.

{% hint style="info" %}
If you've evaluated Pharos in the past and installed the Error Generator package, you may notice there is a Log.cls file included. This is actually a condensed version of Pharos Triton with some slight modifications. We recommend you use the official Triton version, however.
{% endhint %}

## 3. Triton Configuration <a href="#h_01hswdbmj3y683vqpc8npwc2f2" id="h_01hswdbmj3y683vqpc8npwc2f2"></a>

All of Triton's admin configuration lives in one place in the Pharos app. Navigate to **Pharos Admin → Advanced → Triton**.

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-e2bdd0868c50dba5cb41aadb32b76b09f644ac45%2Ftriton-admin-menu.png?alt=media" alt="Pharos Admin Advanced menu with Triton selected"><figcaption><p>Pharos Admin → Advanced → Triton</p></figcaption></figure>

The Triton area has its own left-hand navigation:

* **Configuration** — the platform event, settings, log-level, persistence-level, and trace-link controls covered below.
* **X-Ray Machine** — adds Triton logging to a Flow for you: it inserts Triton **Log** actions between the Flow's elements, giving you a breadcrumb trail without placing each action by hand. It works with screen, autolaunched, and scheduled Flows, but not with before-update Flows.
* **Resources** — deployment links (sandbox / production install), the GitHub repository, and a link to this documentation.

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-0a9bffc1a4b16d5b8219076724d2dddeee25c803%2Ftriton-nav.png?alt=media" alt="Triton area navigation: Configuration, X-Ray Machine, Resources"><figcaption><p>The Triton area navigation</p></figcaption></figure>

**Configuration** is organized into five tabs — **Platform Event**, **Settings**, **Log Levels**, **Persistence Level**, and **Trace Links**.

### 3a. Platform Event

Pharos Triton is based on platform events. In other words, every time logs are flushed, a platform event gets fired off.

In this section we will configure Pharos to raise platform events, thus enabling the use of the log util. These controls now live on the **Platform Event** tab of Triton → Configuration.

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-b73e4938046365abd27e255c41c0bc7fb5de233c%2Ftriton-config-platform-event.png?alt=media" alt="Triton Configuration - Platform Event tab"><figcaption><p>Triton → Configuration → Platform Event</p></figcaption></figure>

Follow the steps in this quick tutorial to complete the configuration, and you're done!

{% embed url="<https://app.arcade.software/share/rk1d50LwD0F3ccO5JAqf>" %}

Feel free to run a test at the end as well. You can come back to the results in the Logs tab in case the test takes a little while.

{% hint style="info" %}

### Why Platform Events? <a href="#h_01ht0gsafztervtjm33sb0emd7" id="h_01ht0gsafztervtjm33sb0emd7"></a>

Platform events are a great way to ensure reliable logging that will not get rolled back no matter what happens to the original transaction. Platform event operations also don't not count against DML limits, which is important in high volume processing situations. It is the de facto standard for logging on the Salesforce platform and is utilized by many other open source logging frameworks. For more information about platform events please refer to [Salesforce developer documentation](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_intro.htm).
{% endhint %}

### 3b. Settings

The **Settings** tab exposes Triton's runtime switches and operational knobs. These map directly to Triton's `TritonSettings__c` custom settings.

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-8a3bf96fbb580025255f6cb43f783ced8cbc981a%2Ftriton-config-settings.png?alt=media" alt="Triton Configuration - Settings tab"><figcaption><p>Triton → Configuration → Settings</p></figcaption></figure>

**Master Switch**

* **Enable logging** — the master switch for all Triton logging (Apex, Flow, and LWC). Turn it off to short-circuit every log before it is built or persisted — a global kill switch for maintenance windows or noisy incidents.
* **Enable flow flush batch** — controls how Flow logs are published. When on, Flow logs are buffered and published by the asynchronous `TritonFlowFlushBatch`. When off, Flow logs are flushed immediately (synchronously, in-transaction). Either way, logging never fails the Flow.

**Operational Knobs**

Leave a field blank to use Triton's packaged default.

* **Flow flush batch delay (minutes)** — how long the flush batch waits before it runs, giving concurrent Flows time to add their logs to the shared buffer. Packaged default: **1 minute**. Keep it below the Cache TTL: Flow logs still waiting in the cache when the TTL expires are never published.
* **Cache TTL (minutes)** — how long Triton keeps the transaction id and buffered Flow logs in platform cache. Packaged default: **5 minutes**.

For the mechanics behind these, see [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing) and the [TritonFlowFlushBatch](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflowflushbatch) reference.

### 3c. Log Levels

The **Log Levels** tab is a visual editor for Triton's `Log_Level__mdt` rules — the same runtime filtering you'd otherwise manage as custom metadata. Each rule controls which logs Triton emits, scoped by any combination of **Level**, **Category**, **Type**, **Area**, **Component**, and **User**.

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-42d6a22d54a55bcc6a7883696a412bf0aff09c68%2Ftriton-config-log-levels.png?alt=media" alt="Triton Configuration - Log Levels tab"><figcaption><p>Triton → Configuration → Log Levels</p></figcaption></figure>

Click **NEW** to add a rule, or the pencil / trash icons to edit or delete an existing one. A rule sets a **Level** (the threshold) plus one or more scoping fields; leave a scope field blank to apply the rule more broadly.

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-69fcddc9685e5764c0bbf1931dbfff788bd11c04%2Ftriton-config-new-log-level-rule.png?alt=media" alt="New Log Level Rule dialog"><figcaption><p>Creating a new log level rule</p></figcaption></figure>

For how thresholds and specificity are resolved, see [Log Levels](https://triton.pharos.ai/core-concepts/log-levels) in Core Concepts.

### 3d. Persistence Level

The **Persistence Level** tab sets the minimum level Pharos stores in this org. Logs more verbose than that are dropped when Pharos ingests them, though they are still exported to an external telemetry backend if you have one. The default, **Off**, stores every log, and a log without a recognized level is always stored.

The two controls act at different points. A `Log_Level__mdt` rule stops Triton from publishing a log at all; Persistence Level decides what Pharos keeps after a log arrives. To reduce publishing volume, use Log Levels.

### 3e. Trace Links

**Trace Links** (Pharos 2.300 and later) — the OpenTelemetry backend that receives this org's logs through Hermes: Datadog, Grafana, Honeycomb, Splunk Observability, or a custom link template. Once set, every Log record page shows links that open the log's trace, or search for it, in that backend. The default, **Off**, shows no trace links.

## 4. Platform Cache Setup <a href="#platform-cache-setup" id="platform-cache-setup"></a>

Triton uses Org platform cache for two things: carrying a transaction id across contexts with `Triton.withCache()`, and holding Flow logs for the deferred flush batch, which is on by default. Both need a default partition with Org cache allocated, so set one up even if you never call `withCache()` yourself. (Triton's own Apex tests don't depend on it — they run against an in-memory stand-in for the cache.)

### Creating a Cache Partition

1. Navigate to **Setup → Platform Cache**
2. Click **New Platform Cache Partition**
3. Configure the partition with the following settings:
   * **Label**: `Default` (or your preferred name)
   * **Name**: `Default`
   * **Default Partition**: ✅ **Check this box** — This is critical! Triton requires a default partition to function properly with cache-based transaction management.

### Allocating Org Cache Memory

{% hint style="warning" %}
You must allocate memory to the **Org Cache Allocation** section for Triton's caching to work. Without Org cache allocation, Triton cannot store transaction IDs or buffer Flow logs.
{% endhint %}

4. In the **Org Cache Allocation** section, set the **Organization** value to at least `1` MB
5. Click **Save**

The image below shows the correct configuration with the Default Partition checkbox and Org Cache Allocation highlighted:

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-8922f63278f4c29053e5ef57387734a1e8d10105%2Fcache_partition.png?alt=media" alt="Platform Cache partition configuration showing Default Partition checkbox and Org Cache Allocation settings"><figcaption><p>Suggested cache partition configuration</p></figcaption></figure>

{% hint style="info" %}
For more detailed information on platform cache configuration, see [Set Up Platform Cache](https://help.salesforce.com/s/articleView?id=sf.data_platform_cache_setup.htm\&type=5) in the Salesforce documentation.

To learn how to use platform cache with Triton for LWC and Apex integration, see [Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache).
{% endhint %}

## 5. Configure Permissions <a href="#configure-permissions" id="configure-permissions"></a>

Pharos Triton comes with three permission sets to help manage access:

### Triton End User

* **Purpose**: Lets a user invoke Triton logging directly, from outside Apex
* **Access**: Apex class access only — no object permissions, no field-level security, no custom metadata access
* **Includes**: Access to the Triton Apex classes (`Triton`, `TritonBuilder`, `TritonFlow`, `TritonHelper`, `TritonLwc`, `TritonTypes`)

### Triton Read

* **Purpose**: For users who need to view and analyze logs
* **Access**: Read-only access to log fields and Log Level custom metadata, plus access to `LogLimitsController` — the set grants no object-level CRUD and no system permissions of its own
* **Includes**:
  * Read access to Log Level custom metadata
  * Read access to all log fields (CPU time, heap size, SOQL queries, etc.)
* **When to use**: Assign to developers, support staff, and business analysts who need to monitor and troubleshoot using logs

### Triton Write

* **Purpose**: For Triton and Pharos administrators, and for the platform-event subscriber that persists logs (see below)
* **Access**: Read and edit access to log fields, read access to Log Level custom metadata, plus access to the Triton Apex classes — the set grants no object-level CRUD and no system permissions of its own
* **Includes**:
  * Edit access to all log fields (CPU time, heap size, SOQL queries, span and transaction fields) — access to the Log object itself comes from your Pharos permission sets, not from this one
  * Read access to Log Level custom metadata — identical to `Triton Read`. Creating or editing a Log Level rule additionally requires the Customize Application system permission, whether through the Triton console or through Setup
  * Access to the Triton Apex classes — those in `Triton End User`, plus `LogLimitsController`
* **When to use**: Assign to Triton administrators, Pharos platform administrators, and the running user of the log subscriber

### Do you actually need Triton End User?

Salesforce only checks Apex class access at an **entry point** — the place where a user invokes Apex from outside Apex (an Aura/LWC `@AuraEnabled` call, an invocable action from a screen flow, a REST/SOAP request, a Visualforce controller). Once execution is inside Apex, every call it makes to another class runs unchecked, regardless of who kicked off the transaction.

That means the common case needs **no permission set at all**: a user saves a record, a trigger fires, the trigger's Apex calls `Triton.log()` to record what happened or catch an exception. The trigger runs in system context, so Salesforce never checks the user's access to the Triton classes. **Your general user population does not need `Triton End User`** just because their actions eventually cause a log to be written.

`Triton End User` is only needed by the user actually sitting at the entry point:

| Path into Triton                                      | Entry point?                                     | Needs `Triton End User`? |
| ----------------------------------------------------- | ------------------------------------------------ | ------------------------ |
| Apex trigger → `Triton.log()`                         | No — runs in system mode                         | No                       |
| Apex class, batch, queueable, `@future`, scheduled    | No                                               | No                       |
| Record-triggered / autolaunched flow (system context) | No                                               | No                       |
| Screen flow (user context) → Triton Log action        | Yes — `@InvocableMethod TritonFlow.log`          | Yes                      |
| LWC using the `triton` module                         | Yes — `@AuraEnabled TritonLwc.saveComponentLogs` | Yes                      |
| Visualforce / REST / SOAP calling Triton directly     | Yes                                              | Yes                      |
| Experience Cloud / guest users doing any of the above | Yes                                              | Yes                      |

Two things worth calling out explicitly:

* **Flows.** The line that matters is user context vs. system context, not screen vs. autolaunched. Screen flows always run as the user, so the Log action needs `Triton End User` on anyone who runs one. Record-triggered and autolaunched flows default to system context and need nothing — but an autolaunched flow explicitly configured to run in user context does need the permission set.
* **LWC is unavoidable.** Any component built on the `triton` LWC module calls `TritonLwc.saveComponentLogs`, a hard `@AuraEnabled` entry point — there's no system-context path around it. Every user of an instrumented LWC needs `Triton End User`, full stop. If that component sits in a customer community, that means every community user. Plan for it rather than discovering it in production.

{% hint style="info" %}
Best Practice: only assign `Triton End User` to the users who sit at one of the entry points above — most commonly, screen flow users and users of instrumented LWCs. Assign `Triton Read` to anyone monitoring logs, and reserve `Triton Write` for administrators and the platform-event subscriber.
{% endhint %}

### The platform-event subscriber needs Triton Write, not just Log\_Admin

Triton publishes a platform event; a separate subscriber process performs the actual `pharos__Log__c` insert when that event is received. That subscriber's running user needs **`Triton Write`**, because several of the fields Triton populates — the limit fields (CPU time, heap size, SOQL queries, etc.) and the span/transaction fields — are un-namespaced custom fields the subscriber needs field-level security on, on top of whatever access `Log_Admin` already grants.

If the subscriber is missing `Triton Write`, logs will still land — but silently missing their limit and span data. There's no error to alert you; the record is just incomplete. If new Apex or Flow logs arrive with the essential limit fields (CPU time, heap size, SOQL queries, DML, callouts) empty, check the subscriber's permission sets before anything else. The extended limit fields stay blank unless a log asks for `withFullLimitInfo()`, and LWC logs carry no limit data.

### Add the Log Limits component to the Log page

The `logLimits` component (**Log Limits** in Lightning App Builder) draws a usage bar for each governor limit a log captured. It can be placed only on the Log record page:

1. Open any Log record, then choose **Edit Page** from the Setup (gear) menu to open Lightning App Builder.
2. Drag **Log Limits** from the Custom components list onto the page.
3. **Save**, and activate the page if Salesforce prompts you.

### The Log Limits component needs Triton Read or Triton Write

The `logLimits` LWC component (the one that renders limit-usage bars on a Log record page) calls `LogLimitsController.getLimitUsage`. `LogLimitsController` is granted by both **`Triton Read`** and **`Triton Write`**, so anyone already monitoring logs with either set can use the component.

It is **not** granted by `Triton End User`. A user whose only Triton permission set is `Triton End User` — or who has none at all — gets an Apex class-access error on that component specifically when they open a Log page containing it. If you place the component on a page such users can reach, give them `Triton Read`.

## 6. Start Logging! <a href="#id-01hswedx82r2bk16vnnmd9vnjv" id="id-01hswedx82r2bk16vnnmd9vnjv"></a>

This is where the fun begins. We recommend you identify [which use cases](https://triton.pharos.ai/#logging-use-cases) you'd like to tackle first such as troubleshooting, tracing or profiling, or anything else. Once you have an idea of what you'd like to start with, head on over to [Core Concepts](https://triton.pharos.ai/core-concepts) to get started.


# Core Concepts

The mental model behind Pharos Triton — how the static logger, builder, templates, buffering, and transactions fit together before you write any logging code.

Before we get into batch jobs, LWC, Flows, and the finer points of taxonomy, it's worth spending a few minutes on the mental model. Triton is small on purpose — once these five ideas click, everything else in the docs is just a variation on them.

Here's the whole framework in one breath: **you describe a log with a builder, you hand that builder to `Triton`, and `Triton` keeps the running state of your transaction — the buffer, the transaction id, your template — statically, for the life of the Apex transaction.** That's it. The rest is detail.

## The five ideas

| Concept                     | One-liner                                                                                      | Read next                                                                                              |
| --------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| **The static API**          | You call `Triton` directly — `Triton.info(...)`, `Triton.error(...)` — no instances to manage. | [The Static Logging API](https://triton.pharos.ai/core-concepts/static-logging-api)                    |
| **The builder & templates** | A fluent `TritonBuilder` describes one log; a template stamps shared fields onto all of them.  | [The Builder & Templates](https://triton.pharos.ai/core-concepts/builder-and-templates)                |
| **Log levels**              | Levels rank severity and let you tune verbosity per environment without touching code.         | [Log Levels](https://triton.pharos.ai/core-concepts/log-levels)                                        |
| **Buffering & flushing**    | Logs queue in memory and publish in bulk, so you don't burn platform-event allocations.        | [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing) |
| **Enums**                   | `Category`, `Type`, and `Area` classify every log so it's filterable and analyzable later.     | [Enums](https://triton.pharos.ai/core-concepts/enums)                                                  |

## A first log

Here's what a complete, buffered log looks like in Triton 2.0:

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.makeBuilder()
    .category(TritonTypes.Category.Apex)
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.Accounts)
    .summary('Recalculated account rollups')
    .level(TritonTypes.Level.INFO));

Triton.flush();
```

{% endcode %}

Three moves, every time:

1. **Build** the log with a builder (`Triton.makeBuilder()` gives you one, pre-set to the `Apex` category).
2. **Hand it to `Triton`** — here `Triton.log(...)` adds it to the buffer.
3. **Flush** when you're ready to publish. (Need it persisted immediately? Use `Triton.logNow(...)` and skip the separate flush.)

If that looks like more ceremony than you want to repeat, good — that's exactly what [templates](https://triton.pharos.ai/core-concepts/builder-and-templates) and the [convenience level methods](https://triton.pharos.ai/core-concepts/static-logging-api) are for. The example above collapses to a one-liner once you've set a template:

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t.summary('Recalculated account rollups'));
```

{% endcode %}

## Where to go next

If you like learning top-down, read the five pages above in order — each builds on the last. If you'd rather learn by doing, jump straight to your context: [Logging in Apex](https://triton.pharos.ai/common-apex-usage-patters), [Logging in LWC](https://triton.pharos.ai/beyond-apex/lwc), or [Logging in Flow](https://triton.pharos.ai/flows).


# The Static Logging API

How Triton 2.0's static, builder-first API works — log methods, immediate vs buffered logging, level shorthands, and the transaction state kept for you.

In Triton 2.0 you talk to the logger through the `Triton` class directly. There's no logger to instantiate, no instance to pass around, and no singleton to fetch — you just call `Triton`:

{% code lineNumbers="true" %}

```apex
Triton.error(Triton.t.summary('Payment capture failed').exception(e));
```

{% endcode %}

This page covers the whole surface: how logs get built and sent, the difference between buffered and immediate logging, the convenience level methods, and — importantly — where all the state actually lives now that there's no instance.

## Building and sending a log

Every log follows the same shape: **build a description, hand it to a `Triton` method.** The builder describes *what* to log; the `Triton` method decides *how* (which level, buffered or immediate).

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.makeBuilder()
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.OpportunityManagement)
    .summary('Synced opportunity to ERP')
    .level(TritonTypes.Level.INFO));
```

{% endcode %}

You'll almost always start the builder with `Triton.makeBuilder()` (a fresh builder, pre-set to the `Apex` category) or `Triton.t` (a builder cloned from your [template](https://triton.pharos.ai/core-concepts/builder-and-templates)). More on both below.

## Buffered vs immediate

This is the one distinction worth internalizing. Triton can either **queue** a log for later or **publish** it right now.

| You want to…                          | Call                     | What happens                                                   |
| ------------------------------------- | ------------------------ | -------------------------------------------------------------- |
| Queue a log to publish later, in bulk | `Triton.log(builder)`    | Added to the buffer. Nothing is published until you `flush()`. |
| Publish a log right now               | `Triton.logNow(builder)` | Added to the buffer **and** flushed immediately.               |

{% code lineNumbers="true" %}

```apex
// Buffered — cheap, batched, published on flush()
Triton.log(Triton.t.summary('Step 1 complete'));
Triton.log(Triton.t.summary('Step 2 complete'));
Triton.flush();               // both published together, one platform event batch

// Immediate — published on the spot
Triton.logNow(Triton.t.summary('Critical failure').exception(e));
```

{% endcode %}

Why does this matter? Salesforce caps how many platform events you can publish, and every published log consumes an allocation. Buffering lets you publish many logs in one batch instead of one at a time. The trade-off: buffered logs are only in memory until you flush, so if the transaction dies first, they're lost. The rule of thumb — **buffer the routine, publish the critical immediately** — is covered in depth in [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).

## The convenience level methods

Setting `.level(TritonTypes.Level.ERROR)` on every builder gets old fast, so `Triton` gives you a method per level. Each one applies the level for you and buffers the log:

{% code lineNumbers="true" %}

```apex
Triton.error(builder);     // same as Triton.log(builder.error())
Triton.warning(builder);
Triton.info(builder);
Triton.debug(builder);
Triton.fine(builder);
Triton.finer(builder);
Triton.finest(builder);
```

{% endcode %}

So these two lines are identical:

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.t.summary('Retrying').level(TritonTypes.Level.WARNING));
Triton.warning(Triton.t.summary('Retrying'));
```

{% endcode %}

There's no `Triton.errorNow(...)` — for immediate publishing at a specific level, set the level on the builder and call `logNow`:

{% code lineNumbers="true" %}

```apex
Triton.logNow(Triton.t.summary('Critical').error().exception(e));
```

{% endcode %}

## Where the state lives now

If there's no instance, where does the buffer live? Where does the transaction id live? On the `Triton` class itself, as **static state that persists for the entire Apex transaction**. Everything you log during a transaction accumulates in the same place — one buffer, one transaction id, one template — held as `static` members:

* **The buffer** — a static list of pending logs, shared by every `Triton.log(...)` call in the transaction.
* **The transaction id** — a static `Triton.TRANSACTION_ID`, so all your logs correlate automatically.
* **The template** — a static builder you set once and reuse via `Triton.t`.
* **The underlying Pharos logger** — lazily initialized and reused.
* **Log-level config** — loaded once from `Log_Level__mdt` custom metadata.

Because Apex statics live for the duration of a single transaction, this gives you a "one logger, shared context" model with nothing to pass around. When the transaction ends, the statics reset, so there's no bleed between transactions.

{% hint style="info" %}
**Bulk / async note:** because the buffer is static per-transaction, the usual bulkification discipline applies — buffer as much as you can, then flush at safe boundaries. In async contexts (Batch, Queueable) each execution is its own transaction with its own fresh statics. See [Logging in Apex → Batch Logging](https://triton.pharos.ai/common-apex-usage-patters/batch-logging).
{% endhint %}

{% hint style="info" %}
Upgrading existing code that used `Triton.instance`? See the [Migrating from 1.x](https://triton.pharos.ai/migration) guide.
{% endhint %}

## Quick reference

{% code lineNumbers="true" %}

```apex
// Build
Triton.makeBuilder()            // fresh builder, category = Apex
Triton.t                        // builder cloned from the template (+ current transaction id)

// Buffer
Triton.log(builder)             // buffer at the builder's level
Triton.error(builder)           // buffer at ERROR  (also: warning/info/debug/fine/finer/finest)

// Publish
Triton.logNow(builder)          // buffer + flush this log now
Triton.flush()                  // publish everything buffered
Triton.flushTop()               // publish only the most recent buffered log
Triton.drain()                  // hand off the buffer without publishing (for batching)
// log, the level methods, logNow, flush, and flushTop never throw:
// a log that can't be published is dropped and noted in the Apex debug log

// Marks (buffered, logged at FINE)
Triton.startMark()              // open a timed span named <Class>.<method> from the stack trace
Triton.startTriggerMark()       // same, named <Handler>.<Trigger.operationType>
Triton.endMark()                // close the innermost open mark (call it in a finally)
Triton.clearMarks()             // discard open marks and reset to the request root

// Transactions
Triton.startTransaction()       // begin a correlation id
Triton.resumeTransaction(id)    // adopt an existing id
Triton.stopTransaction()        // clear it
Triton.withCache()              // back transaction state with platform cache
```

{% endcode %}


# 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). `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).
* When logs actually publish, and how to conserve platform events: [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).
* Correlating logs across LWC → Apex → Flow, and span-based tracing: [End-to-End Logging](https://triton.pharos.ai/end-to-end).


# Log Levels

How Triton log levels work — the severity scale, choosing the right level, and tuning verbosity per environment with Log\_Level\_\_mdt instead of code changes.

A **level** answers one question about a log: how important is it? Triton uses levels for two things — telling humans how urgent a record is, and deciding at runtime whether a log is even worth saving. The second part is the powerful one: you can turn the firehose up in a sandbox and down in production **without changing a line of code**.

## The scale

There are seven levels, ordered from least to most verbose:

| Level                       | Use it for                                                                                               |
| --------------------------- | -------------------------------------------------------------------------------------------------------- |
| `ERROR`                     | Something failed and needs attention — exceptions, failed callouts, broken invariants.                   |
| `WARNING`                   | Something recoverable or suspicious — retries, partial DML failures, deprecated paths.                   |
| `INFO`                      | Notable business events — "order placed", "sync completed". The default signal you'd want in production. |
| `DEBUG`                     | Developer-oriented detail useful while diagnosing.                                                       |
| `FINE` / `FINER` / `FINEST` | Increasingly chatty tracing — payload dumps, loop-level detail, everything-and-the-kitchen-sink.         |

Set the level on the builder, either explicitly or with the shorthand method:

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.t.summary('Order placed').level(TritonTypes.Level.INFO));
Triton.info(Triton.t.summary('Order placed'));   // identical
```

{% endcode %}

{% hint style="info" %}
Levels are ordered from least verbose (`ERROR`) to most verbose (`FINEST`). "Turning the level down to INFO" means: keep `ERROR`, `WARNING`, and `INFO`; drop everything more verbose. This is the same mental model as Salesforce's own debug log levels.
{% endhint %}

## Runtime filtering with `Log_Level__mdt`

Here's where levels earn their keep. Triton reads a custom metadata type, **`Log_Level__mdt`**, to decide which logs actually get persisted. Each record sets a **threshold** (a level) for some slice of your logs, scoped by any combination of five fields: **Category**, **Type**, **Area**, **Component**, and **User**.

The rule for a single record is simple: **a log is saved when its level is at or below that record's threshold.** Turn the threshold down and the chatty logs silently stop persisting; turn it up and they come back — all through metadata, deployable per environment.

### An example

Say you create one `Log_Level__mdt` record:

| Field    | Value  |
| -------- | ------ |
| Category | `Apex` |
| Level    | `INFO` |

Now, for any `Apex` log:

* `ERROR`, `WARNING`, `INFO` logs → **saved** (at or below the `INFO` threshold)
* `DEBUG`, `FINE`, `FINER`, `FINEST` logs → **dropped**

Bump that record to `FINEST` in your sandbox and every level flows through; drop it to `WARNING` in production and only warnings and errors persist. No code change, no redeploy of Apex.

### Scoping a rule

A record's scope fields decide *which* logs it applies to. A record **targets** a log only when **every** field it fills in matches that log; any field left blank is a wildcard that matches everything. A record with only `Category = Apex` set therefore applies to all Apex logs, while one that also sets `Component` and `User` applies to a single component for a single user.

| Field         | Matches against                     | Notes                                                                                                                                                                                      |
| ------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Category**  | The log's Category                  | e.g. `Apex`, `LWC`, `Flow`. Matched case-insensitively.                                                                                                                                    |
| **Type**      | The log's Type                      | e.g. `Backend`. Matched case-insensitively.                                                                                                                                                |
| **Area**      | The log's Area                      | Your functional area, e.g. `Community`. Matched case-insensitively.                                                                                                                        |
| **Component** | The component that produced the log | The Apex **class name**, the **LWC component name**, or the **Flow API name** — whichever matches the log's origin. Matched case-insensitively, but in full: `My_Flow-4` is not `My_Flow`. |
| **User**      | The running user                    | The 15-character Salesforce User Id. The one **case-sensitive** field — matching is exact on the 15-character form.                                                                        |

{% hint style="info" %}
**Component resolution.** The component is the Flow API name for Flow logs, the component name for LWC logs, and the class name for Apex logs. When an Apex log has no explicit operation, Triton derives the class from the stack trace so component-scoped rules still match — it only does this extra work when at least one component-scoped rule actually exists, so orgs without one pay nothing for it.
{% endhint %}

Matching on **Category**, **Type**, **Area** and **Component** is case-insensitive — they're free-text fields typed by hand, so `apex` and `Apex` mean the same thing. **User is the exception:** Salesforce Ids are case-sensitive base-62, and folding their case would collide distinct users, so a User Id is compared exactly, on its 15-character form.

{% hint style="warning" %}
**Case-insensitive matching silently widens rules you already have.** A rule field typed `apex` — which previously matched nothing, because the log's Category is `Apex` — now matches every Apex log. Review existing `Log_Level__mdt` rows for values whose case doesn't match what they were meant to target: a rule that had quietly never fired may start firing, and it may be more specific than the rule you thought was in charge.
{% endhint %}

Case is the only thing matching is forgiving about, because **the scope fields are free text, not picklists**. On `Log_Level__mdt`, `Category__c`, `Type__c`, `Area__c` and `Component_Name__c` are `Text(255)` and `User_Id__c` is `Text(15)` — only **Level** is a picklist. Nothing validates a scope value against anything real, so a rule keyed on a value that no longer exists — a renamed class, a retired Area, a Category removed in 2.0 — doesn't error. It silently stops matching, and that slice of logs falls back to whatever broader rule applies. When you rename or retire a value, re-key the rules that name it.

### How multiple rules combine

When several records target the same log, the **single most specific one wins** — and its threshold overrides the others in *both* directions. A narrow rule can raise verbosity for its slice above a broad default, or **lower** it below one, so you can turn a single noisy component or user down while leaving everything else untouched.

Specificity is ranked by which fields a rule fills in, from narrowest to broadest scope:

**User > Component > Area > Type > Category**

Naming a narrower field always outranks any combination of broader ones — a rule that sets only `User` beats a rule that sets `Component + Area + Type + Category`. If two rules are *equally* specific (they fill in the same fields), the more restrictive (less verbose) level wins, so the outcome never depends on metadata order.

Two examples, both starting from a global default record at `INFO`:

* **Boost one slice.** Add `Area = RestAPI`, `Level = FINEST`. For `RestAPI` logs the more specific rule wins → every level flows through, while everything else stays at `INFO`.
* **Silence one slice.** Add `Component = NoisyController`, `Level = ERROR`. For that component the more specific rule wins → only `ERROR` persists, while everything else still logs at `INFO`.

{% hint style="success" %}
**Sensible defaults, no surprises.** If a log has no level set, it's always saved. And if none of the matching rules exist in `Log_Level__mdt` at all, the log is saved too. Filtering only kicks in once you've explicitly configured a threshold that covers the log — so adding Triton to an org never silently swallows logs until you opt into filtering.
{% endhint %}

{% hint style="success" %}
**Filtering fails open, and a bad rule can't break your transaction.** A malformed `Log_Level__mdt` row — one with a blank **Level**, for instance — is skipped rather than thrown into the transaction that was doing the logging, so your remaining rules still apply. And a log whose own level Triton can't parse is **kept**, not dropped. When filtering can't decide, the log survives.
{% endhint %}

## Choosing levels well

* **Reserve `ERROR` for things a human should look at.** If everything is an error, nothing is.
* **Make `INFO` your production signal.** Ask "would I want to see this in prod?" — if yes, it's probably `INFO` or higher.
* **Push volume down the scale.** Loop bodies, payload dumps, and step-by-step traces belong at `FINE` and below, where filtering can switch them off cheaply.
* **Don't gate logs with `if` statements.** Resist `if (debugMode) Triton.debug(...)`. Log at the right level and let `Log_Level__mdt` decide — that's the whole point.

## Related reading

* Classifying logs by [Category, Type & Area](https://triton.pharos.ai/core-concepts/enums) — three of the fields that scope level filtering.
* [Log Levels: When to Use What](https://triton.pharos.ai/triton-best-practices/log-levels-and-usage) in Best Practices, for deeper guidance and examples.


# Buffering, Flushing & Deferred Publishing

How Triton buffers logs and publishes them as platform events — flush, flushTop, and drain, and why bulkification matters for platform-event limits.

Triton logs are published as **platform events**, and Salesforce puts a ceiling on how many of those you can fire. Buffering is how Triton respects that ceiling: instead of publishing each log the moment you create it, it queues logs in memory and publishes them together. This page explains the buffer, the methods that drain it, and how to buffer without ever losing a log that mattered.

## The buffer

Every `Triton.log(...)` (and every level method like `Triton.info(...)`) adds a log to an in-memory **buffer** — a static queue that lives for the duration of the transaction. Nothing leaves your org until you flush.

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t.summary('Step 1'));   // buffered
Triton.info(Triton.t.summary('Step 2'));   // buffered
Triton.info(Triton.t.summary('Step 3'));   // buffered
Triton.flush();                            // all three published together
```

{% endcode %}

Publishing three logs as one batch instead of three separate events is the entire game. In a trigger firing across 200 records, the difference between buffering and not buffering can be the difference between one platform event and hundreds.

## The three ways logs leave the buffer

| Method              | Publishes                                                    | Use when                                                                             |
| ------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------ |
| `Triton.flush()`    | **Everything** in the buffer, then clears it                 | You've reached a safe checkpoint and want your queued logs persisted.                |
| `Triton.flushTop()` | Only the **most recent** buffered log                        | You just logged something critical and want *it* out now, without flushing the rest. |
| `Triton.drain()`    | **Nothing** — returns the buffered logs and clears the queue | You want to hand logs off for someone else to publish later (e.g. a Flow batch).     |

`Triton.logNow(...)` is just sugar for "buffer this one, then `flushTop()`" — the convenient way to publish a single log immediately. If a log-level rule filters the log out, nothing is published and the rest of the buffer is left alone:

{% code lineNumbers="true" %}

```apex
Triton.logNow(Triton.t.summary('Critical failure').exception(e));
```

{% endcode %}

### `drain()` and deferred publishing

`drain()` is the newest of the three and exists for a specific problem: high-volume producers (Flows especially) that would otherwise burn platform-event allocations inline. Instead of publishing, they **drain** the buffer and hand the records to a batch that publishes them later, off the hot path. You rarely call `drain()` yourself in Apex — it powers the Flow flush batch. See [Logging in Flow → Deferred Flush & Batching](https://triton.pharos.ai/flows) and [End-to-End Logging](https://triton.pharos.ai/end-to-end).

## Buffer the routine, publish the critical

Buffering has one catch: **a buffered log only exists in memory until you flush it.** If the transaction throws (or hits a governor limit) before the flush, those queued logs are gone. That leads to a simple, reliable discipline:

* **Buffer the routine.** Progress logs, info, debug — queue them and flush at the end.
* **Publish the critical immediately.** For an exception you must not lose, use `Triton.logNow(...)` so it's persisted before anything else can go wrong.
* **Flush at boundaries.** End of a trigger handler, end of a batch `execute`, before a callout, in `finally` blocks — these are natural flush points.

{% code lineNumbers="true" %}

```apex
try {
    for (Account a : scope) {
        // ... work ...
        Triton.info(Triton.t.summary('Processed ' + a.Id));   // buffered, cheap
    }
    Triton.flush();                                            // publish the batch
} catch (Exception e) {
    Triton.logNow(Triton.t.summary('Batch failed').exception(e));   // never lose this one
}
```

{% endcode %}

{% hint style="warning" %}
**Watch the `finally`.** If there's meaningful risk of an exception between a log and its flush, either move the flush into a `finally` block or publish the important log immediately with `logNow`. A buffered log that never flushes is a log you'll wish you had.
{% endhint %}

## When publishing fails

Logging should never be the reason your code fails, so `Triton.log(...)`, the level methods, `Triton.logNow(...)`, `Triton.flush()`, `Triton.flushTop()`, and the performance-mark methods never throw into the caller. If Pharos can't accept a publish — the running user lacks a license or a permission, for example — the logs in that publish are **dropped**, not retried, and one `ERROR` line naming the failure and the number of logs lost is written to the Apex debug log. Your transaction carries on.

Three things are still yours to handle:

* **Builder arguments run in your code.** Everything inside the parentheses of `Triton.log(...)` is evaluated before Triton is called, so a null dereference there — `Trigger.newMap.keySet()` in a before-insert trigger, say — throws in your code. Keep builder arguments null-safe.
* **Governor limits.** `System.LimitException` can't be caught by any Apex. In bulk code, buffer and flush once at a boundary rather than calling `logNow` in a loop.
* **`Triton.stopTransaction()` with `withCache()` enabled** can still throw, if clearing the cached transaction id fails.

Triton doesn't throttle publishing on its own, so the discipline above — buffer, then flush in bulk at boundaries — is also what keeps you inside your platform-event allocation. For trigger handlers, see [Instrument Apex → Trigger handlers](https://triton.pharos.ai/instrumentation-skills/instrument-apex#trigger-handlers-logging-never-fails-the-write).

## Bulk & async notes

* **The buffer is per-transaction.** Because it's static, each Apex transaction starts with an empty buffer and clears at the end — no bleed between transactions.
* **In Batch and Queueable**, each `execute` is its own transaction. Flush within each execution (typically at the end) rather than assuming logs carry across chunks.
* **The same discipline as DML applies.** Think of `flush()` like a DML statement: do it in bulk, at boundaries, and out of loops.

## Related reading

* The methods in context: [The Static Logging API](https://triton.pharos.ai/core-concepts/static-logging-api).
* Real patterns for triggers, batches, and queueables: [Logging in Apex](https://triton.pharos.ai/common-apex-usage-patters).
* Correlating buffered logs across contexts: [End-to-End Logging](https://triton.pharos.ai/end-to-end).


# Enums

The Category, Type, and Area enums in TritonTypes — what each one classifies, the values that ship out of the box, and how to extend them for your own org.

Three fields classify every Triton log: **Category**, **Type**, and **Area**. Getting them right is what turns a pile of log records into something you can filter, group, and actually learn from. All three are defined as enums in `TritonTypes.cls`, plus a fourth enum — `Level` — for severity.

Why enums instead of free-text strings? Consistency. If half your team writes `"Accounts"` and the other half writes `"Account"`, no filter will ever line up. Enums make the value set explicit, discoverable in your IDE, and safe to refactor. You *can* pass raw strings where you need to (`.type(...)` and `.area(...)` accept them), but reach for the enum first.

## Category — the broad bucket

Category is the highest-level classification, and it matters for more than filtering: Pharos uses it to decide which page layout and detail view to render for the record. Mislabel an Apex log as a Flow log and it'll still capture your data, but the detail page won't show the Apex stack trace where you expect it.

The values that ship in `TritonTypes.Category`:

`Apex` · `Flow` · `LWC` · `Aura`

Category answers exactly one question — *what technology produced this log?* Severity is never expressed through Category; that's what the `Level` enum is for.

**Rule of thumb: match the technology you're logging from.** Logging from Apex? Use `Apex`. From a Lightning web component? `LWC`. Logging around a callout or integration from Apex? Keep the `Apex` category and attach the HTTP exchange with `.integrationPayload(...)` — there's no need to reach for a separate category or entity for integration logging. Many of Triton's built-in methods set the category for you — `Triton.makeBuilder()` starts you on `Apex`.

{% hint style="info" %}
Pharos' automated error capture also produces records under platform categories that aren't in this enum (for example Flow, Process Builder, Email-to-Case, Web-to-Lead). Those are set for you during automatic capture. For your own custom logging, stick to the enum values above.
{% endhint %}

## Type — the technical detail

Type is a finer, more technical classification written to the Type field. It doesn't affect how the record renders, so you have more freedom here. The out-of-the-box values in `TritonTypes.Type`:

| Value                                                                                        | Typical use                                                                                                                                                                                                                   |
| -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Backend`                                                                                    | Server-side Apex work (the common default).                                                                                                                                                                                   |
| `Frontend`                                                                                   | Client-side / UI-originated logs.                                                                                                                                                                                             |
| `DMLResult`                                                                                  | Logs summarizing bulk DML outcomes.                                                                                                                                                                                           |
| `LongRunningRequest`                                                                         | Slow requests worth flagging.                                                                                                                                                                                                 |
| `ConcurrentRequestsLimit`                                                                    | Concurrency-limit conditions.                                                                                                                                                                                                 |
| `AccountTrigger`                                                                             | Example of a domain-specific type.                                                                                                                                                                                            |
| `BackendCall` · `UserInteraction` · `ComponentLifecycle` · `ComponentRender` · `Performance` | Set by the LWC profiling APIs — see [Profiling](https://triton.pharos.ai/beyond-apex/profiling). `Performance` is also set by Apex [performance marks](https://triton.pharos.ai/common-apex-usage-patters/performance-marks). |

When you log an exception via `.exception(e)`, Triton sets the Type to the **exception's own type name** (e.g. `DmlException`, `CalloutException`), falling back to `Backend` when it can't determine one. That's usually exactly what you want.

## Area — the business context

Area (written to the **Functional Area** field) describes *what part of the business* a log is about, from a business perspective rather than a technical one. This is the classification you'll customize the most, because it's the most org-specific. The starter values in `TritonTypes.Area`:

`OpportunityManagement` · `LeadConversion` · `Community` · `RestAPI` · `Accounts` · `LWC` · `Flow`

Good areas read like features or domains: `DealRegistration`, `PartnerCommunity`, `InvoiceSync`, `AccountEnrichment`. Aim for the level of granularity you'd actually want to filter or alert on.

{% hint style="success" %}
**Add your own functional areas — but not by editing this enum.** There is no universal set of functional areas; the shipped values are just a starting point. Defining your own domains is expected and encouraged — just do it the upgrade-safe way, with your own `String`-constant classes rather than by editing `TritonTypes.cls`. See [Custom Classifications](https://triton.pharos.ai/core-concepts/custom-classifications).
{% endhint %}

## Level — severity

The fourth enum, `TritonTypes.Level`, ranks severity from least to most verbose: `ERROR` · `WARNING` · `INFO` · `DEBUG` · `FINE` · `FINER` · `FINEST`. It gets its own page because it also drives runtime filtering — see [Log Levels](https://triton.pharos.ai/core-concepts/log-levels).

## Adding your own values — the upgrade-safe way

Sooner or later you'll want classifications the shipped enums don't cover — an `InvoiceSync` area, a `Callout` type. The tempting move is to add them straight to the enum in `TritonTypes.cls`. **Resist it.** Apex enums can't be extended from the outside, so the only way to add a value is to edit the shipped `TritonTypes.cls` — and that file belongs to Triton. Your additions get clobbered (or cause merge conflicts) the next time you upgrade.

Treat the built-in enums as convenient defaults you *use* as-is, not values you extend. When you need your own `Type` and `Area` values, define them as `public static final String` constants in your *own* classes and pass them to `.area(...)` / `.type(...)`:

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t.area(TritonArea.INVOICE_SYNC).summary('Invoice pushed to ERP'));
```

{% endcode %}

Those constant classes are yours, so no Triton upgrade will ever touch them — and you keep the consistency, typo-safety, and IDE discoverability that made enums appealing in the first place. See [Custom Classifications](https://triton.pharos.ai/core-concepts/custom-classifications) for the full pattern (and why `Category` is the one exception you should still leave as an enum).

Keep additions deliberate and documented — the value of a taxonomy is that everyone uses the same one. For guidance on designing a taxonomy that scales, see [Taxonomy & Standards](https://triton.pharos.ai/triton-best-practices/taxonomy-and-standards).


# Custom Classifications

Add your own Type and Area values the upgrade-safe way — with your own String-constant classes instead of extending Triton's shipped enums.

Triton ships with a set of built-in `Category`, `Type`, and `Area` values (see [Enums](https://triton.pharos.ai/core-concepts/enums)), and they're perfectly fine to use as-is out of the box. But every org eventually wants its *own* classifications — an `InvoiceSync` area, a `Callout` type — and the obvious move is to crack open `TritonTypes.cls` and add them to the enum. Don't. This page shows the convention we recommend instead.

## The problem with extending the enums

Apex enums can't be extended from the outside. There's no `implements`, no subclassing, no "add a value in your own file." The only way to add `InvoiceSync` to `TritonTypes.Area` is to edit the shipped `TritonTypes.cls` enum directly.

That one edit quietly signs you up for a recurring tax:

* **Upgrades clobber your changes.** `TritonTypes.cls` is a Triton file. When you pull a newer version of Triton, your additions get overwritten — or, worse, you hit merge conflicts every single upgrade and have to re-reconcile the enum by hand.
* **You now own a fork of a vendor file.** Every future Triton release becomes a manual merge instead of a clean install.

{% hint style="warning" %}
**Don't edit `TritonTypes.cls` (or any shipped Triton class) to add your own values.** Anything you add there is fair game to be clobbered on the next upgrade. Keep your customizations in files that are *yours*.
{% endhint %}

## The convention: your own constant classes

The builder already accepts plain `String` values for the two classifications you'll actually want to customize — `type(String)` and `area(String)`. So instead of extending an enum, define your own class of `public static final String` constants and pass those. The file is yours; no Triton upgrade will ever touch it.

Create a class per classification. Here's an `Area` catalog for your org:

{% code lineNumbers="true" %}

```apex
public class TritonArea {
    public static final String INVOICE_SYNC = 'InvoiceSync';
    public static final String ACCOUNT_ENRICHMENT = 'AccountEnrichment';
    public static final String PARTNER_COMMUNITY = 'PartnerCommunity';
    public static final String DEAL_REGISTRATION = 'DealRegistration';
}
```

{% endcode %}

And a `Type` catalog:

{% code lineNumbers="true" %}

```apex
public class TritonType {
    public static final String CALLOUT = 'Callout';
    public static final String SCHEDULED_JOB = 'ScheduledJob';
    public static final String DATA_QUALITY = 'DataQuality';
}
```

{% endcode %}

Then log against your constants exactly the way you would against an enum:

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t
    .area(TritonArea.INVOICE_SYNC)
    .type(TritonType.CALLOUT)
    .summary('Invoice pushed to ERP'));
```

{% endcode %}

## Why this beats the alternatives

This convention sits deliberately between two worse options — raw string literals and enum extension — and takes the best of both:

* **vs. raw string literals** (`.area('InvoiceSync')`): literals invite typos (`'InvoceSync'` filters into oblivion), give you no IDE autocomplete, and offer no single place to see the full vocabulary. Constants fix all three — one typo-proof definition, discoverable in your editor, self-documenting.
* **vs. editing the enum**: you keep the consistency and discoverability of a fixed value set, but without the upgrade tax. Your constants live in *your* classes, so Triton upgrades stay clean.

In short: **the benefits of enums (consistency, no typos, autocomplete, self-documenting code) without the upgrade pain.**

{% hint style="info" %}
The values are just strings on the log record either way — `TritonArea.INVOICE_SYNC` and `TritonTypes.Area.OpportunityManagement` both end up as plain text in the Functional Area field. Mixing built-in enum values and your own constants in the same org is completely fine.
{% endhint %}

## The same values from LWC and Flow

Area is what groups a feature's logs across tiers, so use the same string everywhere. The LWC builder's `.area(...)` and the Flow **Log** action's **Area** input both accept any string and keep it as sent: `.area('InvoiceSync')` in a component lands next to `TritonArea.INVOICE_SYNC` from Apex. The LWC `AREA` constants carry the built-in Apex names (`AREA.ACCOUNTS` is `'Accounts'`), so they group with the `TritonTypes.Area` values too.

## A note on Category

`Category` is the exception, and it's worth calling out. Unlike `type(...)` and `area(...)`, the builder's **`category(...)` only accepts the `TritonTypes.Category` enum — there is no `category(String)` overload.** That's by design: Category drives how Pharos renders the log detail page and layout, so it isn't a free-form, business-specific field the way Type and Area are.

So this constants pattern is for **Type** and **Area** — the extensible, org-specific classifications. For **Category**, stick with the built-in enum values.

{% hint style="success" %}
**Do**

* Keep your custom `Type` and `Area` values in your own `public static final String` constant classes (e.g. `TritonArea`, `TritonType`).
* Pass them via `.area(TritonArea.INVOICE_SYNC)` and `.type(TritonType.CALLOUT)`.
* Use the built-in `TritonTypes` enum values as-is when they already fit.
* Use the `TritonTypes.Category` enum for Category — always.

**Don't**

* Edit `TritonTypes.cls` (or any shipped Triton class) to add your own values — upgrades will clobber them.
* Scatter raw string literals through your code — you lose typo-safety and discoverability.
* Invent custom Category strings — Category affects rendering, so keep it on the built-in enum.
  {% endhint %}

For guidance on designing a classification vocabulary that scales, see [Taxonomy & Standards](https://triton.pharos.ai/triton-best-practices/taxonomy-and-standards).


# Migrating from 1.x

Move your Apex from the Triton 1.x singleton to the 2.0 static, builder-first API — the method-by-method mapping and the one behavioral gotcha to audit.

Triton 2.0 is a breaking release, but the migration is mostly mechanical: the concepts you already know all carry over, they just wear different clothes. This page is the one place we talk about "1.x vs 2.0" — everywhere else in the docs, 2.0 is simply *Triton*. Read this once, run the find-and-replace, audit the one behavioral change that actually bites, and you're done.

{% hint style="info" %}
**Upgrading an org that already runs 1.x?** Salesforce refuses to install 2.0 while any Apex in the org still calls the 1.x API. [Upgrading an Org from 1.x](https://triton.pharos.ai/migration/upgrading-an-org) gives the order that works.
{% endhint %}

## The one idea that changed

In 1.x, you logged through a **singleton**: `Triton.instance`. That instance held the shared state of your transaction — the buffer, the transaction id, your template — so everything you logged accumulated in one place.

In 2.0, there's **no instance**. You call the `Triton` class directly, and you describe each log with a **builder**:

{% code lineNumbers="true" %}

```apex
// 1.x
Triton.instance.error(TritonTypes.Area.Accounts, e);

// 2.0
Triton.error(Triton.t.area(TritonTypes.Area.Accounts).exception(e));
```

{% endcode %}

Here's the reassuring part: **all that shared state didn't go anywhere.** The buffer, the transaction id, and the template are still shared for the life of the Apex transaction — they just live as **static members on the `Triton` class** now instead of on a singleton instance. Apex statics last exactly one transaction, so you get the same "one logger, shared context" guarantee the singleton gave you, with nothing to fetch and nothing to pass around. When the transaction ends, the statics reset — no bleed between transactions.

So the shift is really two moves you'll make on every call:

1. **Drop `.instance`** — call `Triton` statically.
2. **Move the log's details onto a builder** — `Triton.t` (a fresh clone of your template) or `Triton.makeBuilder()` (a plain builder, pre-set to the `Apex` category), then chain `.area(...)`, `.summary(...)`, `.exception(...)`, and friends.

> `Triton.t` is shorthand for `Triton.fromTemplate()`. Each call hands back a fresh clone of your template with the current transaction id already stamped on it.

## Method mapping

Most 1.x calls map cleanly onto a 2.0 builder expression. The pattern is always the same: pick the level method, build from `Triton.t`, and move the old positional arguments onto builder methods.

| Triton 1.x                                                                             | Triton 2.0                                                                                                                      |
| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `Triton.instance.error(area, e)`                                                       | `Triton.logNow(Triton.t.area(area).exception(e))`                                                                               |
| `Triton.instance.addError(area, e)`                                                    | `Triton.error(Triton.t.area(area).exception(e))`                                                                                |
| `Triton.instance.error(area, e, relatedObjectIds)`                                     | `Triton.logNow(Triton.t.area(area).exception(e).relatedObjects(relatedObjectIds))`                                              |
| `Triton.instance.addError(area, e, relatedObjectIds)`                                  | `Triton.error(Triton.t.area(area).exception(e).relatedObjects(relatedObjectIds))`                                               |
| `Triton.instance.error(type, area, summary, details)`                                  | `Triton.logNow(Triton.t.type(type).area(area).summary(summary).details(details).error())`                                       |
| `Triton.instance.addError(type, area, summary, details)`                               | `Triton.error(Triton.t.type(type).area(area).summary(summary).details(details))`                                                |
| `Triton.instance.warning(type, area, summary, details)`                                | `Triton.logNow(Triton.t.type(type).area(area).summary(summary).details(details).warning())`                                     |
| `Triton.instance.addWarning(type, area, summary, details)`                             | `Triton.warning(Triton.t.type(type).area(area).summary(summary).details(details))`                                              |
| `Triton.instance.debug(type, area, summary, details)`                                  | `Triton.logNow(Triton.t.type(type).area(area).summary(summary).details(details).debug())`                                       |
| `Triton.instance.addDebug(type, area, summary, details)`                               | `Triton.debug(Triton.t.type(type).area(area).summary(summary).details(details))`                                                |
| `Triton.instance.debug(type, area, summary, details, duration)`                        | `Triton.logNow(Triton.t.type(type).area(area).summary(summary).details(details).duration(duration).debug())`                    |
| `Triton.instance.addDebug(type, area, summary, details, duration)`                     | `Triton.debug(Triton.t.type(type).area(area).summary(summary).details(details).duration(duration))`                             |
| `Triton.instance.event(level, type, area, summary, details)`                           | `Triton.logNow(Triton.t.type(type).area(area).summary(summary).details(details).level(level))`                                  |
| `Triton.instance.addEvent(level, type, area, summary, details)`                        | `Triton.log(Triton.t.type(type).area(area).summary(summary).details(details).level(level))`                                     |
| `Triton.instance.event(type, area, summary, details)`                                  | `Triton.logNow(Triton.t.type(type).area(area).summary(summary).details(details).info())`                                        |
| `Triton.instance.addEvent(type, area, summary, details)`                               | `Triton.info(Triton.t.type(type).area(area).summary(summary).details(details))`                                                 |
| `Triton.instance.dmlResult(area, results)`                                             | `Triton.logNow(Triton.t.area(area).dmlResults(results))`                                                                        |
| `Triton.instance.addDMLResult(area, results)`                                          | `Triton.error(Triton.t.area(area).dmlResults(results))`                                                                         |
| `Triton.instance.integrationError(area, e, request, response)`                         | `Triton.logNow(Triton.t.area(area).exception(e).integrationPayload(request, response))`                                         |
| `Triton.instance.addIntegrationError(area, e, request, response)`                      | `Triton.error(Triton.t.area(area).exception(e).integrationPayload(request, response))`                                          |
| `Triton.instance.integrationError(type, area, summary, details, request, response)`    | `Triton.logNow(Triton.t.type(type).area(area).summary(summary).details(details).integrationPayload(request, response).error())` |
| `Triton.instance.addIntegrationError(type, area, summary, details, request, response)` | `Triton.error(Triton.t.type(type).area(area).summary(summary).details(details).integrationPayload(request, response))`          |
| `Triton.instance.log(builder)`                                                         | `Triton.logNow(builder)` — 1.x `log` published immediately                                                                      |
| `Triton.instance.addLog(builder)`                                                      | `Triton.log(builder)`                                                                                                           |
| `Triton.instance.setTemplate(builder)`                                                 | `Triton.setTemplate(builder)`                                                                                                   |
| `Triton.instance.fromTemplate()`                                                       | `Triton.fromTemplate()` (or just `Triton.t`)                                                                                    |
| `Triton.instance.flush()`                                                              | `Triton.flush()`                                                                                                                |
| `Triton.instance.flushTop()`                                                           | `Triton.flushTop()`                                                                                                             |
| `Triton.instance.withCache()`                                                          | `Triton.withCache()` — returns `void` in 2.0, so split any call chained off it                                                  |
| `Triton.instance.TRANSACTION_ID`                                                       | `Triton.TRANSACTION_ID`                                                                                                         |
| `Triton.instance.logs`                                                                 | `Triton.logs` (test assertions only)                                                                                            |
| `Triton.instance.startTransaction()`                                                   | `Triton.startTransaction()`                                                                                                     |
| `Triton.instance.resumeTransaction(id)`                                                | `Triton.resumeTransaction(id)`                                                                                                  |
| `Triton.instance.stopTransaction()`                                                    | `Triton.stopTransaction()`                                                                                                      |

A few rows deserve a note:

* **Http and REST payloads share one mapping.** Each 1.x integration-error overload exists twice, once taking `HttpRequest`/`HttpResponse` and once taking `RestRequest`/`RestResponse`. `integrationPayload(...)` accepts either pair, so the rewrite is the same.
* **The six-argument `integrationError` flushed everything.** In 1.x it published the whole buffer, not just its own log. `Triton.logNow(...)` publishes only that log, so add a `Triton.flush()` after it if you relied on the rest going out too.
* **The DML rows are correct as written.** Like 1.x, `dmlResults(...)` emits nothing when every row succeeded — whichever method you pass it to — so the rewrite needs no failure check around it.
* **Match the overload, not just the name.** Most 1.x logging methods are overloaded, and the overloads map differently. If a call's exact shape isn't in this table, map it by hand from the 1.x method body rather than guessing from the name.

The transaction and template methods are the easy ones — same names, just without `.instance`. The logging methods are where the shape changes, and where the one real gotcha lives.

The `event` rows deserve a word: **`event`/`addEvent` map to a Level, not a category.** In 1.x they stamped an `Event` category on the log; in 2.0 that category is gone, so the mapping simply omits `.category(...)` and lets the builder's `Apex` default apply — these are Apex APIs, so categorize by the call site, and set `.category(...)` only when that call site genuinely bridges another technology. The level follows the overload: the forms that took a `level` keep it via `.level(level)`, the four-argument forms (no level) become `INFO`, and the bare `event` published immediately, so it goes to `Triton.logNow(...)` like the other bare methods. The same goes for any legacy severity-shaped categorization: a "debug" log is a `DEBUG`-**Level** log (`Triton.debug(...)`), a "warning" is `Triton.warning(...)` — the `addWarning`/`addDebug` rows above already land there.

**Post-processing isn't carried across.** The 1.x warning, debug, and event methods asked Pharos for a narrower post-processing set — stack trace, user info, and related objects. 2.0 sets no post-processing controls on Apex logs, so they get the Pharos defaults. To keep the narrower set on a rewritten call, append `.postProcessing(Triton.makePostProcessingBuilder().stackTrace(true).userInfo(true).relatedObjects(true))`.

## The behavioral change to audit for

This is the part that can quietly change what your code does, so read it carefully.

**In 1.x, the method name decided when the log published:**

* Bare methods — `error(...)`, `warning(...)`, `debug(...)`, `event(...)`, `dmlResult(...)`, `integrationError(...)`, and `log(...)` — published **immediately**.
* `add*` methods — `addError(...)`, `addWarning(...)`, `addDebug(...)` — **buffered**, waiting for a `flush()`.

**In 2.0, the level methods all buffer.** `Triton.error(...)`, `Triton.warning(...)`, `Triton.info(...)`, and the rest add to the buffer and wait for a flush. You opt *into* immediate publishing explicitly with **`Triton.logNow(...)`**.

That inversion is why the mapping table sends the old **bare** methods (`error`, `warning`, …) to **`Triton.logNow(...)`** and the old **`add*`** methods to the **level methods** (`Triton.error`, …).

{% hint style="warning" %}
**Audit every old bare-method call.** If you had code relying on `Triton.instance.error(...)` persisting a log the instant it ran — before a later exception, a callout, or a governor limit could kill the transaction — the naive rename to `Triton.error(...)` will now **buffer** that log instead. If nothing flushes before the transaction dies, the log is lost. Either switch those to `Triton.logNow(...)`, or make sure there's a reliable `Triton.flush()` (ideally in a `finally` block) covering them.
{% endhint %}

The flip side is a nice win: buffering is now the default, so routine progress logs batch up cheaply and you only pay the platform-event cost when you deliberately flush. See [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing) for the full model.

## If you vendor Triton as source

If the `Triton*.cls` files live in your repository rather than arriving as a package, upgrading the library is part of the migration: 2.0 removes `Triton.instance`, so the library and every caller have to land together. Settle three things first:

* **Keep your org-local enum values.** Diff your `TritonTypes` against the 2.0 one and re-add any values you'd added; a wholesale copy drops them, and every reference stops compiling. Going forward, keep new values in your own `String` constants (see [Use real enum values](#use-real-enum-values)).
* **Migrate the branch that holds every caller.** In a repository with a promotion pipeline, the integration branch can be well ahead of the default branch.
* **Keep Jest tests out of deploys.** Add `**/__tests__/**` and `**/__mocks__/**` to your project's `.forceignore`. Triton's own repository ignores them, but a `.forceignore` only governs its own project.

## Prefer `.exception(e)` over hand-set fields

In 1.x it was common to spell out an error's type, summary, and stack trace by hand. In 2.0, let the builder do it. **`.exception(e)`** 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 — all in one call:

{% code lineNumbers="true" %}

```apex
// Don't hand-assemble the error
Triton.error(Triton.t
    .area(TritonTypes.Area.OpportunityManagement)
    .type(TritonTypes.Type.Backend)
    .summary(e.getMessage())
    .details(e.getStackTraceString()));

// Do this instead
Triton.error(Triton.t
    .area(TritonTypes.Area.OpportunityManagement)
    .exception(e));
```

{% endcode %}

While you're migrating, this is a good moment to collapse those hand-built error logs down to `.exception(e)`. Fewer lines, and you pick up issue-creation flagging for free. Same idea for bulk DML: reach for `.dmlResults(results)` instead of assembling failure summaries yourself.

## Use real enum values

Migrating is a good time to make sure every `Category`, `Type`, and `Area` you pass is an actual `TritonTypes` enum value rather than an ad-hoc string that drifted in over time. Consistent values are the whole point of the taxonomy — filters and dashboards only line up when everyone uses the same names.

{% hint style="warning" %}
**`TritonTypes.Category.Integration` no longer exists in 2.0** — Apex referencing it won't compile. Drop the `.category(TritonTypes.Category.Integration)` call and keep `.integrationPayload(request, response)`: the builder defaults to the `Apex` category, and these logs now also capture the Apex execution context. (The Flow and LWC bridges still accept the string `'Integration'`: they map it to that context's default category and append a note to Details.) See [Integration Logs](https://triton.pharos.ai/common-apex-usage-patters/integration-logs) for the current pattern.
{% endhint %}

{% hint style="warning" %}
**The `Warning`, `Event`, and `Debug` categories no longer exist in 2.0** — Apex referencing `TritonTypes.Category.Warning`, `.Event`, or `.Debug` won't compile. Category now answers only "what technology produced this?" (`Apex` · `Flow` · `LWC` · `Aura`); severity belongs in the log **Level**. Deployed Flows and LWCs still passing the old strings keep logging — they're re-categorized to `Flow`/`LWC` with a diagnostic note appended to Details. If you have `Log_Level__mdt` rules keyed on Category = `Event`/`Warning`/`Debug`, re-key them to a real origin Category or to a Level — they stop matching logs from upgraded producers. Historical logs keep their stored category strings.
{% endhint %}

The shipped `TritonTypes.Area` values are:

`OpportunityManagement` · `LeadConversion` · `Community` · `RestAPI` · `Accounts` · `LWC` · `Flow`

So use the real thing:

{% code lineNumbers="true" %}

```apex
Triton.error(Triton.t.area(TritonTypes.Area.OpportunityManagement).exception(e));
Triton.info(Triton.t.area(TritonTypes.Area.Accounts).summary('Rollups recalculated'));
Triton.warning(Triton.t.area(TritonTypes.Area.RestAPI).summary('Callout retried'));
```

{% endcode %}

`Area` and `Type` are meant to grow with your org — but **don't extend the shipped enums to do it.** If you were passing ad-hoc strings like `'InvoiceSync'`, promote them to `public static final String` constants in your own classes and pass those; editing `TritonTypes.cls` gets clobbered on every Triton upgrade. See [Custom Classifications](https://triton.pharos.ai/core-concepts/custom-classifications) for the upgrade-safe pattern, and [Enums](https://triton.pharos.ai/core-concepts/enums) for the built-in value sets.

## LWC changes to check

The method mapping and the [migrate-to-2.0 skill](https://triton.pharos.ai/instrumentation-skills/migrate-to-2.0) cover **Apex only**. Check your LWCs, Flow XML, and `Log_Level__mdt` rules by hand:

* **Removed `CATEGORY` keys.** `CATEGORY.WARNING`, `.DEBUG`, and `.EVENT` are gone and evaluate to `undefined`. The log still lands — re-categorized to `LWC`, with a note in Details — but express severity through the log level instead.
* **Area values.** The `AREA` constants now hold the Apex names (`AREA.ACCOUNTS` is `'Accounts'`, not `'ACCOUNTS'`). Code that compares area strings needs updating; code that only passes the constants to `.area(...)` doesn't. Custom area strings are now kept as sent rather than recorded as `LWC`.
* **`logNow()` and `flush()` no longer reject.** A failed flush keeps its logs for the next one, so a `.catch(...)` on these calls never runs. Keep your own error handling on your own code path.
* **`exception(error)` sets `ERROR`** on any builder, so those logs now open an issue. Chain `.level(...)` after it if a caught error isn't worth one.
* **Profiling records log at `FINE` and below** (failures at `ERROR`). A `Log_Level__mdt` rule at `INFO` or stricter for LWC logs now drops the backend-call, interaction, and mark spans it used to keep at `INFO`.
* **Flow Log actions and `Log_Level__mdt` rules** that name a removed category — see the warnings under [Use real enum values](#use-real-enum-values), and the `Log_Level__mdt` item in the [2.0 upgrade notes](https://triton.pharos.ai/release-notes/2.0#upgrade-notes).

## Migration checklist

1. **Replace `Triton.instance.<method>(...)`** with the static, builder-first equivalents from the mapping table above.
2. **Audit old bare methods** (`error`, `warning`, `debug`, …) that relied on immediate publishing — send them to `Triton.logNow(...)` or ensure a `flush()` covers them.
3. **Confirm `flush()` coverage.** Now that level methods buffer, make sure every code path that logs also flushes — end of a trigger handler, end of a batch `execute`, in `finally` blocks.
4. **Collapse hand-built error logs** to `.exception(e)`, and bulk-DML logs to `.dmlResults(...)`.
5. **Set a template early** with `Triton.setTemplate(...)` and log from `Triton.t`, so shared fields like category and area stop repeating.
6. **Swap ad-hoc strings for stable values** — the built-in `TritonTypes` enums where they fit, and your own `String`-constant classes (see [Custom Classifications](https://triton.pharos.ai/core-concepts/custom-classifications)) for org-specific Type/Area values. Don't edit the shipped enums.
7. **Re-assign the permission sets** (`Triton_Read` / `Triton_Write`) after deploying so the new fields are visible — see the [2.0 release notes](https://triton.pharos.ai/release-notes/2.0).
8. **Check LWCs, Flows, and `Log_Level__mdt` rules by hand** — see [LWC changes to check](#lwc-changes-to-check).

Once you're through the list, delete this page from your mental model: everything else in the docs is written for 2.0, and 2.0 is just *Triton* now. Start with [Core Concepts](https://triton.pharos.ai/core-concepts).


# Upgrading an Org from 1.x

How to install Triton 2.0 in an org that already runs 1.x code: find what depends on Triton, migrate it, and land it together with 2.0.

[Migrating from 1.x](https://triton.pharos.ai/migration) shows how to rewrite your code. This page covers how to get that code and Triton 2.0 into an org that still runs 1.x, in an order Salesforce accepts.

## Why the install fails

Triton 2.0 installs as an unlocked package with the same class names as 1.x, so it replaces the 1.x classes in place. Salesforce then recompiles every Apex class and trigger that uses them. If any of them still calls the 1.x API, the compile fails and Salesforce refuses the whole install. Nothing in the org changes: it stays on 1.x.

The error looks like this:

```
Encountered errors installing the package!
Installation errors:
1) Apex compile failure, Details: Apex class AppLogger: line 4, column 9: Variable does not exist: Triton.instance
2) Apex compile failure, Details: Apex class AppLogger: line 16, column 44: Variable does not exist: Event
3) Apex compile failure, Details: Apex class BillingCallout: line 11, column 48: Variable does not exist: Integration
```

{% hint style="warning" %}
**Salesforce lists only the first six errors.** The classes it names are only the first ones it hit. If you fix those and retry, the next attempt shows the next six. Find every dependent first ([step 1](#step-1-find-everything-that-uses-triton)) and fix them all at once.
{% endhint %}

What each error means:

| Error                                                                   | Cause                                                                                                     | Fix                                                                                                                                                                                                        |
| ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Variable does not exist: Triton.instance`                              | A 1.x singleton call.                                                                                     | Rewrite it with the static API. See the [method mapping](https://triton.pharos.ai/migration#method-mapping).                                                                                               |
| `Variable does not exist: Integration` (or `Event`, `Warning`, `Debug`) | A `TritonTypes.Category` value that 2.0 removed.                                                          | Drop the category and set the level instead. See [Use real enum values](https://triton.pharos.ai/migration#use-real-enum-values).                                                                          |
| `Variable does not exist: <a value you added>`                          | A value your team added to `TritonTypes`. The package ships its own `TritonTypes`, which doesn't have it. | Move an added Area or Type value to your own `String` constants (see [Custom Classifications](https://triton.pharos.ai/core-concepts/custom-classifications)). Switch an added Category to a built-in one. |
| `Method does not exist or incorrect signature: … from the type Triton`  | A half-migrated call such as `Triton.addError(...)`, or a 1.x method that 2.0 removed.                    | Use the 2.0 method from the [method mapping](https://triton.pharos.ai/migration#method-mapping).                                                                                                           |

Flows and LWCs never block the install: in 2.0 the Flow **Log** action and the LWC modules only gained inputs and exports, they didn't lose any. They can log differently afterwards, though. See [LWC changes to check](https://triton.pharos.ai/migration#lwc-changes-to-check).

## Before you start

* **Install Pharos 2.284.5 or later.** Triton 2.0 depends on it, so upgrade Pharos first.
* **Use a sandbox that has your current code.** Rehearse the whole sequence there before production.
* **Have a way to deploy Apex**, such as the Salesforce CLI or your usual pipeline. Step 3 needs a deployment.
* **Check for scheduled Apex.** If any class in the deployment has scheduled jobs waiting, or is used by one, Salesforce refuses the deployment. Either let those jobs finish, or turn on **Allow deployments of components when corresponding Apex jobs are pending or in progress** in **Setup → Deployment Settings**.

## Step 1: Find everything that uses Triton

The Tooling API records which components reference which. Run the queries below in the Developer Console's **Query Editor** with **Use Tooling API** ticked, or with `sf data query --use-tooling-api`.

First, get the ids of the Triton classes and LWC modules:

```sql
SELECT Id, Name FROM ApexClass
WHERE NamespacePrefix = null
AND Name IN ('Triton', 'TritonTypes', 'TritonBuilder', 'TritonHelper', 'TritonFlow', 'TritonLwc')
```

```sql
SELECT Id, DeveloperName FROM LightningComponentBundle
WHERE NamespacePrefix = null
AND DeveloperName IN ('triton', 'tritonBuilder', 'tritonUtils')
```

Then paste those ids into this query to list everything that references them:

```sql
SELECT MetadataComponentType, MetadataComponentName, RefMetadataComponentName
FROM MetadataComponentDependency
WHERE RefMetadataComponentId IN ('01p...', '01p...', '0Rb...')
```

A component appears once for each Triton component it uses, so expect repeats. The query returns at most 2,000 rows. If you get exactly 2,000, the list is cut off: run the query again once for each id.

The result includes Triton's own components. Skip those: `Triton`, `TritonBuilder`, `TritonFlow`, `TritonHelper`, `TritonLwc`, `TritonTypes`, `TritonTest`, `LogLimitsController` and `LogLimitsControllerTest`, and the `triton`, `tritonBuilder`, `tritonUtils` and `logLimits` bundles. Everything else is yours:

* **Apex classes and triggers** must be migrated before 2.0 can install.
* **Flows and LWCs** don't block the install. Check them for behaviour changes after the upgrade.

Two more checks:

* **Values you added to `TritonTypes`.** Open `TritonTypes` in your org. These are the values Triton ships, so anything else in `Area`, `Type` or `Category` was added by your team:
  * `Area`: `OpportunityManagement`, `LeadConversion`, `Community`, `RestAPI`, `Accounts`, `LWC`, `Flow`
  * `Type`: `Backend`, `Frontend`, `DMLResult`, `LongRunningRequest`, `ConcurrentRequestsLimit`, `AccountTrigger`, `BackendCall`, `ComponentLifecycle`, `ComponentRender`, `UserInteraction`, `Performance`
  * `Category`: `Apex`, `Flow`, `LWC`, `Aura`, plus `Warning`, `Event`, `Debug` and `Integration`, which 2.0 removes
* **Your repository.** The query only sees what's deployed to this org. Search your source too, including branches that haven't been deployed yet, for `Triton.instance`, `TritonTypes.Category.` and any values you added to `TritonTypes`.

## Step 2: Migrate the code

* **Rewrite the Apex.** Use the [migrate-to-2.0 skill](https://triton.pharos.ai/instrumentation-skills/migrate-to-2.0), or work by hand from the [method mapping](https://triton.pharos.ai/migration#method-mapping).
* **Replace the values you added to `TritonTypes`.** The package replaces `TritonTypes`, so any reference to an added value stops the install with `Variable does not exist: <value>`.
  * Move added Area and Type values into your own `String` constants class, and pass them as strings, for example `.area(AppAreas.BILLING)`.
  * `category(...)` only takes the built-in values, so switch an added Category to `Apex`, `Flow`, `LWC` or `Aura`.
* **Update the tests** that cover the changed code. The deployment in step 3 runs them.
* **Keep the result in source control.** You can't deploy it on its own yet, because it calls 2.0 methods that the org doesn't have. Step 3 lands it together with 2.0.

## Step 3: Land Triton 2.0 and your migrated code together

Your migrated code needs 2.0 to compile, and 2.0 can't install while your 1.x code is in the org. The way through is one deployment followed by the package install.

1.x was installed as an unmanaged package, so its classes are ordinary metadata that a deployment can overwrite. Deploy the Triton 2.0 source and your migrated code together. Salesforce compiles them as one, so either everything lands or nothing changes. Then install the 2.0 package, which takes over the Triton classes it finds already at 2.0.

1. Get the 2.0 source:

   ```bash
   git clone --branch v2.0 https://github.com/Pharos-AI/triton.git
   ```
2. Copy your migrated classes into `triton/force-app/main/default/classes/`, and your triggers into a new `triton/force-app/main/default/triggers/` folder. Copy each file together with its `-meta.xml` file: the CLI silently skips a class without one, and its tests never run.
3. Do a trial run. It compiles everything and runs the tests, but changes nothing.

   In a sandbox:

   ```bash
   cd triton
   sf project deploy start --dry-run --source-dir force-app --target-org <sandbox> \
     --test-level RunSpecifiedTests \
     --tests TritonTest --tests TritonFlowTest --tests TritonMarkTest \
     --tests TritonSpanContextTest --tests LogLimitsControllerTest \
     --tests <YourTestClass>
   ```

   In production, use `validate` with the same flags, so you can deploy the validated job later:

   ```bash
   sf project deploy validate --source-dir force-app --target-org <production> \
     --test-level RunSpecifiedTests \
     --tests TritonTest --tests TritonFlowTest --tests TritonMarkTest \
     --tests TritonSpanContextTest --tests LogLimitsControllerTest \
     --tests <YourTestClass>
   ```

   With `RunSpecifiedTests`, every class and trigger in the deployment needs 75% coverage from the tests you list, so list the tests for your migrated code too. You can use `RunLocalTests` instead, but then any test in the org that already fails blocks the deployment.
4. Deploy:

   * **In a sandbox,** run the same `sf project deploy start` command without `--dry-run`.
   * **In production,** deploy the validated job:

     ```bash
     sf project deploy quick --job-id <job id from step 3> --target-org <production>
     ```

   From this point the org runs 2.0, and your migrated code with it.
5. Install the 2.0 package from the [sandbox install link](https://resources.pharos.ai/pharos-triton-sandbox) or the [production install link](https://resources.pharos.ai/pharos-triton-prod). Keep the default, **Compile all Apex in the org**.

{% hint style="info" %}
**You can stay on source instead.** If you'd rather keep Triton as source in your own repository, stop after step 4. That's the GitHub option on the [install page](https://triton.pharos.ai/installing-pharos-triton). You can keep your own `TritonTypes` values that way, but each future upgrade becomes a merge rather than an install.
{% endhint %}

{% hint style="danger" %}
**Don't use "Compile only the Apex in the package".** Salesforce's package install screen offers it under **Advanced Options**, and the CLI offers it as `--apex-compile package`. It can get 2.0 past the install's compile check, but your 1.x code still can't run on 2.0. The failure just moves from the install to your users.

In our sandbox test, 2.0 installed and every class and trigger that called 1.x was marked invalid. Until the migrated code was deployed, every Account save failed with `AccountAudit: execution of AfterUpdate caused by: Variable does not exist: Triton.instance`, and calling a 1.x class failed with `Dependent class is invalid and needs recompilation`.
{% endhint %}

## Step 4: After the upgrade

* **Check Installed Packages.** Pharos Triton now shows version 2.0. The old 1.x entry, such as "Pharos Triton v1.421", may still be listed. Its classes now belong to 2.0, so leave the entry in place.
* **Re-assign the permission sets** `Triton_Read` and `Triton_Write`, including on the user that runs the platform-event subscriber. See the [2.0 upgrade notes](https://triton.pharos.ai/release-notes/2.0#upgrade-notes).
* **Send a test log**, and check that it lands on the Logs tab.
* **Review Flows, LWCs and `Log_Level__mdt` rules** for behaviour changes. See [LWC changes to check](https://triton.pharos.ai/migration#lwc-changes-to-check) and the [2.0 upgrade notes](https://triton.pharos.ai/release-notes/2.0#upgrade-notes).

## If the error names a class you don't recognise

* **A class from another package without a namespace.** This means an unmanaged package, or an unlocked package your team builds. Its classes are editable in the org, so migrate them and include them in the step 3 deployment. If it's your own unlocked package, also release a new version with the same changes.
* **A Triton class that 2.0 doesn't have.** It's left over from an early Triton build. If nothing else uses it, delete it from the org with a destructive deployment before step 3.
* **A class from a managed package.** A vendor's managed package can't refer to classes in your org, so it isn't what fails to compile. To check where a class comes from, look at the **Namespace Prefix** column in **Setup → Apex Classes**.

Still stuck? Email <support@pharos.ai> with the full error text and the results of the step 1 query.


# Logging in Apex

The everyday Apex logging patterns — a first log, grouping logs under a transaction, and the try/catch/finally shape you'll reach for again and again.

You've got the [mental model](https://triton.pharos.ai/core-concepts) down: describe a log with a builder, hand it to `Triton`, flush when you're ready. This section is where that model meets real Apex — triggers, services, batches, callouts, REST endpoints. We'll start with the shape you'll use most and build up from there.

## A first Apex log

Here's error logging in Triton 2.0, start to finish:

{% code lineNumbers="true" %}

```apex
public void updateAccounts() {
    Triton.startTransaction();
    try {
        List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
        if (!accounts.isEmpty()) {
            Triton.debug(Triton.t
                .area(TritonTypes.Area.Accounts)
                .summary('Account found, applying update')
                .details('Processing ' + accounts[0].Id));
            accounts[0].Name = 'Logging rules!';
            update accounts;
        }
        Triton.flush();
    } catch (Exception e) {
        Triton.logNow(Triton.t.area(TritonTypes.Area.Accounts).exception(e));
    } finally {
        Triton.stopTransaction();
    }
}
```

{% endcode %}

Everything you need is in that snippet. Let's unpack the three ideas that make it tick.

## Group related logs with a transaction

`Triton.startTransaction()` opens a **correlation scope**: every log you create until `stopTransaction()` shares one transaction id, and Pharos groups them under a single parent log. Instead of a scattered pile of records, you get a tidy tree you can navigate top-down.

{% code lineNumbers="true" %}

```apex
Triton.startTransaction();
Triton.info(Triton.t.area(TritonTypes.Area.Accounts).summary('Job started'));
Triton.info(Triton.t.area(TritonTypes.Area.Accounts).summary('Records processed'));
Triton.flush();
Triton.stopTransaction();
```

{% endcode %}

The first log created becomes the parent; everything after nests beneath it.

{% hint style="info" %}
Need to correlate logs across a boundary — into an async job, a `@future` call, or a callout? Pass `Triton.TRANSACTION_ID` along and call `Triton.resumeTransaction(id)` on the other side. That's the whole basis of end-to-end tracing — see [Transactions & Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache).
{% endhint %}

If you skip `startTransaction()` entirely, Triton still logs everything — the records just won't be grouped under a shared parent. Grouping is a convenience, not a requirement.

## `.exception(e)` — the error one-liner

When you're catching an exception, don't hand-assemble the log. `.exception(e)` sets the type from the exception (falling back to `Backend`), flips the level to `ERROR`, copies the message into the summary, captures the stack trace and details, and flags the log for issue creation — all at once:

{% code lineNumbers="true" %}

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

{% endcode %}

Set the area, pass the exception, done. Issues are created automatically for error logs; routine `debug`/`info` logs don't generate issues. Full builder details live in [The Builder & Templates](https://triton.pharos.ai/core-concepts/builder-and-templates).

## Buffer the routine, publish the critical

Notice the mix above: `Triton.debug(...)` and `Triton.info(...)` **buffer** (cheap, published together on `flush()`), while the exception uses `Triton.logNow(...)` to **publish immediately**. That's the discipline for every Apex context:

* **Buffer** progress and info logs, then `Triton.flush()` at a safe checkpoint.
* **Publish critical failures now** with `Triton.logNow(...)` so you never lose them if the transaction dies.

{% hint style="warning" %}
**Mind the governor limits.** If you blow a limit mid-transaction, there's no guarantee your `finally` block (and its `flush()`/`stopTransaction()`) runs. A buffered log that never flushes is a log you'll wish you had — so publish anything you truly can't lose with `logNow`, and treat `flush()` like DML: do it at boundaries, out of loops. More in [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).
{% endhint %}

## Where to go next

Each page here takes one Apex context and goes deep:

* [Batch Logging](https://triton.pharos.ai/common-apex-usage-patters/batch-logging) — buffering across `execute()` chunks and grouping every iteration under one transaction.
* [Performance Marks](https://triton.pharos.ai/common-apex-usage-patters/performance-marks) — timing a stretch of Apex with `startMark` / `endMark`, and the span tree they build.
* [Integration Logs](https://triton.pharos.ai/common-apex-usage-patters/integration-logs) — capturing request/response payloads on outbound callouts.
* [Apex REST Logging](https://triton.pharos.ai/common-apex-usage-patters/apex-rest-logging) — logging inbound REST requests and threading the transaction id downstream.
* [Full Control with TritonBuilder](https://triton.pharos.ai/common-apex-usage-patters/full-control-with-tritonbuilder) — the complete builder surface, custom attributes, and templates.
* [Log Levels](https://triton.pharos.ai/common-apex-usage-patters/log-levels) — choosing severity and tuning verbosity per environment.


# Batch Logging

Logging in Batch Apex — where to flush, why each execute() is its own transaction, and how to group every iteration under a single parent log.

Batch jobs are the classic logging blind spot. They run in the background, they chew through thousands of records, and when something fails Salesforce often hands you a one-line error with no stack trace. Good logging turns that black box into something you can actually debug.

There's one thing about batch that changes how you log, so let's lead with it.

## Each `execute()` is its own transaction

Triton's buffer and transaction id are **static state that lives for one Apex transaction** (see [The Static Logging API](https://triton.pharos.ai/core-concepts/static-logging-api)). In a batch, every `execute()` chunk — plus `start()` and `finish()` — runs as a *separate* transaction. So the statics reset between chunks.

The practical consequence: **flush at the end of each `execute()`, not in `finish()`.** Anything you buffer in a chunk is gone once that chunk's transaction ends.

## Basic error handling

For a batch that just needs to not swallow failures, this is all you need — no `Database.Stateful`, no bookkeeping:

{% code lineNumbers="true" %}

```apex
public class LeadsBatch implements Database.Batchable<SObject> {
    private final String query;

    public LeadsBatch(String leadQuery) {
        this.query = leadQuery;
    }

    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext bc, List<Lead> leads) {
        for (Lead l : leads) {
            try {
                LeadProcessingResult result = LeadService.getQualificationScore(l);
                if (result.isSuccess) {
                    l.Score__c = result.qualificationScore;
                }
            } catch (Exception e) {
                Triton.error(Triton.t.area(TritonTypes.Area.LeadConversion).exception(e));
            }
        }

        try {
            update leads;
        } catch (Exception e) {
            Triton.error(Triton.t.area(TritonTypes.Area.LeadConversion).exception(e));
        }

        Triton.flush();   // publish this chunk's logs before the transaction ends
    }

    public void finish(Database.BatchableContext bc) {}
}
```

{% endcode %}

`Triton.error(...)` **buffers** the exception at `ERROR` level (and flags it for issue creation); the single `Triton.flush()` at the bottom publishes the whole chunk's worth of logs in one platform event. That's the win over logging inline — a batch with hundreds of iterations still costs one event per chunk instead of one per record.

{% hint style="info" %}
**Why buffer at all?** Every published log consumes a platform-event allocation. Buffering lets a chunk's logs go out together. See [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).
{% endhint %}

## Grouping every iteration under one transaction

The basic version publishes each chunk independently, so the logs aren't tied together. To see the *whole job* as one navigable tree, you need every chunk to share a transaction id — and that means preserving the id across chunks with `Database.Stateful`.

The pattern: take the caller's transaction id in the constructor and stash it in a stateful field (`start` begins a new one only when there's none), then `resumeTransaction(id)` at the top of every entry point so that chunk's logs adopt the shared id.

{% code title="Batch + shared transaction" lineNumbers="true" %}

```apex
public class LeadsBatch implements Database.Batchable<SObject>, Database.Stateful {
    private final String query;
    private String transactionId;   // preserved across chunks by Database.Stateful
    private Integer iteration = 0;

    // Callers pass Triton.TRANSACTION_ID. Only store it: the constructor runs in the
    // caller's transaction, so startTransaction() here would overwrite the caller's id.
    public LeadsBatch(String leadQuery, String callerTransactionId) {
        this.query = leadQuery;
        this.transactionId = callerTransactionId;
    }

    public Database.QueryLocator start(Database.BatchableContext bc) {
        if (String.isBlank(transactionId)) {
            transactionId = Triton.startTransaction();
        } else {
            Triton.resumeTransaction(transactionId);
        }
        setTemplate();
        Triton.info(Triton.t.summary('LeadsBatch starting').details('Query: ' + query));
        Triton.flush();
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext bc, List<Lead> leads) {
        Triton.resumeTransaction(transactionId);
        setTemplate();
        iteration++;
        Triton.fine(Triton.t
            .summary('Executing iteration ' + iteration)
            .details('Processing ' + leads.size() + ' leads'));

        for (Lead l : leads) {
            try {
                LeadProcessingResult result = LeadService.getQualificationScore(l);
                if (result.isSuccess) {
                    l.Score__c = result.qualificationScore;
                } else {
                    Triton.fine(Triton.t
                        .summary('No qualification score for ' + l.Id)
                        .details(String.valueOf(result)));
                }
            } catch (Exception e) {
                Triton.error(Triton.t.exception(e));
            }
        }

        try {
            update leads;
        } catch (Exception e) {
            Triton.error(Triton.t.exception(e));
        }

        Triton.flush();
    }

    public void finish(Database.BatchableContext bc) {
        Triton.resumeTransaction(transactionId);
        setTemplate();
        Triton.info(Triton.t
            .summary('LeadsBatch finished')
            .details('Iterations processed: ' + iteration));
        Triton.flush();
    }

    // Statics reset in every batch method, so each one sets the template again.
    private static void setTemplate() {
        Triton.setTemplate(Triton.makeBuilder()
            .type(TritonTypes.Type.Backend)
            .area(TritonTypes.Area.LeadConversion));
    }
}
```

{% endcode %}

What's doing the work here:

* **`Database.Stateful`** preserves `transactionId` between chunks — the static `Triton.TRANSACTION_ID` doesn't survive on its own.
* **The constructor only stores the id.** It runs in the caller's transaction, so calling `startTransaction()` there would overwrite the caller's `Triton.TRANSACTION_ID` and re-root the caller's later logs under the batch. Enqueue with `Database.executeBatch(new LeadsBatch(query, Triton.TRANSACTION_ID))`; `start` resumes that id (or starts one if there's none), and `resumeTransaction(transactionId)` at the top of `execute` and `finish` re-adopts it so every log lands under the same parent.
* **A template, set at the top of every method.** `Triton.setTemplate(...)` stamps the common `type`/`area` onto every `Triton.t`, so each log only spells out what's unique. The template is a static like the buffer, so one set in the constructor or in `start` is gone by the time `execute` runs; the `setTemplate()` helper re-applies it in each method. Templates get the full treatment in [Full Control with TritonBuilder](https://triton.pharos.ai/common-apex-usage-patters/full-control-with-tritonbuilder).
* **Log levels earn their keep** — routine tracing sits at `fine`, milestones at `info`, failures at `error`. Turn the noise up in a sandbox and down in production without touching this code. See [Log Levels](https://triton.pharos.ai/common-apex-usage-patters/log-levels).

## Timing each chunk

Once the transaction id is threaded through, wrapping a chunk in a [performance mark](https://triton.pharos.ai/common-apex-usage-patters/performance-marks) costs two lines and gives you a timed span per chunk — plus automatic parenting for every log inside it:

{% code lineNumbers="true" %}

```apex
public void execute(Database.BatchableContext bc, List<Lead> leads) {
    Triton.resumeTransaction(transactionId);
    setTemplate();
    Triton.startMark();                    // → 'LeadsBatch.execute'
    try {
        // ... the loop from above ...
    } finally {
        Triton.endMark();
        Triton.flush();
    }
}
```

{% endcode %}

`Triton.startMark()` takes no arguments — the phase *is* the method name, so it derives `LeadsBatch.execute` from the stack trace. There's no batch-specific mark method to learn, and no `clearMarks()` needed at the top of the chunk: a fresh execution context already starts with an empty mark stack, so each chunk becomes its own subtree under the shared transaction.

{% hint style="warning" %}
**Do** flush at the end of every `execute()`. **Don't** buffer across chunks expecting `finish()` to flush them — by then those chunk transactions are over and their buffers are gone.
{% endhint %}

Log in every method that has real logic, not just `execute()`. A one-line `start()` doesn't need it; a `start()` that builds a dynamic query absolutely does.


# Performance Marks

Time any stretch of Apex with startMark / endMark — names derived from the stack trace, automatic nesting, and every log inside the mark parented to it.

Timing a piece of Apex used to mean a stopwatch you wrote yourself: a `Long` before, a subtraction after, and a `.duration(...)` on the log. **Marks** replace that with two calls that also build a span tree — and they don't ask you to type a name.

{% code lineNumbers="true" %}

```apex
public void recalculateForecast() {
    Triton.startMark();
    try {
        // ... the work being measured ...
    } finally {
        Triton.endMark();
    }
}
```

{% endcode %}

That's the whole idiom. The mark is named `ForecastService.recalculateForecast` — derived from the stack trace Triton already captures — and it emits a pair of records: one when it opens, one when it closes carrying the elapsed milliseconds.

This is the Apex counterpart of the LWC [Custom Performance Marks](https://triton.pharos.ai/beyond-apex/profiling/custom-marks). Same concept, same record shape, so a trace that starts in the browser and lands in Apex reads as one tree.

## Naming: derived by default

`startMark()` takes no arguments on purpose. The class and method are already in the stack trace, so making you retype them just creates strings that drift — a renamed method leaves a mark (and any `Log_Level__mdt` rule pointing at it) quietly stale. A derived name cannot drift.

It returns the derived name, which is handy when you need to close out of order:

{% code lineNumbers="true" %}

```apex
String mark = Triton.startMark();     // → 'ForecastService.recalculateForecast'
```

{% endcode %}

When the meaningful name simply *isn't* a method name, supply one:

{% code lineNumbers="true" %}

```apex
Triton.startMark('nightly-reconcile');
Triton.startMark('chunk-3-of-40');
```

{% endcode %}

Use the explicit form for a name the framework can't know, or when you want to measure one method in several labelled segments.

{% hint style="info" %}
**`startMark(String)` is not a performance escape hatch.** Both forms capture the stack once — the records need a trace regardless — so supplying a name skips only a short string parse, not the capture. Pick whichever reads better; they cost effectively the same. If derivation can't produce a name, the mark falls back to `AnonymousMark` plus a counter, so it still nests and is still identifiable.
{% endhint %}

## Nesting

Marks form a stack. `endMark()` closes the innermost open mark, whatever it's called — which is why the `finally` block never has to name anything, and can't silently no-op on a typo:

{% code lineNumbers="true" %}

```apex
Triton.startMark();                      // OrderService.submit
try {
    Triton.startMark('validate');        // nested inside OrderService.submit
    try {
        validate(orders);
    } finally {
        Triton.endMark();                // closes 'validate'
    }

    persist(orders);
} finally {
    Triton.endMark();                    // closes OrderService.submit
}
```

{% endcode %}

For work that legitimately finishes out of order — opened in one method, closed in another — close by name with `endMark(String)`; it closes the newest open mark carrying that name.

`clearMarks()` discards every open mark and resets to the request root. Call it when you want that reset explicitly — `startTransaction()` does **not** clear marks while one is open, and you do **not** need `clearMarks()` at the top of a batch chunk or a queueable (see [Async and batch](#async-and-batch)). It's there for deliberate recovery to a known-good state.

## Trigger handlers

`startTriggerMark()` is the one shorthand, and it exists for one reason: `Trigger.operationType` is the single piece of naming information a stack trace *cannot* carry. `BEFORE_UPDATE` and `AFTER_UPDATE` run the same method from the same frame, so without it a trigger cascade collapses into one indistinguishable span.

{% code lineNumbers="true" %}

```apex
public void run() {
    Triton.startTriggerMark();     // → 'OpportunityHandler.BEFORE_UPDATE'
    try {
        dispatch();
    } finally {
        Triton.endMark();
    }
}
```

{% endcode %}

Zero arguments — the handler class comes from the stack trace, the context from `Trigger.operationType`. Put it in your base handler's dispatch method and every handler in the org is instrumented without touching one of them. Called outside trigger context, there's no operation to append, so it produces the same `<Class>.<method>` name `startMark()` would — it is exactly `startMark()` at that point, safe to leave in a method that's also reachable outside a trigger.

{% hint style="info" %}
**There is no boundary method and no batch method.** A request boundary is `startMark()` at the top of the endpoint; a batch phase is `startMark()` at the top of `execute()`. Depth is a fact the framework already knows, not something you declare — the outermost mark parents to the transaction automatically.
{% endhint %}

## What gets logged

A mark emits **two** records — one on open, one on close — so a transaction that dies mid-mark still shows the work having started.

| Field               | Opening record                | Completion record                           |
| ------------------- | ----------------------------- | ------------------------------------------- |
| Summary             | `Performance started: <mark>` | `Performance: <mark>`                       |
| Details             | *(unset)*                     | `Duration: <n>ms`                           |
| Type                | `Performance`                 | `Performance`                               |
| Action              | `<mark>`                      | `<mark>`                                    |
| Duration            | *(unset)*                     | the elapsed milliseconds                    |
| `Span_Id__c`        | the mark's span               | the **same** span                           |
| `Parent_Span_Id__c` | the enclosing span            | the **same** enclosing span                 |
| Stack trace         | the `startMark()` call site   | the **same** trace, not `endMark()`'s frame |
| Level               | `FINE`                        | `FINE`                                      |
| Category / Area     | inherited from `Triton.t`     | inherited from `Triton.t`                   |

Both halves are built from your template, so an entry point that sets an Area gets it on its marks for free. Both carry the *opening* call site's stack trace: they describe the same span, and where the two genuinely differ — an out-of-order close from another method — the opening frame is the more useful one, because that's where the measured work began.

The opening record omits governor-limit info (it has no duration and no deltas worth having); the completion record keeps it.

### Levels are a rule, not an argument

Marks always log at `FINE`. There is deliberately **no** `level` parameter, because a level baked into a call site overrides the `Log_Level__mdt` rule an admin is supposed to control without a deploy — the opposite of how the rest of Triton works. To turn marks on for one class, write the rule:

| Field     | Value             |
| --------- | ----------------- |
| Component | `ForecastService` |
| Level     | `FINE`            |

Every other field left blank is a wildcard, so that record targets `ForecastService` logs in any category, type, or area. See [Log Levels (resolution rules)](https://triton.pharos.ai/core-concepts/log-levels) for how competing rules resolve.

## Logs inside a mark become children of it

This is the part that turns marks from a stopwatch into a trace. While a mark is open, every ordinary log you emit is parented to it:

{% code lineNumbers="true" %}

```apex
Triton.startMark();                                     // OrderService.submit
try {
    Triton.info(Triton.t.summary('Validating 42 orders'));   // ← child of the mark
    Triton.fine(Triton.t.summary('Pricing applied'));        // ← child of the mark
} finally {
    Triton.endMark();
}
```

{% endcode %}

You write nothing extra. The outermost mark parents to the transaction span; a nested mark parents to the mark enclosing it; ordinary logs become leaves under whichever mark is innermost. Full model in [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing).

{% hint style="info" %}
**An id you set yourself always wins.** If you call `.spanId(...)` or `.parentSpanId(...)` on a builder, marks never overwrite it. That's what keeps an LWC → Apex trace intact: the ids the browser forwarded stay exactly as they arrived.
{% endhint %}

### Filtered-out marks stay transparent

If a `Log_Level__mdt` rule rejects a mark's opening record, the mark doesn't leave a hole behind it. Its children re-parent to the nearest surviving ancestor instead of pointing at a span that was never published — so dialling a class down thins the tree rather than orphaning it.

## Marks never flush

`startMark()` and `endMark()` use the buffered path, exactly like `Triton.log()`. No mark method ever publishes a platform event, so a mark opened and closed inside a loop adds two buffered records per iteration and nothing else. Your existing flush points stay yours.

{% hint style="warning" %}
**Buffered means buffered.** Paired records make a crash *after* a flush visible — the opening record is already out. They don't rescue a buffer that never flushed. If you can't afford to lose a boundary event, publish it with `Triton.logNow(...)` as you would today.
{% endhint %}

## Async and batch

Apex statics don't survive a batch chunk, a `Queueable`, or a `@future`, and the mark stack is a static. That's fine — each async unit starts clean and becomes its own subtree under the shared transaction, which is what you want anyway.

The whole batch idiom is two calls you already have:

{% code lineNumbers="true" %}

```apex
public void execute(Database.BatchableContext bc, List<Lead> leads) {
    Triton.resumeTransaction(transactionId);   // if you carry one (Database.Stateful)
    Triton.startMark();                        // → 'LeadsBatch.execute'
    try {
        // ... process the chunk ...
    } finally {
        Triton.endMark();
        Triton.flush();
    }
}
```

{% endcode %}

The phase *is* the method name, so `startMark()` derives `LeadsBatch.execute` for free — there's no batch-specific method to learn. `clearMarks()` isn't needed here: a fresh execution context already starts with an empty stack. Carrying the transaction id across chunks is still `Database.Stateful` plus an instance field, unchanged — see [Batch Logging](https://triton.pharos.ai/common-apex-usage-patters/batch-logging).

## Opting in

Marks change nothing until you add one. A transaction with no open mark produces byte-identical span fields to before.

{% hint style="warning" %}
**Once a mark is open, span fields change shape.** `Span_Id__c` on an ordinary log inside a mark becomes a fresh UUID instead of the request id. If a query, report, or dashboard treats `Span_Id__c == requestId` as "this log belongs to request X", move it to **`pharos__Request_Id_External__c`**, which is where that fact actually lives. `Parent_Span_Id__c` also goes from always-null to populated, and log volume grows by two records per mark.

A mark that log levels filtered out is still an *open* mark, so it still reshapes the logs around it — suppression is transparent for parenting, not for data shape.
{% endhint %}

## Do / Don't

{% hint style="success" %}
**Do**

* **Prefer `Triton.startMark()` with no arguments.** The derived name can't drift out of sync with a rename.
* **Close in a `finally`.** An exception mid-mark shouldn't leave the stack open.
* **Use `startTriggerMark()` in your base trigger handler** — one call instruments every handler context in the org.
* **Reach for `startMark(String)` when the name isn't a method name**, not as a performance optimisation.
* **Control verbosity with `Log_Level__mdt`**, the same way you do for every other log.
  {% endhint %}

{% hint style="danger" %}
**Don't**

* **Don't hand-time work you've marked.** The completion record already carries the duration; a manual `System.now().getTime()` alongside it is duplication. Manual timing is still fine for a one-off you don't want a span for.
* **Don't flush inside a mark just to "get it out".** Marks are buffered by design; flush at your boundaries.
* **Don't call `clearMarks()` at the top of a batch chunk or queueable.** The stack is already empty there.
* **Don't assume `Span_Id__c` is the request id** once marks are in play.
  {% endhint %}

## Related reading

* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) — how the mark stack becomes a trace tree.
* [Custom Performance Marks](https://triton.pharos.ai/beyond-apex/profiling/custom-marks) — the LWC equivalent.
* [Log Levels in Apex](https://triton.pharos.ai/common-apex-usage-patters/log-levels) — dialling mark verbosity per environment.
* [`Triton` methods reference](https://triton.pharos.ai/methods-reference/apex-methods-reference/triton#performance-marks) — signatures for all six methods.


# Integration Logs

Capture the full request/response payload on an outbound callout so a failed integration is something you can inspect — and replay — instead of guess at.

When Salesforce talks to an external service, the happy path is boring: you send a request, you get a `200`, life goes on. The interesting case is the `500` at 2am that nobody sees until a customer complains. By then the request is long gone — unless you logged it.

An "integration log" isn't a special kind of log — it's an **ordinary Apex log with the HTTP request and response attached**. You build it exactly like every other Apex log in this section (`Triton.t`, or `Triton.makeBuilder()`, which defaults to the Apex category) and add one method — `.integrationPayload(request, response)` — to capture both sides of the exchange on the record. That's the whole trick: attaching a payload is a property of the log, not a separate category or entity.

## The payload viewer

Once a log carries an HTTP exchange, Triton renders it in a Postman-style viewer right on the log record:

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-e7c3d1670418b06a3434fcd6a41a2268442bd4ea%2FScreenshot_2024-06-13_at_10_47_57_AM.png?alt=media" alt=""><figcaption><p>Pharos Triton Integration Log View</p></figcaption></figure>

From here you can inspect the endpoint, headers, parameters, and bodies of both the request and the response — and even **replay** the request (with optional edits) from your org, not just your browser. For troubleshooting a flaky endpoint, that's gold.

## The callout, before logging

Here's a typical outbound callout: gather some data, build a JSON body, fire it off.

{% code lineNumbers="true" %}

```apex
public static void pushLoanApplication(Id loanApplicationId) {
    Loan_Application__c la = [
        SELECT Id, Primary_Contact__r.FirstName, Primary_Contact__r.LastName,
               Primary_Contact__r.Email, Primary_Contact__r.Social__c
        FROM Loan_Application__c
        WHERE Id = :loanApplicationId
        LIMIT 1
    ];

    Map<String, String> requestMap = new Map<String, String>{
        'firstName' => la.Primary_Contact__r.FirstName,
        'lastName'  => la.Primary_Contact__r.LastName,
        'email'     => la.Primary_Contact__r.Email,
        'ssn'       => la.Primary_Contact__r.Social__c
    };

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('callout:LoanService/applications');
    request.setMethod('POST');
    request.setHeader('Content-Type', 'application/json;charset=UTF-8');
    request.setBody(JSON.serializePretty(requestMap));

    HttpResponse response = http.send(request);
}
```

{% endcode %}

The glaring problem: if the response comes back non-`200`, we never know. Let's fix that.

## Attaching the payload

Nothing about the log changes except one method call. It's still a plain Apex log — the default category — and `.integrationPayload(request, response)` serializes the full HTTP exchange onto the record so Pharos can render the payload viewer:

{% code lineNumbers="true" %}

```apex
public static void pushLoanApplication(Id loanApplicationId) {
    Loan_Application__c la = [
        SELECT Id, Primary_Contact__r.FirstName, Primary_Contact__r.LastName,
               Primary_Contact__r.Email, Primary_Contact__r.Social__c
        FROM Loan_Application__c
        WHERE Id = :loanApplicationId
        LIMIT 1
    ];

    Map<String, String> requestMap = new Map<String, String>{
        'firstName' => la.Primary_Contact__r.FirstName,
        'lastName'  => la.Primary_Contact__r.LastName,
        'email'     => la.Primary_Contact__r.Email,
        'ssn'       => la.Primary_Contact__r.Social__c
    };

    try {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:LoanService/applications');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody(JSON.serializePretty(requestMap));

        HttpResponse response = http.send(request);

        if (response.getStatusCode() != 200) {
            // A plain Apex error log — with the HTTP exchange attached
            Triton.logNow(Triton.t
                .area(TritonTypes.Area.RestAPI)
                .summary('Unable to push loan application to loan service')
                .details(String.format(
                    'Received a {0} status code when pushing application {1}',
                    new String[]{ String.valueOf(response.getStatusCode()), la.Id }))
                .relatedObject(la.Id)
                .integrationPayload(request, response)
                .error());
        } else {
            // Success — a routine INFO log, payload attached for the record
            Triton.log(Triton.t
                .area(TritonTypes.Area.RestAPI)
                .summary('Loan application pushed to loan service')
                .relatedObject(la.Id)
                .integrationPayload(request, response)
                .info());
        }
    } catch (Exception e) {
        Triton.logNow(Triton.t
            .area(TritonTypes.Area.RestAPI)
            .relatedObject(la.Id)
            .exception(e));
    } finally {
        Triton.flush();
    }
}
```

{% endcode %}

A few things worth calling out:

* **`.integrationPayload(request, response)`** is the only thing that makes this an "integration" log — it captures both sides of the exchange for the viewer. Everything else is a normal Apex log. There's an overload for inbound REST too (`.integrationPayload(RestRequest, RestResponse)`); see [Apex REST Logging](https://triton.pharos.ai/common-apex-usage-patters/apex-rest-logging).
* **No special category.** The log uses the default **Apex** category (`Triton.t` / `Triton.makeBuilder()`). You don't reach for a distinct "Integration" category — attaching a payload is a property of an ordinary log.
* **`.error()`** on the bad-response path sets the level to `ERROR` and flags the log for issue creation, so a bad response doesn't just get recorded — it gets someone's attention. On the happy path, the same log goes out at `.info()` with the payload still attached, so you have a record of successful exchanges too.
* **`.exception(e)`** handles the *other* failure mode — a thrown `CalloutException`, a timeout — with the same one-liner you use everywhere else.
* **`.relatedObject(la.Id)`** links the log to the loan application, so it shows up in the Related Objects view on that record.
* **`Triton.logNow(...)`** publishes the failure immediately — an integration failure is exactly the kind of thing you never want stuck in a buffer that might not flush — while the routine success buffers and goes out on the closing `Triton.flush()`.

Run this against a failing endpoint and you get a fully inspectable record:

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-9af523798a2532c08046b73376cbb0046b3655a8%2FScreenshot%202024-06-13%20at%204.08.19%20PM.png?alt=media" alt=""><figcaption><p>Resulting Integration Log</p></figcaption></figure>

…with the loan application linked automatically:

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-26a1f335676f758cefdf5e7a53b23f7f0faffb16%2FScreenshot%202024-06-13%20at%204.08.31%20PM.png?alt=media" alt=""><figcaption><p>Related Object Automatically Associated</p></figcaption></figure>

{% hint style="info" %}
**Type is yours to define.** The example leans on `Area`, but a log with a payload attached is a great place for a domain-specific `Type` like `LoanServiceSync`. Keep it as a `String` constant in your own class rather than adding it to the shipped enum — see [Custom Classifications](https://triton.pharos.ai/core-concepts/custom-classifications).
{% endhint %}


# Apex REST Logging

Logging an inbound REST request at your custom Apex endpoint — capture the payload, open a transaction, and thread its id through everything downstream.

[Integration Logs](https://triton.pharos.ai/common-apex-usage-patters/integration-logs) covered the *outbound* case — Salesforce calling someone else. This is the mirror image: an external system calling a custom REST endpoint you expose with `@RestResource`. Same payload-capture idea, pointed the other way.

Your goal at the front door is threefold: **log the incoming request** (with its payload), **open a transaction** so everything the request triggers is grouped together, and **pass that transaction id downstream** so async work correlates back to the original call.

{% code lineNumbers="true" %}

```apex
@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {

    @HttpPost
    global static String doPost(String name, String phone, String website) {
        String transactionId = Triton.startTransaction();
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;

        // A plain Apex log for the inbound request — with the payload attached
        Triton.log(Triton.t
            .area(TritonTypes.Area.Accounts)
            .summary('Inbound account creation request')
            .details(String.format('POST received with name={0}, phone={1}, website={2}',
                new String[]{ name, phone, website }))
            .integrationPayload(req, res));
        Triton.flush();

        try {
            Account account = new Account(Name = name, Phone = phone, Website = website);

            // Hand the transaction id to downstream async work so its logs correlate
            AccountProcessing.doAsyncProcessing(account, transactionId);

            insert account;
            return account.Id;
        } catch (Exception e) {
            Triton.logNow(Triton.t
                .area(TritonTypes.Area.Accounts)
                .exception(e));
        }
        return null;
    }
}
```

{% endcode %}

What each move buys you:

* **`Triton.startTransaction()`** returns a fresh id and opens the correlation scope. The first log becomes the parent; everything after nests under it.
* **`.integrationPayload(req, res)`** captures the inbound `RestRequest`/`RestResponse` for the payload viewer — the same tool you get on outbound integration logs.
* **Passing `transactionId` to `AccountProcessing.doAsyncProcessing(...)`** lets that code call `Triton.resumeTransaction(transactionId)` on the other side, so its logs join this same tree even though they run in a separate Salesforce transaction.
* **`.exception(e)`** on the catch publishes the failure immediately with `logNow`, flagged for issue creation.

## The resulting log structure

Say the `insert` throws a `DmlException`, and `doAsyncProcessing()` does some logging of its own. You get one clean tree:

* **Parent** — Apex log for the inbound request, with the payload attached
  * **Child** — Apex error log from the try/catch
  * **Children** — any logs emitted inside `AccountProcessing.doAsyncProcessing()`

{% hint style="info" %}
The order of the async children depends on how quickly Salesforce schedules `AccountProcessing` — Queueable vs. Batch, and whether it runs right away. Grouping by transaction id keeps them together regardless of timing.
{% endhint %}

Threading a transaction id from an entry point through downstream Apex, async jobs, and even LWC or Flow is the backbone of end-to-end tracing. For the full picture — including span-based tracing and platform-cache-backed correlation — see [Transactions & Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache) and [End-to-End Logging](https://triton.pharos.ai/end-to-end).


# Full Control with TritonBuilder

The complete TritonBuilder surface — every method worth knowing, the deep-dive helpers, custom attributes, and the template pattern in full.

`TritonBuilder` is the fluent object that describes a single log. You've seen it throughout this section as `Triton.t` and `Triton.makeBuilder()`; this page is the full tour — everything the builder can do, and how to keep your logging code DRY with templates.

If you just want the mental model, [The Builder & Templates](https://triton.pharos.ai/core-concepts/builder-and-templates) covers it. This page is the reference you come back to when you need a specific capability.

## Two ways to start a builder

{% code lineNumbers="true" %}

```apex
Triton.makeBuilder()   // a fresh builder, pre-set to the Apex category
Triton.t               // a clone of your template, stamped with the current transaction id
```

{% endcode %}

Reach for `Triton.t` almost always — it carries your [template](#templates) fields for free. Use `Triton.makeBuilder()` when you want a clean slate or you're building a template itself.

## Turning a builder into a log

The builder only *describes* a log. `Triton` decides what happens to it:

| Call                                                                            | Effect                                                                |
| ------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `Triton.log(builder)`                                                           | **Buffer** at the builder's level. Nothing published until `flush()`. |
| `Triton.error(builder)` (also `warning`/`info`/`debug`/`fine`/`finer`/`finest`) | Set that level, then buffer.                                          |
| `Triton.logNow(builder)`                                                        | Buffer **and** flush this one immediately.                            |

{% code lineNumbers="true" %}

```apex
// Buffered — cheap, batched, published on flush()
Triton.log(Triton.makeBuilder()
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.Community)
    .summary('Sample log entry')
    .details('A detailed description of what happened')
    .level(TritonTypes.Level.INFO));

// Immediate — published on the spot
Triton.logNow(Triton.t.summary('Critical failure').exception(e));
```

{% endcode %}

{% hint style="info" %}
`Triton.log(...)` **buffers**; `Triton.logNow(...)` **publishes now**. Reach for `logNow` only when a log must survive even if the transaction dies. Everything else buffers and flushes at a boundary — see [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).
{% endhint %}

## The method surface

The builder is broad, but it clusters into a handful of groups.

| Group                     | Methods                                                                                                                                 |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| **Classification**        | `.category(...)` · `.type(...)` · `.area(...)` · `.level(...)`                                                                          |
| **Level shorthands**      | `.error()` · `.warning()` · `.info()` · `.debug()` · `.fine()` · `.finer()` · `.finest()` (each also has a `(String summary)` overload) |
| **Content**               | `.summary(String)` · `.details(String)` · `.stackTrace(String)` · `.operation(String)` · `.action(String)`                              |
| **Errors & DML**          | `.exception(Exception)` · `.dmlResults(List<Object>)`                                                                                   |
| **Records**               | `.relatedObject(Id/String)` · `.relatedObjects(...)` · `.userId(Id)`                                                                    |
| **Integrations**          | `.integrationPayload(HttpRequest, HttpResponse)` · `.integrationPayload(RestRequest, RestResponse)`                                     |
| **Limits & context**      | `.limitInfo()` · `.limitInfoLite()` · `.withFullLimitInfo()` · `.withoutLimitInfo()` · `.apexExecutionContext()`                        |
| **Tracing**               | `.spanId(String)` · `.parentSpanId(String)` · `.traceable(Boolean)` · `.tracePoint()` · `.transactionId(String)`                        |
| **Issues & escape hatch** | `.createIssue()` · `.attribute(String, Object)`                                                                                         |

Every method returns the builder, so it all chains. A few deserve a closer look.

### `.exception(e)` — the error one-liner

Don't hand-set type, summary, stack trace, and details for an error. `.exception(e)` 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 %}

### `.dmlResults()` — partial-success DML

Running partial-success DML? Hand the results straight to the builder. It tallies successes and failures, collects the failed ids, formats the error messages, and only produces a log **if something actually failed**. On all-success — or a null or empty list — nothing is emitted, whichever method you pass it to, so no `if` is needed:

{% code lineNumbers="true" %}

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

{% endcode %}

It understands `SaveResult`, `DeleteResult`, `UpsertResult`, `UndeleteResult`, and `MergeResult`, sets the type to `DMLResult`, writes a failure-count summary (set your own summary after it if you want one), relates the failed records, and logs at `ERROR` with an issue. Pass it to `Triton.warning(...)` instead to record expected partial failures without an issue.

### `.integrationPayload()` — HTTP and REST exchanges

Serialize a full request/response pair onto the record for the payload viewer. There's an overload each for outbound callouts and inbound REST:

{% code lineNumbers="true" %}

```apex
builder.integrationPayload(httpRequest, httpResponse);   // outbound callout
builder.integrationPayload(restRequest, restResponse);   // inbound REST endpoint
```

{% endcode %}

See [Integration Logs](https://triton.pharos.ai/common-apex-usage-patters/integration-logs) and [Apex REST Logging](https://triton.pharos.ai/common-apex-usage-patters/apex-rest-logging) for the full patterns.

### `.relatedObject()` — link records

Associate one or many records so the log surfaces in the Related Objects view:

{% code lineNumbers="true" %}

```apex
builder.relatedObject('001xx000003DGb2AAG');
builder.relatedObjects(new Set<Id>{ acc.Id, opp.Id });
```

{% endcode %}

Invalid ids are quietly skipped, so you can pass raw strings without pre-validating.

### Limit info and execution context

By default, buffered logs capture essential governor usage (SOQL, DML, CPU, heap, callouts). You can tune this:

{% code lineNumbers="true" %}

```apex
builder.withFullLimitInfo();   // also capture extended limits (SOSL, future, queueable, ...)
builder.withoutLimitInfo();    // skip limit capture entirely (e.g. high-volume trace logs)
```

{% endcode %}

`.apexExecutionContext()` appends the current context (trigger operation and sObject, or the async context type) to the details — Triton adds it automatically for Apex-category logs.

### Custom attributes — the escape hatch

Any field on `pharos__Log__c` — standard or custom — is reachable with `.attribute()`:

{% code lineNumbers="true" %}

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

{% endcode %}

It works, but sprinkling API names through your code is fragile. **Prefer a typed method.** `TritonBuilder` declares its own field names as constants at the top of the class and adds a method per field — follow the same approach for your org:

{% code lineNumbers="true" %}

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

public TritonBuilder orderNumber(String value) {
    this.attribute(ORDER_NUMBER, value);
    return this;
}
```

{% endcode %}

Now the call site is clean, autocompletes, and has a single place to change the field name:

{% code lineNumbers="true" %}

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

{% endcode %}

### Tracing helpers

`.spanId()`, `.parentSpanId()`, `.traceable(Boolean)`, and `.tracePoint()` support fine-grained, span-based tracing across a distributed process. They're covered end-to-end in [Spans & Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing).

## Templates

Look across any of the examples above and the same fields recur — category, area, sometimes a related object. A **template** is a builder you configure once and reuse.

Set it where your unit of work begins:

{% code lineNumbers="true" %}

```apex
Triton.setTemplate(Triton.makeBuilder()
    .category(TritonTypes.Category.Apex)
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.Community));
```

{% endcode %}

Then start every log from it with `Triton.t`:

{% code lineNumbers="true" %}

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

{% endcode %}

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

### Templates in practice

Here's the [batch job from the previous page](https://triton.pharos.ai/common-apex-usage-patters/batch-logging#grouping-every-iteration-under-one-transaction) leaning on a template — notice how each log only spells out what's unique:

{% code lineNumbers="true" %}

```apex
public class LeadsBatch implements Database.Batchable<SObject>, Database.Stateful {
    private final String query;
    private String transactionId;
    private Integer iteration = 0;

    // Callers pass Triton.TRANSACTION_ID. Only store it: the constructor runs in the
    // caller's transaction, so startTransaction() here would overwrite the caller's id.
    public LeadsBatch(String leadQuery, String callerTransactionId) {
        this.query = leadQuery;
        this.transactionId = callerTransactionId;
    }

    public Database.QueryLocator start(Database.BatchableContext bc) {
        if (String.isBlank(transactionId)) {
            transactionId = Triton.startTransaction();
        } else {
            Triton.resumeTransaction(transactionId);
        }
        setTemplate();
        Triton.info(Triton.t.summary('LeadsBatch starting').details('Query: ' + query));
        Triton.flush();
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext bc, List<Lead> leads) {
        Triton.resumeTransaction(transactionId);
        setTemplate();
        iteration++;
        Triton.fine(Triton.t.summary('Executing iteration ' + iteration));
        // ... process leads ...
        Triton.flush();
    }

    public void finish(Database.BatchableContext bc) {
        Triton.resumeTransaction(transactionId);
        setTemplate();
        Triton.info(Triton.t.summary('LeadsBatch finished').details('Iterations: ' + iteration));
        Triton.flush();
    }

    // Statics reset in every batch method, so each one sets the template again.
    private static void setTemplate() {
        Triton.setTemplate(Triton.makeBuilder()
            .type(TritonTypes.Type.Backend)
            .area(TritonTypes.Area.LeadConversion));
    }
}
```

{% endcode %}

Note where the template is set: at the top of `start`, `execute`, and `finish`. A template is a static, like the buffer, and in a batch each of those methods is its own transaction — so a template set in the constructor is gone before `start` runs.

Why bother? **Consistency** (every log shares the same taxonomy), **less code** (specify only what changes), **maintainability** (change the shared fields in one place), and **readability** (the noise is gone). A little up-front effort for a lot less fragility later.

{% hint style="info" %}
**Why does `Triton.t` clone?** If it returned the same builder each time, one log's summary would leak into the next. Cloning makes the template a stamp, not a shared mutable object. A couple of per-log fields (the full summary text, captured execution context) are intentionally *not* cloned.
{% endhint %}


# Log Levels

Choosing the right log level in Apex — the severity scale, the shorthand methods, and tuning verbosity per environment with metadata instead of code changes.

A level answers one question: how important is this log? In Apex you use levels for two things — telling a human how urgent a record is, and letting Triton decide *at runtime* whether the log is even worth saving. That second part means you can run chatty in a sandbox and quiet in production **without changing a line of code**.

The mechanics of runtime filtering (the `Log_Level__mdt` metadata, specificity resolution, the defaults) live in [Core Concepts → Log Levels](https://triton.pharos.ai/core-concepts/log-levels). This page is about *using* levels well in Apex.

## The scale

Seven levels, least to most verbose:

| Level                       | Reach for it when…                                                                         |
| --------------------------- | ------------------------------------------------------------------------------------------ |
| `ERROR`                     | Something failed and a human should look — exceptions, failed callouts, broken invariants. |
| `WARNING`                   | Something recoverable or suspicious — retries, partial DML failures, approaching a limit.  |
| `INFO`                      | A notable business event — "order placed", "sync completed". Your production signal.       |
| `DEBUG`                     | Developer detail useful while diagnosing.                                                  |
| `FINE` / `FINER` / `FINEST` | Increasingly chatty tracing — payload dumps, loop-level detail, everything.                |

## Setting the level

Two equivalent ways — an explicit `.level(...)`, or the shorthand method on `Triton`:

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.t.summary('Order placed').level(TritonTypes.Level.INFO));
Triton.info(Triton.t.summary('Order placed'));   // identical
```

{% endcode %}

The shorthands — `Triton.error/warning/info/debug/fine/finer/finest(builder)` — set the level and buffer in one call. (`Triton.error(...)` also flags the log for issue creation.) There's no `errorNow`; for immediate publishing at a level, set it on the builder and call `logNow`:

{% code lineNumbers="true" %}

```apex
Triton.logNow(Triton.t.summary('Payment capture failed').error().exception(e));
```

{% endcode %}

## Worked examples

Same code, different levels — pick the one that matches the *audience* for the message.

{% code lineNumbers="true" %}

```apex
// ERROR — something broke
try {
    processAccount(account);
} catch (Exception e) {
    Triton.error(Triton.t.area(TritonTypes.Area.Accounts).exception(e));
}

// WARNING — approaching a governor limit
if (System.Limits.getQueries() > System.Limits.getLimitQueries() * 0.8) {
    Triton.warning(Triton.t
        .area(TritonTypes.Area.Accounts)
        .summary('Approaching SOQL query limit')
        .details('Used ' + System.Limits.getQueries() + ' of ' + System.Limits.getLimitQueries()));
}

// INFO — a business milestone
Triton.info(Triton.t
    .area(TritonTypes.Area.Accounts)
    .summary('Account created')
    .details('Account ' + newAccount.Id + ', owner ' + newAccount.OwnerId));

// DEBUG — diagnostic detail
Triton.debug(Triton.t
    .area(TritonTypes.Area.Accounts)
    .summary('Validating account')
    .details('Industry: ' + account.Industry));

// FINE — loop-level tracing
Triton.fine(Triton.t
    .area(TritonTypes.Area.Accounts)
    .summary('Processing record ' + (i + 1) + ' of ' + accounts.size())
    .details('Account ' + account.Id));
```

{% endcode %}

## Tune verbosity per environment

The point of levels is that **the same code behaves differently by environment** — because a `Log_Level__mdt` record, not your Apex, decides what persists. Write the log once at the right level:

{% code lineNumbers="true" %}

```apex
Triton.debug(Triton.t
    .area(TritonTypes.Area.Accounts)
    .summary('Account validation started')
    .details('Validating: ' + accountData));
```

{% endcode %}

With a metadata rule of `Category: Apex → INFO` in production, that `DEBUG` log is dropped; bump the same rule to `DEBUG` (or `FINEST`) in a sandbox and it flows. No redeploy of Apex.

## Choosing levels well

* **Reserve `ERROR` for things a human should act on.** If everything is an error, nothing is.
* **Make `INFO` your production signal.** Ask "would I want to see this in prod?" — if yes, it's `INFO` or higher.
* **Push volume down the scale.** Loop bodies, payload dumps, and step-by-step traces belong at `FINE` and below, where filtering switches them off cheaply.
* **Don't gate logs with `if` statements.** Resist `if (debugMode) Triton.debug(...)`. Log at the right level and let the metadata decide — that's the whole point.

{% hint style="warning" %}
**Watch expensive details.** Filtering happens *after* the builder is constructed, so heavy `JSON.serialize(...)` or string concatenation in `.details(...)` still runs even when the log is dropped. For very hot paths, guard the expensive construction, not the log call.
{% endhint %}

For deeper guidance on designing a level strategy across a codebase, see [Log Levels: When to Use What](https://triton.pharos.ai/triton-best-practices/log-levels-and-usage).


# Logging in LWC

Logging from Lightning Web Components — the JavaScript Triton API, transaction management, correlating LWC with Apex, and profiling component performance.

Not everything happens in Apex. A modern Salesforce org is a mix of technologies, and the front end — Lightning Web Components — is where users actually live. When a screen misbehaves, "it worked on my machine" isn't a debugging strategy. Triton gives LWC the same structured logging you get in Apex, plus a few things only the browser can offer: runtime info, render timing, and user-interaction telemetry.

The JavaScript API mirrors the Apex one closely — a fluent builder, buffered vs. immediate logging, transactions, templates — so if you know one, you mostly know the other. Grab the logger like any other LWC module:

{% code lineNumbers="true" %}

```javascript
import Triton, { TYPE, AREA, LEVEL } from 'c/triton';
```

{% endcode %}

{% code lineNumbers="true" %}

```javascript
this.triton = new Triton().bindToComponent('MyComponent');

this.triton.log(
    this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
        .summary('Component ready')
);
```

{% endcode %}

## What's in this section

| Page                                                                                       | What you'll learn                                                                       |
| ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
| [LWC](https://triton.pharos.ai/beyond-apex/lwc)                                            | The JS logger, component binding, the builder, buffered vs. immediate, templates.       |
| [LWC Transaction Management](https://triton.pharos.ai/beyond-apex/lwctransaction)          | How transactions are auto-managed, the auto-flush monitor, and manual control.          |
| [LWC and Apex](https://triton.pharos.ai/beyond-apex/lwc-and-apex)                          | Correlating a click on the front end with the Apex it triggers.                         |
| [Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache) | Sharing a transaction id across contexts without passing it by hand.                    |
| [Profiling](https://triton.pharos.ai/beyond-apex/profiling)                                | Capturing performance telemetry — backend calls, interactions, lifecycle, custom marks. |

{% hint style="info" %}
Work through the pages in order if you're new to LWC logging — each builds on the last. Once your front end and back end both log to Triton, the natural next step is stitching an entire user journey (LWC → Apex → Flow) into one trace: see [End-to-End Logging](https://triton.pharos.ai/end-to-end).
{% endhint %}

Logging from Flow is its own thing — declarative, no JavaScript — and lives in [Logging in Flow](https://triton.pharos.ai/flows).


# LWC

Logging from Lightning Web Components — binding the logger, the fluent builder, buffered vs. immediate logging, and component-scoped templates.

LWC interfaces have a way of growing. What starts as one tidy component becomes a tree of them, wired to Apex, juggling async calls and user input — and when something breaks in production, you need more than a browser console you can't see. This is where Triton earns its place on the front end.

{% hint style="info" %}
Every user who loads an instrumented LWC needs the `Triton End User` permission set — the `triton` module's Apex call is a hard entry point, unlike calls made from inside Apex. See [Configure Permissions](https://triton.pharos.ai/installing-pharos-triton#configure-permissions) for the full model.
{% endhint %}

## Bind the logger first

Every LWC logger starts with `bindToComponent()`. It creates a component-scoped context that gives you three things for free:

1. **Component identification** — every log is tagged with the component that produced it.
2. **Scoped templates** — component-specific templates are isolated so two components never clobber each other's.
3. **Accurate stack traces** — error traces and component details resolve to the right place.

{% code lineNumbers="true" %}

```javascript
this.triton = new Triton().bindToComponent('myComponentName');
```

{% endcode %}

Pass a stable, unique identifier — the component name is almost always the right call.

{% hint style="warning" %}
**Always bind.** Without `bindToComponent()` you lose component context, templates won't scope correctly, and the [profiling APIs](https://triton.pharos.ai/beyond-apex/profiling) refuse to run. It's one line; make it a habit.
{% endhint %}

## Where to initialize

`Triton` uses a shared instance under the hood, so `new Triton()` is cheap to call — but *when* you bind matters if your component uses `@wire`.

### Without `@wire`

Bind in `connectedCallback` — it's one of the first hooks to fire, and with no wires there's no earlier data or error you could miss:

{% code title="logDemo.js" lineNumbers="true" %}

```javascript
import Triton, { TYPE, AREA, LEVEL } from 'c/triton';

export default class LogDemo extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('logDemo');
    }

    async handleClick(event) {
        someAction({}).then(() => {
            // Buffer the routine success
            this.triton.log(
                this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                    .summary('Action completed successfully')
                    .details(JSON.stringify({ someKey: 'value' }))
            );
        }).catch(async (error) => {
            // Publish the failure immediately
            await this.triton.logNow(
                this.triton.exception(error)
                    .summary('Action failed')
            );
        });
    }
}
```

{% endcode %}

### With `@wire`

Wires initialize and start fetching *before* `connectedCallback` runs. To catch an early wire error, bind in the constructor:

{% code lineNumbers="true" %}

```javascript
export default class LogDemoWithWire extends LightningElement {
    triton;

    constructor() {
        super();
        this.triton = new Triton().bindToComponent('logDemoWithWire');
    }

    @wire(getRecord, { /* ... */ })
    wiredRecord({ error, data }) {
        if (error) {
            this.triton.logNow(
                this.triton.exception(error).summary('Failed to load record')
            );
        }
    }
}
```

{% endcode %}

{% hint style="info" %}
**Just bind in the constructor and forget about it.** It works whether or not you use `@wire`, it's future-proof if you add a wire later, and the shared-instance pattern means there's no cost to initializing early. The only downside — binding on a component that never mounts — is rare and harmless.
{% endhint %}

## The builder

Each level method (`error`, `warning`, `info`, `debug`) takes a `TYPE` and `AREA` and returns a chainable builder. `exception(error)` builds an `ERROR` log straight from a caught error — which, as in Apex, also opens a Pharos issue:

{% code lineNumbers="true" %}

```javascript
this.triton.log(
    this.triton.error(TYPE.FRONTEND, AREA.ACCOUNTS)
        .summary('Failed to load account details')
        .details(JSON.stringify({ accountId: '123' }))
        .relatedObjects(['001xx000003DGb2AAG'])
);
```

{% endcode %}

Triton captures rich context automatically — component details, browser/device runtime info, the transaction id, a timestamp, and the user — so you only chain the fields specific to *this* log. Everything's optional; add as much or as little as you need:

{% code lineNumbers="true" %}

```javascript
const startTime = performance.now();
// ... perform operation ...
this.triton.log(
    this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
        .summary('Processing account update')
        .duration(performance.now() - startTime)
        .relatedObjects([accountId])
);
```

{% endcode %}

{% hint style="info" %}
**Areas.** The `AREA` constants carry the Apex area names — `AREA.ACCOUNTS` is `'Accounts'` — so LWC logs group with the Apex and Flow logs of the same feature. `.area(...)` also accepts any string: pass the area your Apex controller uses (`.area('OrderEntry')`) and it's kept as sent. Leave the area off and the log lands under `LWC`.
{% endhint %}

## Buffered vs. immediate

Same distinction as Apex:

* **`log(builder)`** buffers. Logs accumulate and go to the server together — on the next flush, on auto-flush, or when you call `flush()`. Efficient for routine, high-volume logging.
* **`logNow(builder)`** sends immediately and returns a Promise. Use it for critical errors you can't risk losing. Only the log you pass goes out now; the rest of the buffer stays put. The Promise never rejects: if the server can't take the log, it stays buffered for the next flush, so `await this.triton.logNow(...)` inside a `catch` can't derail your own error handling.

{% code lineNumbers="true" %}

```javascript
// Buffered — routine
this.triton.log(
    this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS).summary('Debug info')
);

// Immediate — critical
await this.triton.logNow(
    this.triton.error(TYPE.FRONTEND, AREA.ACCOUNTS).summary('Critical error')
);
```

{% endcode %}

A realistic handler mixes both — buffer the routine, publish the failure:

{% code lineNumbers="true" %}

```javascript
async handleAccountOperations() {
    this.triton.log(
        this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
            .summary('Starting account update sequence')
    );

    try {
        await this.updateAccountDetails();
        this.triton.log(
            this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('Account details updated')
                .details(JSON.stringify({ accountId: this.accountId }))
        );
    } catch (error) {
        await this.triton.logNow(
            this.triton.exception(error)
                .summary('Failed to update account')
                .details(JSON.stringify({ accountId: this.accountId }))
        );
        this.showErrorMessage('Failed to update account. Support has been notified.');
    }
}
```

{% endcode %}

Buffering keeps routine logs cheap; immediate logging guarantees the important failure is saved before the component can crash or navigate away. That balance matters most in mission-critical flows — payments, healthcare, anything where a lost log is a real problem.

## Component-scoped templates

If a component logs the same `type`/`area`/`level` over and over, set a template once and start each log from it. Because you bound the logger, the template is scoped to *this* component:

{% code lineNumbers="true" %}

```javascript
connectedCallback() {
    this.triton = new Triton().bindToComponent('AccountManager');

    this.triton.setTemplate(
        this.triton.makeBuilder()
            .type(TYPE.FRONTEND)
            .area(AREA.ACCOUNTS)
            .level(LEVEL.INFO)
            .relatedObjects([this.recordId])
    );
}
```

{% endcode %}

Then `fromTemplate()` clones it, and you fill in only what changes:

{% code lineNumbers="true" %}

```javascript
async handleAccountUpdate() {
    try {
        await updateAccount(this.accountId);
        this.triton.log(
            this.triton.fromTemplate()
                .summary('Account updated successfully')
                .details(JSON.stringify({ accountId: this.accountId }))
        );
    } catch (error) {
        this.triton.logNow(
            this.triton.fromTemplate()
                .exception(error)
                .summary('Failed to update account')
        );
    }
}
```

{% endcode %}

{% hint style="info" %}
Templates are scoped by the component binding: each component gets its own, they never interfere, and `setTemplate` / `fromTemplate` only work after `bindToComponent()`.
{% endhint %}

## A pattern worth knowing: dual-wire logging

Wire the same Apex method twice — once to a property (for programmatic `refreshApex`) and once to a function (for processing and logging):

{% code lineNumbers="true" %}

```javascript
export default class OrderManager extends LightningElement {
    @wire(getOrderItems, { orderId: '$recordId' })
    wiredOrderItems;

    @wire(getOrderItems, { orderId: '$recordId' })
    logOrderItemsChange({ error, data }) {
        if (data) {
            this.setOrderItems(data);
            this.triton.log(
                this.triton.fromTemplate()
                    .level(LEVEL.DEBUG)
                    .summary('Order items retrieved')
                    .relatedObjects([this.recordId])
                    .details(`Retrieved ${data.length} order items`)
            );
        } else if (error) {
            this.triton.log(
                this.triton.fromTemplate()
                    .level(LEVEL.ERROR)
                    .summary('Error retrieving order items')
                    .relatedObjects([this.recordId])
                    .exception(error)
            );
        }
    }
}
```

{% endcode %}

You get a refreshable reference *and* automatic logging of every load — automatic or manual. LWC shares a single subscription for identical wire configs, so this doesn't double your network traffic.

## Where to go next

You've got the front end logging. Next, correlate those logs with the Apex they call — and eventually stitch a whole journey together:

* [LWC Transaction Management](https://triton.pharos.ai/beyond-apex/lwctransaction) — how logs get grouped and auto-flushed.
* [LWC and Apex](https://triton.pharos.ai/beyond-apex/lwc-and-apex) — one transaction spanning a click and its server call.
* [End-to-End Logging](https://triton.pharos.ai/end-to-end) — the full LWC → Apex → Flow trace.


# LWC Transaction Management

How Triton manages transactions in LWC — automatic ids, session-storage continuity across components, the auto-flush monitor, and when to take manual control.

A transaction id is what ties a scatter of log records into one story. In LWC, Triton manages that id for you automatically — creating it, persisting it across component lifecycles, and flushing logs on a timer so nothing gets stranded. Most of the time you never think about it. This page is for the times you do.

## It's automatic by default

The moment you create a logger, transaction handling kicks in. Behind the scenes Triton:

1. Looks for an existing transaction id in session storage.
2. Reuses it if found; generates a fresh UUID v4 if not.
3. Starts an auto-flush monitor that watches the buffer.

{% code lineNumbers="true" %}

```javascript
connectedCallback() {
    this.triton = new Triton().bindToComponent('LogDemo');
    // transaction id is already set and shared
}
```

{% endcode %}

Because the id lives in **session storage**, it survives component teardown and is shared across every Triton logger on the page. Two sibling components logging in the same session automatically land under the same transaction — no wiring required.

{% code lineNumbers="true" %}

```javascript
async handleOperation() {
    try {
        this.triton.log(
            this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS).summary('Operation started')
        );
        await this.performOperation();
        this.triton.log(
            this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS).summary('Operation completed')
        );
    } catch (error) {
        this.triton.log(
            this.triton.exception(error).summary('Operation failed')
        );
    }
}
```

{% endcode %}

Every `log()` above gets the current transaction id stamped on it, so all three correlate in the database — ready to view as one grouped trace.

## The auto-flush monitor

Buffered logs don't wait forever. Triton runs a background monitor that:

* **checks the buffer every 5 seconds**, and
* **flushes the buffer once the newest log in it is 10 seconds old** — that is, after 10 seconds with nothing new logged.

This is what keeps logs from being lost when a user wanders off mid-session or a component is destroyed before you flush by hand. You still get the batching benefit — logs published together — without the risk of a buffer that never drains.

If a flush fails — the user went offline, say — its logs go back into the buffer and the next flush retries them. After the third failure in a row they're dropped. After a failed flush, the buffer is trimmed to the newest 500 logs (`Triton.MAX_BUFFERED_LOGS`). `flush()` and `logNow()` never reject, so logging can't break your component's own error handling.

It's a safety net, not a substitute for flushing at real boundaries. For anything critical, still use `logNow()` (see [LWC](https://triton.pharos.ai/beyond-apex/lwc#buffered-vs-immediate)), and flush explicitly when a component tears down:

{% code lineNumbers="true" %}

```javascript
disconnectedCallback() {
    if (this.triton) {
        this.triton.flush();
    }
}
```

{% endcode %}

## Manual transaction control

When you want explicit boundaries, three methods give it to you:

{% code lineNumbers="true" %}

```javascript
this.triton.startTransaction();               // new id, fresh span context, cleared marks
this.triton.resumeTransaction(existingId);    // adopt an existing id
this.triton.stopTransaction();                // flush pending logs, then clear the id
```

{% endcode %}

* **`startTransaction()`** generates a new UUID v4, stores it in session storage, resets the span context, clears any active performance marks, and (re)starts the auto-flush monitor. Everything logged afterward uses the new id.
* **`resumeTransaction(id)`** adopts an id you already have — the key to correlating with an existing transaction (e.g. one that started in Apex). See [LWC and Apex](https://triton.pharos.ai/beyond-apex/lwc-and-apex).
* **`stopTransaction()`** stops the monitor, starts a final flush of anything pending, and removes the id from session storage. It returns a promise that settles once that final flush has been attempted — `await` it if you need the logs sent before moving on. It never rejects.

### When manual control pays off

The classic case is a **multi-step flow** you want captured as one unit:

{% code lineNumbers="true" %}

```javascript
// A wizard: one transaction across all steps
async handleWizardNavigation() {
    if (this.isFirstStep) {
        this.triton.startTransaction();
    }
    try {
        this.triton.log(
            this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary(`Wizard step ${this.currentStep} completed`)
        );
        await this.processCurrentStep();
        if (this.isLastStep) {
            this.triton.stopTransaction();   // close it out, flush everything
        }
    } catch (error) {
        this.triton.stopTransaction();
        throw error;
    }
}
```

{% endcode %}

The same shape works for a batch-processing UI where you want every record's logs grouped under one parent — `startTransaction()` at the top, `stopTransaction()` in a `finally`.

## Do / Don't

* **Do** let Triton manage transactions automatically for ordinary work — single API calls, form submits, standard CRUD. The defaults are right for the common case.
* **Do** reach for manual control when you have a genuine multi-step boundary, and always pair `startTransaction()` with a `stopTransaction()` (a `finally` is your friend).
* **Do** flush in `disconnectedCallback` so a teardown never strands buffered logs.
* **Don't** call `startTransaction()` on every interaction — you'll fragment what should be one grouped trace into many.

{% hint style="info" %}
Manual transactions are also how you hand off a trace to another layer. Grab the current id from `this.triton.transactionId`, pass it to Apex, and `resumeTransaction(id)` there. That's the foundation of [End-to-End Logging](https://triton.pharos.ai/end-to-end).
{% endhint %}


# LWC and Apex

Correlate a front-end action with the Apex it triggers — pass the transaction id from LWC into your controller so UI logs and server logs land in one trace.

Most interesting bugs live in the seam between the browser and the server. A user clicks a button, the component calls Apex, the Apex does a DML that blows up — and you're left correlating a front-end error with a back-end one by squinting at timestamps. Triton removes the squinting: pass one transaction id across the boundary and both sides log into the same tree.

The setup: a button click starts the flow in LWC, then hands off to Apex. Our job is to link the two.

## The LWC controller

Start a log on the front end, then call Apex — passing `this.triton.transactionId` so the server can adopt it.

{% code title="logDemo.js" lineNumbers="true" %}

```javascript
import apexActionThatGeneratesDMLError from '@salesforce/apex/LogDemoController.apexActionThatGeneratesDMLError';
import Triton, { AREA, TYPE } from 'c/triton';

export default class LogDemo extends LightningElement {
    triton;
    startTime;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('logDemo');
    }

    handleClick() {
        this.startTime = performance.now();
        this.executeScenario();
    }

    async executeScenario() {
        // Log the start of the flow on the front end
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('LWC action - DML Error')
                .details('Execution start')
                .duration(performance.now() - this.startTime)
        );

        try {
            // Hand the transaction id to Apex so its logs correlate
            await apexActionThatGeneratesDMLError({
                transactionId: this.triton.transactionId
            });
        } catch (error) {
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}
```

{% endcode %}

The key line is `transactionId: this.triton.transactionId`. That's the current front-end transaction id, going along for the ride.

## The Apex controller

On the server, `Triton.resumeTransaction(transactionId)` adopts the id, so every Apex log joins the same tree the LWC logs started:

{% code title="LogDemoController.cls" lineNumbers="true" %}

```apex
public with sharing class LogDemoController {

    @AuraEnabled
    public static void apexActionThatGeneratesDMLError(String transactionId) {
        // Adopt the transaction id passed from LWC
        Triton.resumeTransaction(transactionId);

        Triton.debug(Triton.t
            .type(TritonTypes.Type.Backend)
            .area(TritonTypes.Area.Community)
            .summary('LWC controller (apex) - DML Error')
            .details('Apex execution start'));

        try {
            ContentVersion cv = new ContentVersion();
            cv.ContentLocation = 'Apex Error';
            cv.Title = 'Apex Error';
            cv.PathOnClient = 'ApexError.pdf';
            insert cv;   // throws a DMLException
        } catch (Exception e) {
            Triton.error(Triton.t.area(TritonTypes.Area.Community).exception(e));
        }

        Triton.flush();
    }
}
```

{% endcode %}

`Triton.resumeTransaction(...)` is the whole trick — without it, the Apex logs would form their own separate trace. The buffered `debug` and `error` logs publish together on the closing `Triton.flush()`.

## The result

One click, four logs, one transaction:

* **Parent** — LWC **Debug** log from `executeScenario()`
  1. Child Apex **Debug** log from `apexActionThatGeneratesDMLError()`
  2. Child Apex **Error** log from the try/catch
  3. Child LWC **Error** log from the front-end error handler

{% hint style="info" %}
Everything is stitched together by the shared transaction id. You started it on the front end and resumed it on the back end — that's all correlation requires.
{% endhint %}

## With `@wire`

The same stitching idea applies when Apex is called from a wire: put `transactionId` in the wire config so the server can `resumeTransaction`. Wires need a reactive property for the id — set it in the constructor when you bind Triton (wires can fire before `connectedCallback`).

### LWC side

{% code title="orderBuilder.js" lineNumbers="true" %}

```javascript
import { LightningElement, api, wire } from 'lwc';
import getOrderItems from '@salesforce/apex/OrderBuilderController.getOrderItems';
import Triton, { AREA, TYPE, LEVEL } from 'c/triton';

export default class OrderBuilder extends LightningElement {
    @api recordId;

    /** Wired Apex result so it may be programmatically refreshed. */
    @wire(getOrderItems, { orderId: '$recordId', transactionId: '$_transactionId' })
    wiredOrderItems;

    triton; // Triton instance for logging
    _transactionId; // Direct property for wire reactivity

    constructor() {
        super();
        this.triton = new Triton().bindToComponent('orderBuilder');
        this._transactionId = this.triton.transactionId;

        this.triton.setTemplate(
            this.triton.makeBuilder()
                .level(LEVEL.INFO)
                .type(TYPE.FRONTEND)
                .area(AREA.COMMUNITY)
        );
    }
}
```

{% endcode %}

The reactive `_transactionId` is what makes the wire re-evaluate with the current front-end transaction id. Without it in the config, Apex has nothing to resume.

### Apex side

{% code title="OrderBuilderController.cls" lineNumbers="true" %}

```apex
@AuraEnabled(Cacheable=true)
public static Order_Item__c[] getOrderItems(Id orderId, String transactionId) {
    Triton.resumeTransaction(transactionId);

    Triton.setTemplate(template);

    Triton.info(Triton.t
            .summary('Fetching order items')
            .details('Order ID: ' + orderId)
            .relatedObjects(new List<String>{orderId})
    );

    try {
        Order_Item__c[] orderItems = [
            SELECT
                Id,
                Qty_S__c,
                Qty_M__c,
                Qty_L__c,
                Price__c,
                Product__r.Name,
                Product__r.MSRP__c,
                Product__r.Picture_URL__c
            FROM Order_Item__c
            WHERE Order__c = :orderId
            WITH USER_MODE
        ];

        Triton.debug(Triton.t
                .summary('Order items fetched successfully')
                .details('Total order items retrieved: ' + orderItems.size())
                .relatedObjects(new List<String>{orderId})
        );

        Triton.flush();
        return orderItems;

    } catch (Exception e) {
        Triton.logNow(Triton.t
                .summary('Error fetching order items')
                .details('Order ID: ' + orderId)
                .exception(e)
                .relatedObjects(new List<String>{orderId})
        );
        throw e;
    }
}
```

{% endcode %}

Same trick as the imperative example: `Triton.resumeTransaction(transactionId)` adopts the LWC id before any logging. (`Cacheable=true` is normal for `@wire`; if you were tempted to stitch via Platform Cache instead, see the caveat on [Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache#wont-work-with-cacheable-apex--wire).)

Passing the id through a method parameter is the explicit, predictable approach — great when the call graph is simple. When it isn't (multiple components, async hops, no clean place to thread a parameter), Platform Cache can carry the id for you. That's next: [Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache). For the complete cross-technology journey, see [End-to-End Logging](https://triton.pharos.ai/end-to-end).


# Platform Cache for Transactions

Use Salesforce Platform Cache to share a transaction id across contexts — correlate LWC and Apex logs without passing the id by hand.

[LWC and Apex](https://triton.pharos.ai/beyond-apex/lwc-and-apex) threaded the transaction id through a method parameter. That's clean when you control the call and there's an obvious place to put it. But sometimes there isn't — multiple components, async hops, a chain of calls where plumbing an id through every signature is a pain. For those cases, Platform Cache can hold the id for you, and both sides just ask for it.

{% hint style="info" %}
**Prerequisite:** you need a default cache partition with an Org cache allocation. See [Platform Cache Setup](https://triton.pharos.ai/installing-pharos-triton#platform-cache-setup) in the install guide.
{% endhint %}

## The idea

Instead of passing the id, you call `withCache()`. Triton stores the transaction id in Platform Cache keyed by the running user, and any other context that calls `withCache()` for the same user picks it up. No parameter required.

## LWC side

Notice there's **no `transactionId` argument** — the component just flags that caching is on:

{% code title="logDemo.js" lineNumbers="true" %}

```javascript
export default class LogDemo extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('LogDemo');
    }

    async executeScenario() {
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('Cache Demo - Start')
                .details('Starting execution with cache enabled')
        );

        try {
            // No transactionId passed — the cache carries it
            await apexActionThatGeneratesDMLError({ cacheEnabled: true });
        } catch (error) {
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}
```

{% endcode %}

## Apex side

One call — `Triton.withCache()` — and the Apex logs adopt the cached transaction id:

{% code title="LogDemoController.cls" lineNumbers="true" %}

```apex
public with sharing class LogDemoController {
    @AuraEnabled
    public static void apexActionThatGeneratesDMLError(Boolean cacheEnabled) {
        if (cacheEnabled) {
            Triton.withCache();   // resume the cached transaction id (or start one)
        }

        Triton.debug(Triton.t
            .type(TritonTypes.Type.Backend)
            .area(TritonTypes.Area.Community)
            .summary('Cache Demo - Apex')
            .details('Executing with cached transaction id'));

        try {
            ContentVersion cv = new ContentVersion();
            cv.ContentLocation = 'Apex Error';
            cv.Title = 'Apex Error';
            cv.PathOnClient = 'ApexError.pdf';
            insert cv;
        } catch (Exception e) {
            Triton.error(Triton.t.area(TritonTypes.Area.Community).exception(e));
        }

        Triton.flush();
    }
}
```

{% endcode %}

## How `withCache()` works

When you call it, Triton runs this logic:

1. Check whether Platform Cache is available and configured.
2. **If it is:** build a cache key from the running user's id, look for an existing transaction id, **resume** it if found, or **start** a new one and cache it if not.
3. **If it isn't:** fall back to starting a normal transaction and carry on.

That automatic fallback is the nice part — you never have to special-case an org without cache configured. `withCache()` just does the right thing.

## When to use it — and when not to

### Good fits

* Multiple components or services that should share one trace.
* Correlating across asynchronous boundaries where parameter passing is awkward.
* Reducing signature clutter in a deep call chain.

### Caveats

{% hint style="warning" %}
The cache key is the **running user's id**, so every operation that user performs within the cache window shares one transaction id. That can group things you didn't mean to group:

1. A batch job running as the same user who triggered an LWC action.
2. Multiple browser tabs doing similar work at once.
3. Cache that isn't cleared between logically separate operations.

When separation matters, prefer explicit parameter passing — or call `Triton.startTransaction()` to force a fresh id.
{% endhint %}

### Won't work with cacheable Apex / `@wire`

{% hint style="warning" %}
`@AuraEnabled(Cacheable=true)` methods are read-only for Platform Cache — cache writes are inaccessible. That means `Triton.withCache()` cannot store or resume a transaction id inside a cacheable method.

For `@wire` (and any other cacheable Apex), preserve transaction stitching by passing `transactionId` explicitly and calling `Triton.resumeTransaction(transactionId)` on the server. See the worked example in [With `@wire`](https://triton.pharos.ai/beyond-apex/lwc-and-apex#with-wire) on the previous page.
{% endhint %}

### Rules of thumb

* Use **parameter passing** for simple, synchronous, single-hop calls (the [previous page](https://triton.pharos.ai/beyond-apex/lwc-and-apex)).
* Use **parameter passing** for cacheable Apex / `@wire` — do not rely on `withCache()` there.
* Use **cache** for genuinely complex, multi-context scenarios where signatures are awkward **and** the Apex is not cacheable.
* Reach for `startTransaction()` when you need a clean boundary between operations.

Platform cache is a sharp tool — powerful for the hard cases, overkill for the easy ones. Pick based on how tangled your call graph actually is. For the bigger picture on stitching traces across every layer, see [Transactions & Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache) and [End-to-End Logging](https://triton.pharos.ai/end-to-end).


# Profiling

Capture performance telemetry from LWC components — backend calls, user interactions, render cycles, and custom marks — with Triton's built-in profiling APIs.

LWC components don't just need logging — they need to be *fast*. Slow page loads, sluggish form submissions, and runaway re-renders all hurt the user experience, and they're notoriously hard to diagnose after the fact. Triton ships with a set of profiling helpers that piggy-back on the existing logger so you can capture performance data with the same fluent API you already use for logs.

Every profiling event ends up as a regular `pharos__Log__c` record, with a `duration` value and a typed `TYPE.*` marker, which means everything you've already built around Triton (dashboards, notifications, taxonomies, issue tracking) lights up automatically once you start instrumenting components.

## What Triton Captures

Triton's profiling layer covers four common LWC performance scenarios:

| Scenario                            | Method                                                 | Log type                   |
| ----------------------------------- | ------------------------------------------------------ | -------------------------- |
| Apex / backend wire calls           | `timeBackendCall(name, fn)`                            | `TYPE.BACKEND_CALL`        |
| User-driven interactions            | `timeUserInteraction(name, fn)`                        | `TYPE.USER_INTERACTION`    |
| Component lifecycle (mount/unmount) | `trackComponentLifecycle('connected'\|'disconnected')` | `TYPE.COMPONENT_LIFECYCLE` |
| Render cycles                       | `trackComponentRender()`                               | `TYPE.COMPONENT_RENDER`    |
| Arbitrary timed regions             | `startPerformanceMark` / `endPerformanceMark`          | `TYPE.PERFORMANCE`         |

The expanded `TYPE` enum in `c/triton` looks like this:

{% code lineNumbers="true" %}

```javascript
export const TYPE = {
    BACKEND: 'Backend',
    FRONTEND: 'Frontend',
    BACKEND_CALL: 'BackendCall',
    COMPONENT_LIFECYCLE: 'ComponentLifecycle',
    COMPONENT_RENDER: 'ComponentRender',
    USER_INTERACTION: 'UserInteraction',
    PERFORMANCE: 'Performance'
};
```

{% endcode %}

## Levels and area

Profiling records carry fixed levels, matching Apex performance marks, so one `Log_Level__mdt` threshold decides how much profiling you keep:

| Record                                                | Level                    |
| ----------------------------------------------------- | ------------------------ |
| Backend call or user interaction — started, completed | `FINE`                   |
| Backend call or user interaction — failed             | `ERROR` (opens an issue) |
| Performance mark — started, completed                 | `FINE`                   |
| Component lifecycle                                   | `FINER`                  |
| Component render                                      | `FINEST`                 |

Each record starts from the component's template, so it inherits the template's Area and other shared fields. Set the template before you profile; without one, records land under the `LWC` area.

{% hint style="warning" %}
**A rule at `INFO` or stricter drops profiling.** With an LWC `Log_Level__mdt` rule at `INFO`, only failures survive. Run the LWC threshold — or a rule scoped to a profiling `Type` — at `FINE` to keep backend-call, interaction, and mark timings in production, `FINER` to add lifecycle tracking, and `FINEST` (mid-investigation only) to add render tracking.
{% endhint %}

## Component Binding is Required

The profiling APIs only work after you've called `bindToComponent()`. The same binding you use for [regular LWC logging](https://triton.pharos.ai/beyond-apex/lwc) doubles as the anchor for performance tracking — Triton generates a unique instance ID under the hood (`componentKey = name-uuid`) so two instances of the same component on a page get isolated marks, render counts, and lifecycle events.

If you call a profiling method without binding first, Triton logs a console warning and returns without doing anything — it deliberately won't throw and break your component.

{% hint style="info" %}
You only need to bind once per component. The instance you get back from `bindToComponent()` is a Proxy around the singleton `Triton` instance, so calling `new Triton().bindToComponent('Name')` in two components on the same page is perfectly safe.
{% endhint %}

## Minimum Viable Setup

Here's a complete example that wires Triton up for performance tracking. Add this skeleton to any component you want to profile and you'll get lifecycle and render telemetry for free, plus the option to instrument specific operations.

{% code title="myComponent.js" lineNumbers="true" %}

```javascript
import Triton, { AREA } from 'c/triton';

export default class MyComponent extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('MyComponent');
        this.triton.setTemplate(
            this.triton.makeBuilder().area(AREA.ACCOUNTS)   // profiling records inherit this Area
        );
        this.triton.trackComponentLifecycle('connected');
    }

    renderedCallback() {
        this.triton.trackComponentRender();
    }

    disconnectedCallback() {
        this.triton.trackComponentLifecycle('disconnected');
    }
}
```

{% endcode %}

That's it. Every mount, unmount, and render now produces a structured log entry tied to your component, the current transaction, and the bound user — at `FINER` and `FINEST`, so your log-level rules decide whether they're kept. From here you can layer in the more specialized profiling helpers covered in the rest of this section.

## Locker Service Compatibility

All profiling internals use a safe `getCurrentTime()` helper that prefers `performance.now()` and falls back to `Date.now()` when the Performance API is restricted (which happens under Locker Service in some component contexts). You don't need to think about it — timing will work everywhere your LWC runs.

## Where to Go Next

Pick the area that matches what you're trying to measure:

* [Backend Calls](https://triton.pharos.ai/beyond-apex/profiling/backend-calls) — wrap your Apex calls in `timeBackendCall(...)` and pick from four error-handling scenarios.
* [User Interactions](https://triton.pharos.ai/beyond-apex/profiling/user-interactions) — time anything kicked off by a user (form submits, multi-step flows) with `timeUserInteraction(...)`.
* [Component Lifecycle](https://triton.pharos.ai/beyond-apex/profiling/component-lifecycle) — track mounts, unmounts, render counts, and understand per-instance isolation.
* [Custom Performance Marks](https://triton.pharos.ai/beyond-apex/profiling/custom-marks) — drop browser-style marks anywhere in your code with `startPerformanceMark` / `endPerformanceMark`.


# Backend Calls

Wrap Apex calls in timeBackendCall(...) to capture durations, start/complete events, and exceptions — with four flexible error-handling scenarios.

Most LWC performance problems live in the round trip to the server. `timeBackendCall(methodName, apexCall)` is the workhorse for measuring that round trip. It logs the start of the call, waits for the promise, logs completion (with duration), and — if something goes wrong — logs the failure with the same duration baseline plus the exception.

Under the hood it returns a `PerformanceCallBuilder`, which lets you tune *how* errors are handled before the call is actually executed.

## Basic Usage

{% code title="productSearch.js" lineNumbers="true" %}

```javascript
import Triton from 'c/triton';
import searchProducts from '@salesforce/apex/ProductController.searchProducts';

export default class ProductSearch extends LightningElement {
    triton;
    products = [];

    connectedCallback() {
        this.triton = new Triton().bindToComponent('ProductSearch');
        this.triton.trackComponentLifecycle('connected');
    }

    async handleSearch() {
        const searchTerm = this.searchInput.value;

        try {
            const results = await this.triton.timeBackendCall(
                'searchProducts',
                () => searchProducts({ searchTerm })
            ).execute();

            this.products = results;
        } catch (error) {
            this.showErrorMessage('Search failed. Please try again.');
        }
    }
}
```

{% endcode %}

Three things to notice:

1. The Apex call is wrapped in an arrow function so Triton controls when it runs.
2. `methodName` ("searchProducts") is the label that ends up on the resulting log records. Use the real Apex method name so logs are easy to find.
3. `.execute()` is the trigger — until you call it, no logging or Apex invocation happens.

## The Four Error-Handling Scenarios

`PerformanceCallBuilder` exposes two modifiers that combine into four scenarios. The defaults (built-in logging + rethrow) match what 90% of code wants.

| Modifiers                                                | Error handler           | Rethrow | When to use                                                                            |
| -------------------------------------------------------- | ----------------------- | ------- | -------------------------------------------------------------------------------------- |
| `.execute()`                                             | Built-in (logs failure) | Yes     | Default. The standard try/catch pattern.                                               |
| `.withoutRethrow().execute()`                            | Built-in (logs failure) | No      | You want failures logged but don't need an exception in the calling code.              |
| `.withCustomErrorHandler(fn).execute()`                  | Custom only             | Yes     | You want full control over the side effects but the calling code still needs to react. |
| `.withCustomErrorHandler(fn).withoutRethrow().execute()` | Custom only             | No      | Fire-and-forget calls with custom telemetry/UX.                                        |

### 1. Default: log + rethrow

{% code lineNumbers="true" %}

```javascript
try {
    const result = await this.triton.timeBackendCall(
        'processPayment',
        () => processPayment({ amount: 100, cardToken: 'token123' })
    ).execute();

    this.showPaymentSuccess(result);
} catch (error) {
    this.handlePaymentError(error);
}
```

{% endcode %}

The failure is automatically logged with the method name, duration, and exception, then re-thrown so your `catch` block runs as usual.

### 2. Built-in logging, no rethrow

{% code lineNumbers="true" %}

```javascript
const result = await this.triton.timeBackendCall(
    'processPayment',
    () => processPayment({ amount: 100, cardToken: 'token123' })
)
.withoutRethrow()
.execute();

if (result) {
    this.showPaymentSuccess(result);
} else {
    this.showPaymentWarning('Payment could not be processed');
}
```

{% endcode %}

Useful when you want the call to fail silently from a control-flow perspective but still capture the failure log. A `null` return is your signal that something went wrong.

### 3. Custom handler + rethrow

{% code lineNumbers="true" %}

```javascript
try {
    const result = await this.triton.timeBackendCall(
        'processPayment',
        () => processPayment({ amount: 100, cardToken: 'token123' })
    )
    .withCustomErrorHandler((error, context) => {
        this.sendToErrorTracking({
            method: context.methodName,
            duration: context.duration,
            error: error.message,
            component: 'PaymentProcessor'
        });
    })
    .execute();

    this.showPaymentSuccess(result);
} catch (error) {
    this.handlePaymentError(error);
}
```

{% endcode %}

Custom handlers receive `(error, context)` where `context` is `{ methodName, duration }` for backend calls. Use this when you want to enrich the failure with extra side effects (external monitoring, fancy toasts) but still need an exception to bubble.

{% hint style="warning" %}
A custom handler **replaces** the built-in failure log — it doesn't run alongside it. If you still want a Triton log on failure, call `this.triton.log(...)` from inside your handler.
{% endhint %}

### 4. Custom handler, no rethrow

{% code lineNumbers="true" %}

```javascript
const result = await this.triton.timeBackendCall(
    'processPayment',
    () => processPayment({ amount: 100, cardToken: 'token123' })
)
.withCustomErrorHandler((error, context) => {
    this.showUserFriendlyPaymentError(error);
    this.logToExternalService('payment_failure', {
        duration: context.duration,
        method: context.methodName,
        error: error.message
    });
})
.withoutRethrow()
.execute();

if (result) {
    this.showPaymentSuccess(result);
}
```

{% endcode %}

The most "tolerant" mode — perfect for non-critical operations like notifications, where a failure shouldn't poison the rest of the flow.

## Parallel Calls

`timeBackendCall` returns a builder, and `.execute()` returns a regular `Promise`, so you can fan out calls and wait on them with `Promise.all`. Each call gets its own timing, start log, and completion log.

{% code lineNumbers="true" %}

```javascript
async connectedCallback() {
    this.triton = new Triton().bindToComponent('AccountDashboard');
    this.triton.trackComponentLifecycle('connected');

    try {
        const [accountData, relatedRecords, userPreferences] = await Promise.all([
            this.triton.timeBackendCall('getAccountData',
                () => getAccountData({ accountId: this.recordId })).execute(),
            this.triton.timeBackendCall('getRelatedRecords',
                () => getRelatedRecords({ accountId: this.recordId })).execute(),
            this.triton.timeBackendCall('getUserPreferences',
                () => getUserPreferences({})).execute()
        ]);

        this.accountData = accountData;
        this.relatedRecords = relatedRecords;
    } catch (error) {
        console.error('Failed to load dashboard data:', error);
    }
}
```

{% endcode %}

This pattern is especially powerful for record pages — you instantly get a per-call breakdown of which Apex method is the slow one, instead of staring at a single aggregated load time.

## What Gets Logged

For a successful backend call, you get two log entries:

| Log        | Type           | Summary                                | Notable fields                      |
| ---------- | -------------- | -------------------------------------- | ----------------------------------- |
| Start      | `BACKEND_CALL` | `Backend call started: <methodName>`   | `action = <methodName>`             |
| Completion | `BACKEND_CALL` | `Backend call completed: <methodName>` | `duration`, `action = <methodName>` |

A failure produces the start log plus a `Backend call failed: <methodName>` entry at `ERROR` — which opens an issue — with `duration`, the exception details, and the stack trace (unless you've supplied a custom handler). The start and completion records log at `FINE`; see [Levels and area](https://triton.pharos.ai/beyond-apex/profiling#levels-and-area).

## Best Practices

* Use the real Apex method name as `methodName` — searching and grouping logs by method is dramatically easier.
* Keep the arrow function passed to `timeBackendCall` thin. Anything you do *inside* it that isn't the Apex call gets folded into the duration measurement.
* Lean on `withoutRethrow()` for fire-and-forget side effects (analytics pings, optional enrichment) so a flaky non-critical call can't break your component.
* Combine with [User Interactions](https://triton.pharos.ai/beyond-apex/profiling/user-interactions) when a single user action triggers multiple backend calls — you'll get a parent interaction record plus children for each call.


# User Interactions

Time user-driven flows — form submissions, multi-step actions, and nested backend calls — with timeUserInteraction(...) and the unified PerformanceCallBuilder.

A "backend call" is a single trip to Apex. A "user interaction" is everything that happens between the user clicking a button and seeing the result — which may involve several backend calls, some client-side work, and a final UI update.

`timeUserInteraction(interactionName, fn)` is the umbrella timer for those higher-level flows. It uses the same `PerformanceCallBuilder` as [Backend Calls](https://triton.pharos.ai/beyond-apex/profiling/backend-calls), so the error-handling story is identical (default, `withoutRethrow`, custom handler, both). The only difference is the log type — interactions land as `TYPE.USER_INTERACTION` and the error context exposes `interactionName` instead of `methodName`. Levels match too: started and completed records log at `FINE`, a failure at `ERROR` with an issue.

## Basic Usage

{% code title="formHandler.js" lineNumbers="true" %}

```javascript
import Triton from 'c/triton';
import submitFormData from '@salesforce/apex/FormController.submitFormData';
import validateFormData from '@salesforce/apex/FormController.validateFormData';

export default class FormHandler extends LightningElement {
    triton;
    formData = {};

    connectedCallback() {
        this.triton = new Triton().bindToComponent('FormHandler');
        this.triton.trackComponentLifecycle('connected');
    }

    async handleSubmit() {
        await this.triton.timeUserInteraction('form-submit', async () => {
            const data = this.collectFormData();

            const validation = await this.triton.timeBackendCall(
                'validateFormData',
                () => validateFormData({ data })
            ).execute();

            if (!validation.isValid) {
                throw new Error(`Form validation failed: ${validation.errors.join(', ')}`);
            }

            const result = await this.triton.timeBackendCall(
                'submitFormData',
                () => submitFormData({ data })
            ).execute();

            this.showSuccessMessage(result);
            return result;
        }).execute();
    }
}
```

{% endcode %}

What you get out of this:

* One `User interaction started: form-submit` log when the user clicks.
* Two `Backend call started/completed` pairs for the validate + submit Apex methods.
* One `User interaction completed: form-submit` log at the end, with the *total* duration including both backend calls and any client-side work in between.

That parent-child relationship — interaction with nested backend calls — is the key reason to use `timeUserInteraction` even when "it's just one Apex call". It gives you a single record per user click that aggregates the whole experience.

## Nested Calls With Per-Step Resilience

Real-world flows often want different error policies per step. Here's a payment flow where notification failures don't kill the transaction:

{% code lineNumbers="true" %}

```javascript
async handleComplexUserFlow() {
    await this.triton.timeUserInteraction('payment-flow', async () => {
        const validation = await this.triton.timeBackendCall(
            'validatePaymentInfo',
            () => validatePaymentInfo({ cardToken: this.cardToken })
        ).execute();

        if (!validation.isValid) {
            throw new Error('Invalid payment information');
        }

        const paymentResult = await this.triton.timeBackendCall(
            'processPayment',
            () => processPayment({ amount: this.amount, cardToken: this.cardToken })
        ).execute();

        // Non-critical: log the failure but don't break the flow.
        await this.triton.timeBackendCall(
            'sendNotification',
            () => sendNotification({
                type: 'payment_success',
                userId: this.userId,
                paymentId: paymentResult.id
            })
        )
        .withCustomErrorHandler((error, context) => {
            console.warn(`Notification failed after ${context.duration}ms:`, error);
        })
        .withoutRethrow()
        .execute();

        return paymentResult;
    })
    .withCustomErrorHandler((error, context) => {
        // context.interactionName === 'payment-flow'
        console.error(`Payment flow failed for ${context.interactionName} after ${context.duration}ms:`, error);
        this.showPaymentFlowError(error);
    })
    .withoutRethrow()
    .execute();
}
```

{% endcode %}

Validation and processing rethrow (so a failure short-circuits the flow), notifications swallow their own errors, and the outer interaction wrap catches everything that escaped — surfacing a single user-facing error and a single top-level failure log.

## Custom Handler Context

Custom error handlers on user interactions receive:

{% code lineNumbers="true" %}

```javascript
{ interactionName: 'form-submit', duration: 1234 }
```

{% endcode %}

Contrast with backend calls, which use `methodName` instead of `interactionName`. The duration is measured from `timeUserInteraction(...)` to the moment the error was thrown.

## When to Use Interactions vs. Backend Calls

| If the work is...                                                       | Use                                                                                                                      |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| A single Apex round trip                                                | [`timeBackendCall`](https://triton.pharos.ai/beyond-apex/profiling/backend-calls)                                        |
| A user-triggered flow with one or more Apex calls and client-side logic | `timeUserInteraction` (often wrapping `timeBackendCall` inside)                                                          |
| Purely client-side timing (DOM work, animations, sync work)             | [`startPerformanceMark` / `endPerformanceMark`](https://triton.pharos.ai/beyond-apex/profiling/custom-marks)             |
| Component mount / unmount / re-render telemetry                         | [`trackComponentLifecycle` / `trackComponentRender`](https://triton.pharos.ai/beyond-apex/profiling/component-lifecycle) |

## Best Practices

* Use a stable, descriptive `interactionName`. Treat it like an event name (`'checkout-submit'`, `'opportunity-clone'`) — it'll become a primary grouping key in dashboards.
* When nesting, let inner failures rethrow by default. The outer interaction will record the failure and you don't need to duplicate logging at every level.
* Don't reach for `timeUserInteraction` when there's no user. For background or lifecycle work, the more specific helpers below give better signal.


# Component Lifecycle

Track LWC mount/unmount events and render counts with per-instance isolation, Locker Service-safe timing, and zero-effort multi-instance support.

Knowing *when* a component shows up and *how often* it re-renders is half the battle for UI performance. Triton ships two helpers for this — `trackComponentLifecycle` and `trackComponentRender` — and both work transparently across multiple instances of the same component on a single page.

## `trackComponentLifecycle(event)`

Call this in `connectedCallback` and `disconnectedCallback` to log mount and unmount events. The accepted strings are `'connected'` and `'disconnected'`.

{% code lineNumbers="true" %}

```javascript
connectedCallback() {
    this.triton = new Triton().bindToComponent('AccountDashboard');
    this.triton.trackComponentLifecycle('connected');
}

disconnectedCallback() {
    this.triton.trackComponentLifecycle('disconnected');
}
```

{% endcode %}

Each call produces a `TYPE.COMPONENT_LIFECYCLE` log entry with:

* `summary` = `Component lifecycle: <componentName> - <event>`
* `action` = `lifecycle-connected` or `lifecycle-disconnected`

These records are great for spotting components that mount unexpectedly, churn through DOM updates, or never get torn down properly (a common Aura → LWC migration headache).

## `trackComponentRender()`

Call from `renderedCallback`. Each invocation increments a per-instance counter and emits a `TYPE.COMPONENT_RENDER` log entry.

{% code lineNumbers="true" %}

```javascript
renderedCallback() {
    this.triton.trackComponentRender();
}
```

{% endcode %}

The log entry includes:

* `summary` = `Component render: <componentName>`
* `details` = `Render count: <n>` — useful for spotting components that re-render an order of magnitude more than expected.

{% hint style="warning" %}
`renderedCallback` fires on every reactive update. If you instrument a noisy component, expect a lot of records. Combine with a sampling strategy (e.g. only log every Nth render) if you need to keep volume in check. Render records log at `FINEST` and lifecycle records at `FINER`, so in production keep the LWC `Log_Level__mdt` threshold — or a rule scoped to `Type = ComponentRender` — at `FINER` or stricter, and lower it to `FINEST` only while you investigate.
{% endhint %}

## Per-Instance Isolation

When you call `bindToComponent('ProductSearch')`, Triton mints a UUID v4 behind the scenes and stores tracking data under a key like:

{% code lineNumbers="true" %}

```
ProductSearch-550e8400-e29b-41d4-a716-446655440000
```

{% endcode %}

That means three instances of `<c-product-search>` on the same page produce three independent streams of render counts, lifecycle events, and custom marks — even though the component name is identical.

{% code lineNumbers="true" %}

```javascript
// Instance 1: ProductSearch-550e8400-e29b-41d4-a716-446655440000
// Instance 2: ProductSearch-7b2c5f8d-3e4a-4d5b-8c9f-1a2b3c4d5e6f
// Instance 3: ProductSearch-9a8b7c6d-5e4f-3d2c-1b0a-fedcba987654

export default class ProductSearch extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('ProductSearch');
        this.triton.trackComponentLifecycle('connected');
    }

    renderedCallback() {
        this.triton.trackComponentRender();
    }
}
```

{% endcode %}

You don't need to manage instance IDs yourself — the proxy returned by `bindToComponent` carries them implicitly. The component name you pass is the *grouping* key (so dashboards can roll up across instances), and the UUID is the *uniqueness* key (so individual instances don't clobber each other's data).

## Initialization Timing

Where to bind depends on whether your component uses `@wire`. Same rule as in [LWC logging](https://triton.pharos.ai/beyond-apex/lwc#where-to-initialize):

* **Without `@wire`** — bind and call `trackComponentLifecycle('connected')` inside `connectedCallback`.
* **With `@wire`** — bind in the constructor so the logger exists before wire callbacks fire, but still call `trackComponentLifecycle('connected')` from `connectedCallback` for the mount semantics to be accurate.

{% code lineNumbers="true" %}

```javascript
export default class AccountDashboard extends LightningElement {
    triton;

    constructor() {
        super();
        this.triton = new Triton().bindToComponent('AccountDashboard');
    }

    @wire(getAccountData, { accountId: '$recordId' })
    wiredData({ error, data }) {
        // logger is already bound here
    }

    connectedCallback() {
        this.triton.trackComponentLifecycle('connected');
    }

    renderedCallback() {
        this.triton.trackComponentRender();
    }

    disconnectedCallback() {
        this.triton.trackComponentLifecycle('disconnected');
    }
}
```

{% endcode %}

## Locker Service-Safe Timing

Lifecycle and render entries timestamp themselves with `Date.now()` directly, and the broader profiling stack uses a `getCurrentTime()` helper that prefers `performance.now()` and silently falls back to `Date.now()` when the Performance API is restricted under Locker Service.

You don't need to special-case Locker Service in your code — every profiling helper in this section is built to degrade gracefully.

## What Happens Without `bindToComponent`

Both lifecycle and render helpers check the binding first. If you call them on an unbound logger:

{% code lineNumbers="true" %}

```javascript
// MISSING bindToComponent
this.triton = new Triton();
this.triton.trackComponentLifecycle('connected'); // no-op, console warning
```

{% endcode %}

…they emit a console warning (`Triton performance tracking requires bindToComponent() to be called first`) and return. Nothing crashes; you just won't see the records.

## Best Practices

* Pair every `trackComponentLifecycle('connected')` with a `trackComponentLifecycle('disconnected')`. Missing disconnects are the smoking gun for memory-leak-shaped problems.
* Add `trackComponentRender()` early in the rollout to baseline normal render counts — once you have that baseline, regressions stand out instantly.
* Use the component name to your advantage: keep it stable and human-readable (the class name is usually the right call), so logs are easy to group and search.


# Custom Performance Marks

Drop browser-style performance marks anywhere in your LWC code with startPerformanceMark / endPerformanceMark — fully per-instance and Locker Service-safe.

The high-level helpers (`timeBackendCall`, `timeUserInteraction`, `trackComponentLifecycle`, `trackComponentRender`) cover the common cases. When you need to time something that doesn't fit those moulds — a chunk of client-side data shaping, an animation, a debounce window, a delay between async steps — reach for raw performance marks.

The API mirrors the browser's `performance.mark()` pattern:

{% code lineNumbers="true" %}

```javascript
this.triton.startPerformanceMark('product-search');
// ... do work ...
this.triton.endPerformanceMark('product-search');
```

{% endcode %}

`startPerformanceMark` stores a starting timestamp keyed by mark name and component instance, pushes a span for the mark, and publishes an opening `TYPE.PERFORMANCE` log entry. `endPerformanceMark` computes the duration, publishes the matching completion entry on the same span, and clears the mark.

## When to Reach for Marks

Marks are the right tool when:

* You're measuring purely client-side work that has no backend round trip — e.g. parsing a CSV, computing a derived data structure, an animation timeline.
* You want to wrap *both sides* of an async boundary that the higher-level helpers don't model — e.g. starting a timer when a debounce fires, stopping it when the next user event arrives.
* You want to time a stretch of work that isn't a backend call or a discrete user interaction, without the error handling and result wrapping `timeBackendCall` layers on top.

If your work *is* an Apex call or a user-triggered flow, the higher-level helpers are almost always a better fit — they give you standard error handling and result wrapping for free.

## Example: Wrapping a Search Flow

{% code lineNumbers="true" %}

```javascript
async handleSearch() {
    const searchTerm = this.searchInput.value;

    this.triton.startPerformanceMark('product-search');
    try {
        const results = await this.triton.timeBackendCall(
            'searchProducts',
            () => searchProducts({ searchTerm })
        ).execute();

        this.products = results;
    } finally {
        // Always pair the start with an end — even on failure.
        this.triton.endPerformanceMark('product-search');
    }
}
```

{% endcode %}

This pattern is handy when you want a single "user-perceived search latency" record (the mark) plus the more granular backend call timing inside it. The mark captures the whole stretch — including the time between the backend response and the UI being ready — while the backend call captures just the round trip.

{% hint style="info" %}
You can have multiple marks active at once. Names are independent: `startPerformanceMark('search')` and `startPerformanceMark('hydrate')` coexist happily and end independently.
{% endhint %}

## Per-Instance Isolation

Marks are stored per component instance, just like lifecycle and render counts. Two instances of the same component can each have an active `product-search` mark and neither will interfere with the other.

{% code lineNumbers="true" %}

```javascript
export default class ProductSearch extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('ProductSearch');
        this.triton.trackComponentLifecycle('connected');
    }

    async search() {
        // Each instance's mark is isolated.
        this.triton.startPerformanceMark('search-operation');

        const results = await this.triton.timeBackendCall(
            'searchProducts',
            () => searchProducts({ term: this.searchTerm })
        ).execute();

        this.triton.endPerformanceMark('search-operation');
        this.products = results;
    }
}
```

{% endcode %}

## What Gets Logged

A mark emits a **pair** of log entries — one when it opens, one when it closes:

| Field          | Opening entry                                       | Completion entry                            |
| -------------- | --------------------------------------------------- | ------------------------------------------- |
| `type`         | `TYPE.PERFORMANCE`                                  | `TYPE.PERFORMANCE`                          |
| `summary`      | `Performance started: <componentName> - <markName>` | `Performance: <componentName> - <markName>` |
| `details`      | *(unset)*                                           | `Duration: <ms>ms`                          |
| `duration`     | *(unset)*                                           | the measured milliseconds                   |
| `action`       | the mark name                                       | the mark name                               |
| `spanId`       | the mark's span                                     | the **same** span                           |
| `parentSpanId` | the enclosing span                                  | the **same** enclosing span                 |

The two records share a span id, and the backend pairs them into a single span. Both records log at `FINE`. The reason `startPerformanceMark` logs its opening record right away — buffered like any other log, and sent with the next flush — is that the span has to exist while the mark is open: anything logged in between is parented to it, and a mark left open by an unmounted component, a navigation, or an exception would otherwise leave those logs pointing at a span that never arrives.

If you call `endPerformanceMark` for a name that was never started, Triton emits a console warning and skips the log.

{% hint style="info" %}
**Same concept in Apex.** `Triton.startMark()` / `Triton.endMark()` bring this pattern to Apex, with the same paired records and the same summary prefixes — see [Performance Marks in Apex](https://triton.pharos.ai/common-apex-usage-patters/performance-marks). The names differ by tier: LWC uses `startPerformanceMark` / `endPerformanceMark`, Apex uses `startMark` / `endMark`.
{% endhint %}

## Locker Service Compatibility

Mark timing uses the same `getCurrentTime()` helper described in [Component Lifecycle](https://triton.pharos.ai/beyond-apex/profiling/component-lifecycle#locker-service-safe-timing): `performance.now()` when available, `Date.now()` otherwise. You get sub-millisecond precision where allowed, and you never need a fallback path in your code.

## Best Practices

* **Always pair `startPerformanceMark` with `endPerformanceMark`.** Wrap the end in `finally` so an exception in the middle doesn't leave a dangling mark.
* **Use descriptive, hyphenated names.** They show up directly in dashboards (`action` column).
* **Bind first.** Custom marks require `bindToComponent()` — without it you'll just get a console warning and no log.
* **Don't double up.** If you're already wrapping with `timeBackendCall` or `timeUserInteraction`, you usually don't need a custom mark on top — the helpers already record duration.


# Logging in Flow

Add structured logging to Salesforce Flows with Triton's invocable Log action — no code required, with deferred batching to protect your platform-event budget.

Flows are where a lot of business logic lives these days — and where a lot of it silently breaks. A screen flow fails three steps in, or an autolaunched flow makes a bad decision, and all you have is a terse debug email. Triton brings the same structured logging you use in Apex to Flow, entirely through a **no-code invocable action**.

{% hint style="info" %}
Screen flows run in user context, so anyone running one needs the `Triton End User` permission set to use the Log action. Record-triggered and autolaunched flows run in system context by default and need no permission set at all. See [Configure Permissions](https://triton.pharos.ai/installing-pharos-triton#configure-permissions) for the full model.
{% endhint %}

## The Log action

Triton ships an invocable Apex action — labeled **Log**, under the **TritonLogging** category — that you drop into any Flow. It builds a proper `pharos__Log__c` record from parameters you set right in Flow Builder. No Apex, no formulas — just an action element.

Let's walk through a real example: a **Partner Intake** screen flow that captures form data, assigns a lead score by partner type, and creates a lead.

## Step 1 — Log first, log early

Make a logging action the **very first element** in the flow. Two reasons: you always get a record even if the flow blows up downstream, and — crucially — that first log becomes the **parent** that every later log nests under.

1. **Click (+)** and drop an **Action** element onto the canvas.
2. **Search** for "triton" and select the **Log** action.

## Step 2 — Configure the parameters

Give the action a clear label (e.g. "Log Partner Intake Start") and set its parameters.

| Parameter                        | Required | What it does                                                                                                                                                                             |
| -------------------------------- | :------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Area**                         |     ✅    | Functional area from a business perspective — `Accounts`, `LeadConversion`, etc. See [Enums](https://triton.pharos.ai/core-concepts/enums).                                              |
| **Summary**                      |     ✅    | The one-line headline for the record.                                                                                                                                                    |
| **Interview GUID**               |     ✅    | The running Flow instance id. **Always pass `$Flow.InterviewGuid`** (see below).                                                                                                         |
| **Category**                     |          | Leave as `Flow` for most logging. Drives how Pharos renders the record; invalid values fall back to `Flow`.                                                                              |
| **Type**                         |          | Technical classification — e.g. `Screen Flow`, `Autolaunched Flow`.                                                                                                                      |
| **Details**                      |          | The long form: record ids, decision variables, user inputs — anything that explains what happened.                                                                                       |
| **Level**                        |          | Severity (see [Log Levels](https://triton.pharos.ai/core-concepts/log-levels)). Defaults to `INFO`; invalid values fall back to `INFO`. An `ERROR` level automatically creates an issue. |
| **Flow API Name**                |          | The **plain** API name of this flow — no version suffix.                                                                                                                                 |
| **Flow Version**                 |          | This flow's version number, e.g. `4`. Stored separately, in `pharos__Flow_Version__c`.                                                                                                   |
| **Operation**                    |          | Optional name of the operation being performed.                                                                                                                                          |
| **Transaction ID**               |          | Pass an existing id to **resume** a transaction and group these logs with logs from another context.                                                                                     |
| **Additional Fields**            |          | A JSON map of extra field values — see [below](#pass-extra-fields-with-additional-fields).                                                                                               |
| **Stacktrace / Full Stacktrace** |          | Supplied automatically by the X-Ray machine; you don't set these by hand.                                                                                                                |

### Always pass `$Flow.InterviewGuid`

The **Interview GUID** is the single most important parameter after Area and Summary. It's the id of the running Flow instance, and passing `$Flow.InterviewGuid` lets Pharos link your custom logs to Salesforce's own Flow diagnostics — enriching every record with:

* stack traces for error tracking,
* user information,
* related object details,
* installed package information,
* pending jobs in the flow queue,
* total active session information.

Make it a rule: every Log action gets `$Flow.InterviewGuid`.

### Flow API Name and Flow Version

Pass these as two parameters, not one: the **plain** API name in **Flow API Name**, and the version number on its own in **Flow Version**. That's the same split Salesforce's own Flow error logs use, and Triton stores the version in `pharos__Flow_Version__c`.

Keeping the version out of the name matters for filtering. Component-scoped [`Log_Level__mdt`](https://triton.pharos.ai/core-concepts/log-levels) rules match the Flow API Name in full — case-insensitively, but otherwise exactly — so a rule naming `My_Flow` never matches a log whose Flow API Name is `My_Flow-4`.

Flow hands **Flow Version** over as text and Triton parses it into a number. A value it can't parse never fails the log: Triton appends `Unable to parse flow version: <value>. Flow Version will not be set.` to **Details** and saves the log without the version.

### Use constants for the repeated parameters

`Area`, `Category`, and `Type` are the same across most of your log actions. Define them once as **constants** and reference them everywhere — change the value in one place instead of hunting through every action.

Even a 4-action flow benefits: without constants, changing the Area means editing four elements; with constants, one. Adopt a naming convention — prefix log resources with `Log_` — so they're easy to filter in the toolbox.

### Use text templates for details

The **Details** parameter is your troubleshooting lifeline, so make it rich: record ids, decision variables, user inputs, anything that shaped the flow's path. **Text templates** are the right tool for mixing static text with dynamic flow data.

{% hint style="info" %}
Prefix detail templates with `Log_Details_` and use the **Plain Text** view — rich-text formatting is irrelevant here and just gets in the way.
{% endhint %}

## Step 3 — Log throughout the flow

With the opening log in place, add more at the moments that matter:

1. **Flow start** — the initiation and its input parameters.
2. **User interactions** — form submissions, screen inputs, decisions.
3. **Data operations** — before and after DML, callouts, transformations.
4. **Decision points** — which branch the flow took.
5. **Fault paths** — detailed logging wherever a fault connector lands.

{% hint style="warning" %}
**Do** build a fresh Log action each time. **Don't** clone-and-paste existing ones — cloning drags along confusing element names and stale parameter mappings that cause subtle, hard-to-spot bugs.
{% endhint %}

## Step 4 — Read the output

Run the flow (ours is rigged to fail at lead creation) and open the **Partner Intake Flow Start** log. Because every action passed `$Flow.InterviewGuid`, the whole run is grouped under that first parent log:

Click any entry to see the summary, details, and custom context you configured:

{% hint style="info" %}
Notice the final **Error Occurred** entry — *you didn't create that one*. Triton automatically captures unhandled Flow exceptions and files them under your trace, giving you the failure alongside your own breadcrumbs with zero extra configuration.
{% endhint %}

Open that error and you land in the standard Pharos Flow debug view — the flow's state, error details, and decision pathways, all in one place:

## Pass extra fields with Additional Fields

Need to set fields the standard parameters don't cover? Build a JSON map in a text template and pass it to **Additional Fields**:

<figure><img src="https://3094374025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFlq7dXDt5Z9LFxymJV0A%2Fuploads%2Fgit-blob-e73153619897833b9f50e9a66bdb0816da2127c3%2FScreenshot_2024-09-08_at_5_06_01_PM.png?alt=media" alt=""><figcaption><p><em>A well-formed JSON object of extra field values.</em></p></figcaption></figure>

Each key is a field API name, each value the value to set. Malformed JSON won't break your flow — Triton catches the parse failure and appends a note to the details instead of throwing.

## Deferred flush & batching

Here's something Flow logging does for you quietly. Flows can run at enormous volume, and publishing a platform event per log would torch your allocations. So instead of publishing inline, the Log action **drains** its buffered logs and hands them to a batch (`TritonFlowFlushBatch`) that publishes them together, slightly later, off the hot path.

The upshot: your Flow logs are **not** published the instant the action runs — they're buffered in Org Cache and flushed by a short-delayed batch that coalesces logs across concurrent Flow runs into as few platform events as possible. The batch collects what's in the cache when it's scheduled; logs that arrive during its delay go out with the next batch. It's on by default, and it's why heavy Flow logging stays cheap. (The underlying `drain()` mechanism is described in [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).)

Three settings tune it — see [Installing Pharos Triton → Settings](https://triton.pharos.ai/installing-pharos-triton). **Disable Flow Flush Batch** publishes Flow logs in the Flow's own transaction instead. **Flow Flush Batch Delay** sets how long the batch waits (default 1 minute), and **Cache TTL** sets how long logs may sit in the cache (default 5 minutes). Keep the delay below the Cache TTL: Flow logs still cached when the TTL expires are never published.

However it's configured, the **Log** action never fails the Flow. A log that can't be built or published is dropped and noted in the Apex debug log, and the interview carries on.

## Best practices

* **Log first, log at every critical point** — start, user input, before/after data ops, decisions, and every fault path.
* **Always pass `$Flow.InterviewGuid`** — it's what enables grouping and automatic error enrichment.
* **Use constants** for `Area`, `Category`, `Type`; **use text templates** (`Log_Details_…`) for details.
* **Name consistently** — prefix actions, constants, and templates with `Log_`.
* **Set `ERROR` on fault paths** so failures create issues automatically.
* **Reuse a Transaction ID** when a Flow is part of a larger process — resume the id from Apex or LWC to fold the Flow's logs into one cross-technology trace.

## Where to go next

A Flow rarely runs in isolation — it's often kicked off by Apex, which was kicked off by an LWC. To trace a whole journey across all three layers as one story, see [End-to-End Logging](https://triton.pharos.ai/end-to-end).


# End-to-End Logging

How Triton stitches one user action — starting in an LWC, hopping into Apex, and fanning out into a Flow — into a single correlated trace.

A single click in the UI almost never stays in one context. The user presses a button in a Lightning Web Component, that calls an Apex controller, the controller commits a record, and the DML kicks off an autolaunched Flow. Four contexts, one intent — and, without help, four disconnected piles of logs.

This section is about making those four piles into **one story**. Triton correlates logs across LWC, Apex, and Flow using a shared **transaction id**, so when you open a log in Pharos you can follow the whole chain from the button press to the Flow that failed three hops later.

Three pages make up this section:

* **This page** — the full LWC → Apex → Flow walkthrough.
* [Transactions & Platform Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache) — how the transaction id is created, resumed, and shared across contexts (including `Triton.withCache()` and `TritonCacheManager`).
* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) — how spans (`spanId` / `parentSpanId`) add parent-child structure *within* a transaction, and how that maps to OpenTelemetry concepts.

If you haven't yet, skim [Logging in LWC](https://triton.pharos.ai/beyond-apex/lwc) and [Logging in Flow](https://triton.pharos.ai/flows) first — this page assumes you know the basics of each and focuses on wiring them together.

## The scenario

We'll trace one interaction all the way through:

1. A user clicks a button in an LWC.
2. The LWC calls an Apex controller.
3. The controller performs DML.
4. The DML fires an autolaunched Flow, which logs its own progress.

Our goal: **every log from all four steps shares one transaction id**, so they group together in Pharos.

{% code lineNumbers="true" %}

```
Transaction: 7fb8c320-e8f9-4f1b-9742-1a5768b9e0d2
├── LWC        "Flow Demo - Start"        (Frontend)
├── Apex       "Performing DML"           (Backend)
└── Flow       Log actions                (Flow)
    └── Unhandled Flow error              (auto-captured)
```

{% endcode %}

## What "correlation" actually means

The correlation id is the transaction id. In Apex it lives statically on `Triton.TRANSACTION_ID`; in LWC it lives on your logger instance as `this.triton.transactionId`; in Flow it rides along as the **Transaction ID** parameter of the **Log** action. When two logs carry the same transaction id, Pharos groups them.

The interesting question is how that one id makes it from the browser, into Apex, and on into the Flow. There are two ways to do it, and they're not mutually exclusive:

| Approach             | How the id travels                                                                                                                                                                                                                                                                                             | Best for                                                                            |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| **Explicit passing** | You read `this.triton.transactionId` in the LWC and pass it to Apex as a parameter; Apex calls `Triton.resumeTransaction(id)`.                                                                                                                                                                                 | Simple, linear call paths where you control every hop.                              |
| **Platform cache**   | `Triton.withCache()` stashes the id in platform **Org** cache under a per-user key. Later Apex that calls `Triton.withCache()` as the same user resumes it within the Cache TTL. A Flow in the same transaction inherits it; a Flow in a separate transaction needs the id passed to its Transaction ID input. | Multi-component or multi-call scenarios where passing the id everywhere is painful. |

Both produce the exact same grouped result. The rest of this page walks each one. For the full mechanics of transactions and the cache, see [Transactions & Platform Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache).

{% hint style="info" %}
**Why does this even work across the DML → Flow boundary?** The autolaunched Flow runs **inside the same Apex transaction** as your controller's DML. Because Triton keeps `TRANSACTION_ID` as static state for the life of that Apex transaction, the Flow's **Log** action inherits the id automatically — you don't have to pass it. The two approaches below are really about getting the id from the *browser* into *Apex* in the first place.
{% endhint %}

## Approach 1 — Explicit parameter passing

The most transparent option: read the transaction id in the LWC and hand it to Apex directly.

### The LWC

{% code lineNumbers="true" %}

```javascript
// logDemoDirect.js
import apexActionThatTriggersFlow from '@salesforce/apex/LogDemoDirectController.apexActionThatTriggersFlow';
import Triton, { AREA, TYPE } from 'c/triton';

export default class LogDemoDirect extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('logDemoDirect');
    }

    async executeScenario() {
        // Log the start of the interaction from the UI
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('Flow Demo - Start')
                .details('Starting execution with explicit id passing')
        );

        try {
            // Hand the current transaction id to Apex
            await apexActionThatTriggersFlow({
                transactionId: this.triton.transactionId
            });
        } catch (error) {
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}
```

{% endcode %}

`this.triton.transactionId` is the id the LWC logger generated (or resumed) for this session. Passing it as a plain method argument is all it takes.

### The Apex controller

{% code lineNumbers="true" %}

```apex
public with sharing class LogDemoDirectController {
    @AuraEnabled
    public static void apexActionThatTriggersFlow(String transactionId) {
        // Adopt the id the LWC already established
        Triton.resumeTransaction(transactionId);

        Triton.debug(Triton.t
            .type(TritonTypes.Type.Backend)
            .area(TritonTypes.Area.Community)
            .summary('Flow Demo - Apex')
            .details('Performing DML to trigger flow'));

        try {
            List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
            if (!accounts.isEmpty()) {
                accounts[0].Name = 'Flow Demo';
                update accounts;   // ← triggers the autolaunched Flow
            }
        } catch (Exception e) {
            Triton.error(Triton.t.area(TritonTypes.Area.Community).exception(e));
        }

        Triton.flush();   // publish the buffered Apex logs
    }
}
```

{% endcode %}

Two things to notice:

* `Triton.resumeTransaction(transactionId)` sets `TRANSACTION_ID` to the LWC's id. From here, every Apex log — and every log the Flow produces during the `update` — carries that id.
* We buffer with `Triton.debug(...)` / `Triton.error(...)` and publish once with `Triton.flush()`. See [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing) for why that's the right default.

## Approach 2 — Platform cache

When threading a parameter through every layer gets tedious, let the platform cache carry the id for you.

### The LWC

The LWC barely changes — it doesn't need to pass anything:

{% code lineNumbers="true" %}

```javascript
// logDemoCache.js
import apexActionThatTriggersFlow from '@salesforce/apex/LogDemoCacheController.apexActionThatTriggersFlow';
import Triton, { AREA, TYPE } from 'c/triton';

export default class LogDemoCache extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('logDemoCache');
    }

    async executeScenario() {
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('Flow Demo - Start')
                .details('Starting execution with platform cache')
        );

        try {
            // No transaction id argument — the cache handles it
            await apexActionThatTriggersFlow();
        } catch (error) {
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}
```

{% endcode %}

{% hint style="info" %}
When the LWC's logs are saved, `TritonLwc.saveComponentLogs` calls `Triton.withCache()` first. If an id is already cached for the user (within the Cache TTL), that cached id wins and the LWC's own id is not used; otherwise it resumes the LWC's id and writes it into platform Org cache. That's what makes it available to a later Apex call without any parameter passing. The full sequence is spelled out in [Transactions & Platform Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache#how-the-id-travels-lwc-apex-flow).
{% endhint %}

### The Apex controller

{% code lineNumbers="true" %}

```apex
public with sharing class LogDemoCacheController {
    @AuraEnabled
    public static void apexActionThatTriggersFlow() {
        // Resume the id from platform cache (or start one if none is cached)
        Triton.withCache();

        Triton.debug(Triton.t
            .type(TritonTypes.Type.Backend)
            .area(TritonTypes.Area.Community)
            .summary('Flow Demo - Apex')
            .details('Performing DML to trigger flow'));

        try {
            List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
            if (!accounts.isEmpty()) {
                accounts[0].Name = 'Flow Demo';
                update accounts;
            }
        } catch (Exception e) {
            Triton.error(Triton.t.area(TritonTypes.Area.Community).exception(e));
        }

        Triton.flush();
    }
}
```

{% endcode %}

`Triton.withCache()` does the work: if a transaction id is sitting in Org cache, it resumes it; if not, it starts a fresh one and caches it. Either way, the Flow triggered by the `update` inherits the same id.

## The Flow leg

The Flow side is exactly as described in [Logging in Flow](https://triton.pharos.ai/flows) — add the **Log** action, pass `$Flow.InterviewGuid` as the Interview GUID, and configure Area / Summary / Details. You do **not** need to set the **Transaction ID** parameter for this scenario: because the Flow runs inside the same Apex transaction that already called `resumeTransaction` or `withCache`, it picks up `TRANSACTION_ID` automatically.

{% hint style="info" %}
**Set the Transaction ID parameter only when the Flow starts the chain**, or when you're correlating a Flow that runs in a *separate* transaction from the Apex that set the id. In that case, pass the id into the Flow and map it to the **Log** action's **Transaction ID** — it will `resumeTransaction` for you.
{% endhint %}

### Flow logs publish a little later

There's one behavioral detail worth knowing for end-to-end debugging. Flow logs aren't published inline like Apex logs. The **Log** invocable **drains** Triton's buffer and hands the records to `TritonFlowFlushBatch`, a singleton batch that publishes them shortly after (buffered in Org cache, flushed via a short-delayed batch). This keeps high-volume Flows from burning platform-event allocations on the hot path.

The practical upshot: **the LWC and Apex logs may appear in Pharos a beat before the Flow logs.** They'll all land under the same transaction id — the Flow leg just arrives fashionably late. This is the `drain()` path described in [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).

## Unhandled Flow errors come along for free

If the Flow throws an **unhandled** error, you don't need a fault path to capture it. Because you passed `$Flow.InterviewGuid` to your **Log** action, Pharos correlates the automatically-captured Flow error with your transaction. Let's force one by clearing a required field:

{% code lineNumbers="true" %}

```apex
public with sharing class LogDemoCacheController {
    @AuraEnabled
    public static void apexActionThatTriggersFlow() {
        Triton.withCache();

        Triton.debug(Triton.t
            .type(TritonTypes.Type.Backend)
            .area(TritonTypes.Area.Community)
            .summary('Flow Demo - Apex')
            .details('Triggering a flow that will fail'));

        try {
            List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
            if (!accounts.isEmpty()) {
                accounts[0].Name = null;   // Flow validation will reject this
                update accounts;
            }
        } catch (Exception e) {
            Triton.error(Triton.t.area(TritonTypes.Area.Community).exception(e));
        }

        Triton.flush();
    }
}
```

{% endcode %}

The resulting trace in Pharos:

{% code lineNumbers="true" %}

```
Transaction: 7fb8c320-e8f9-4f1b-9742-1a5768b9e0d2
├── LWC   "Flow Demo - Start"
├── Apex  "Flow Demo - Apex"
└── Flow
    ├── Log          (start)
    └── Unhandled Flow error   ← captured automatically via Interview GUID
        └── Interview GUID, current element, message, stack trace
```

{% endcode %}

## Do / Don't

{% hint style="success" %}
**Do**

* **Log the very first action from the UI** so the transaction has a clear origin point.
* **Pick one propagation strategy per chain** — explicit passing *or* cache — and stay consistent so the id's journey is easy to follow.
* **Always pass `$Flow.InterviewGuid`** to **Log** actions so unhandled Flow errors correlate.
* **Flush your Apex logs** before returning from the controller (or use `Triton.logNow` for critical ones).
* **Expect the Flow leg to arrive slightly later** — that's the deferred batch working as designed.
  {% endhint %}

{% hint style="danger" %}
**Don't**

* **Don't set the Flow's Transaction ID parameter** when the Flow is downstream of Apex in the same transaction — it already inherits the id, and overriding it can split the trace.
* **Don't assume the cached id crosses user boundaries.** Org cache works in async and system contexts, but the id is keyed per user — a context running as a different user won't resume it. Pass the id explicitly there. See [Transactions & Platform Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache#when-the-cache-is-not-available).
* **Don't call `Triton.startTransaction()` mid-chain** — it mints a *new* id and disconnects everything logged afterward.
* **Don't hand-roll type/summary/stack trace for exceptions** — `Triton.t.exception(e)` does all of it.
  {% endhint %}

## Where to go next

* [Transactions & Platform Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache) — the mechanics behind `resumeTransaction`, `withCache`, and the cache manager.
* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) — add parent-child structure inside a single transaction.
* [Logging in LWC](https://triton.pharos.ai/beyond-apex/lwc) · [Logging in Flow](https://triton.pharos.ai/flows) · [Logging in Apex](https://triton.pharos.ai/common-apex-usage-patters)
* Coming from 1.x? The transaction methods are unchanged in spirit but now static — see [Migration](https://triton.pharos.ai/migration).


# Transactions & Platform Cache

How a transaction id ties logs together across LWC, Apex, and Flow — the lifecycle methods that manage it and the platform cache that moves it between contexts.

A **transaction id** is Triton's correlation key. Every log carrying the same id groups together in Pharos, no matter which context produced it. This page is the reference for the two things that make correlation work: the transaction lifecycle methods (`startTransaction`, `resumeTransaction`, `stopTransaction`) and the platform cache that shuttles the id between contexts (`withCache` and `TritonCacheManager`).

If you just want to see it wired up in a real LWC → Apex → Flow chain, start with the [End-to-End walkthrough](https://triton.pharos.ai/end-to-end) and come back here for the details.

## The transaction id

In Apex, the current transaction id lives on a single static field:

{% code lineNumbers="true" %}

```apex
public static String Triton.TRANSACTION_ID;
```

{% endcode %}

Because Apex statics live for the duration of one Apex transaction, this one field is shared by everything you log — every `Triton.log(...)`, every convenience method, every Flow **Log** action that runs during that transaction. That's the whole reason logs correlate automatically without you threading an id around. (For the bigger picture on static state, see [The Static Logging API](https://triton.pharos.ai/core-concepts/static-logging-api).)

## Managing the lifecycle

Three static methods drive the transaction id.

### `startTransaction()`

Generates a brand-new UUID v4, stores it in `TRANSACTION_ID`, and returns it. If the cache is enabled (see below), it also writes the id to Org cache.

{% code lineNumbers="true" %}

```apex
String id = Triton.startTransaction();
// TRANSACTION_ID is now a fresh UUID like 7fb8c320-e8f9-4f1b-9742-1a5768b9e0d2
```

{% endcode %}

Call this to **begin a new correlation** — for example at the top of an entry point that isn't downstream of any other context.

### `resumeTransaction(String transactionId)`

Adopts an **existing** id instead of minting one. Use it to tie the current context to a transaction that started somewhere else — the classic case being an Apex controller adopting the id its LWC caller already established.

{% code lineNumbers="true" %}

```apex
Triton.resumeTransaction(idFromLwc);
// Every subsequent log now correlates with the LWC's logs
```

{% endcode %}

If the cache is enabled, `resumeTransaction` also re-caches the id — which conveniently extends its time-to-live.

### `stopTransaction()`

Clears `TRANSACTION_ID` (and removes it from cache when caching is on). After this, the next log that needs an id will start a fresh transaction.

{% code lineNumbers="true" %}

```apex
Triton.stopTransaction();
```

{% endcode %}

{% hint style="warning" %}
`startTransaction()` mid-chain is a common footgun — it mints a **new** id and silently disconnects everything logged afterward from the trace you were building. When you mean "attach to the existing trace," reach for `resumeTransaction(id)`, not `startTransaction()`.
{% endhint %}

## `Triton.withCache()` — let the id travel on its own

Passing a transaction id through method parameters works, but it gets tedious across many components and calls. `Triton.withCache()` offers an alternative: park the id in **platform Org cache** so any later context — even in a separate transaction — can pick it up without you passing anything.

Here's exactly what `withCache()` does:

1. Checks whether Org cache is available (`TritonCacheManager.available()`).
2. **If it isn't available** — turns caching off, and starts a transaction if one isn't already running. Everything still works; you just don't get cross-transaction propagation.
3. **If it is available** — turns caching on, then:
   * looks for a cached transaction id and, if found, **resumes** it;
   * otherwise, if there's no current id, **starts** a new one (which gets cached).

{% code lineNumbers="true" %}

```apex
// At the top of an Apex entry point that should share the browser's transaction:
Triton.withCache();
// TRANSACTION_ID is now either the resumed cached id or a freshly cached new one
```

{% endcode %}

The cached id is stored in Org cache under a **per-user key**, with a time-to-live set by the **Cache TTL (minutes)** setting — **5 minutes** by default. Each resume re-caches it and resets that clock, so an active chain of calls keeps the id alive. Because the key is namespaced by user, two users' transactions never collide in the shared Org cache.

{% hint style="info" %}
**Org cache vs. the browser.** The LWC logger keeps *its* transaction id in the browser's `sessionStorage`; Apex's `withCache()` uses Salesforce **platform Org cache**. These are two different stores. They get connected because the LWC **sends its id along with every log payload**. `TritonLwc.saveComponentLogs` calls `withCache()` first: if an id is already cached for the user (within the TTL), that cached id wins and the browser's id is not used; otherwise it resumes the browser's id and copies it into Org cache. Later Apex that calls `Triton.withCache()` as the same user resumes it within the Cache TTL. A Flow in the same transaction inherits it; a Flow in a separate transaction needs the id passed to its Transaction ID input.
{% endhint %}

## `TritonCacheManager` — the cache behind it all

`TritonCacheManager` is the thin layer that centralizes every platform-cache operation. Triton uses a single partition — **Org cache** — for both things it caches:

| Method group | Methods                           | What Triton uses it for                                                                                 |
| ------------ | --------------------------------- | ------------------------------------------------------------------------------------------------------- |
| Value cache  | `put`, `get`, `getKeys`, `remove` | Storing the **transaction id** (per-user key) and buffering **Flow logs** for the deferred flush batch. |
| Availability | `available`                       | Gatekeeper for `withCache()`.                                                                           |

Org cache is the right home for both: it isn't tied to a user session, so the transaction id survives across separate transactions and asynchronous contexts, and Flow logs remain discoverable by a batch job that runs later. Triton namespaces the transaction-id key by user id so entries don't collide in the org-wide cache.

### `available()`

The gatekeeper for `withCache()`. It probes `Cache.Org` and returns `false` if Org cache can't be reached (for example, when no Org cache capacity is allocated). This is what lets Triton degrade gracefully: no cache, no problem — logging continues without cross-context propagation.

{% code lineNumbers="true" %}

```apex
if (TritonCacheManager.available()) {
    // safe to rely on cached transaction ids
}
```

{% endcode %}

{% hint style="info" %}
**Mock mode for tests.** In test context, `TritonCacheManager` swaps the real `Cache.Org` for an in-memory map (and `available()` returns `true`). This sidesteps a platform quirk where cache `put()` succeeds silently but `get()` returns `null` under test — so your transaction-correlation logic is actually exercisable in unit tests.
{% endhint %}

## When the cache is not available

Because Triton uses **Org cache** — which is not tied to a user session — cache-backed correlation works in interactive contexts (an LWC calling Apex, a user running a screen Flow) **and** in asynchronous ones (Batch, Queueable, Scheduled, `@future`, platform-event triggers). The cache is only "unavailable" when the org has no Org cache capacity allocated or the platform can't reach it.

Triton handles that case for you: `withCache()` checks `available()` first and, when the cache is out of reach, quietly falls back to a plain in-memory transaction for that Apex transaction. Nothing breaks; you simply don't get the automatic cross-transaction hand-off.

{% hint style="success" %}
**Do** rely on `withCache()` across LWC → Apex → Flow chains and asynchronous jobs alike.

**Don't** forget that the cached id is keyed **per user**. When a downstream context runs as a *different* user (for example, a platform-event subscriber running as the Automated Process user), it won't resume the caller's id — **pass it explicitly** and call `resumeTransaction(id)` there.
{% endhint %}

## How the id travels: LWC → Apex → Flow

Putting the pieces together, here's the journey of a single transaction id through the canonical chain:

1. **LWC** generates a transaction id (UUID v4), stored in the browser's `sessionStorage`, and tags every log with it via `this.triton.transactionId`.
2. When those logs flush, **`TritonLwc.saveComponentLogs`** calls `Triton.withCache()`. If no id is cached for the user yet, it resumes the browser's id and copies it into platform **Org** cache; if one is already cached (within the TTL), the cached id wins.
3. Your **Apex controller** calls `Triton.withCache()` (or `Triton.resumeTransaction(idFromLwc)` if you passed it explicitly) and adopts the same id.
4. The controller's DML fires an **autolaunched Flow** in the *same* Apex transaction. The Flow's **Log** action inherits `TRANSACTION_ID` automatically — no parameter needed.
5. Flow logs are drained to `TritonFlowFlushBatch` and published shortly after, still under the same id.

The result is one grouped trace in Pharos spanning all three technologies. The step-by-step controller and component code lives in the [End-to-End walkthrough](https://triton.pharos.ai/end-to-end).

## Quick reference

{% code lineNumbers="true" %}

```apex
// Lifecycle
Triton.startTransaction()        // mint a new UUID id, return it
Triton.resumeTransaction(id)     // adopt an existing id (re-caches it if caching is on)
Triton.stopTransaction()         // clear the id (and remove from cache if caching is on)
Triton.TRANSACTION_ID            // the current id (static, per Apex transaction)

// Platform cache
Triton.withCache()               // resume cached id, or start + cache a new one (if Org cache is available)

// Cache manager (usually called for you, not directly)
TritonCacheManager.available()   // is Org cache reachable?
```

{% endcode %}

## Related reading

* [End-to-End Logging](https://triton.pharos.ai/end-to-end) — the full LWC → Apex → Flow walkthrough.
* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) — structure *within* a transaction.
* [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing) — how Flow logs reach the deferred batch via `drain()`.
* [The Static Logging API](https://triton.pharos.ai/core-concepts/static-logging-api) — why the transaction id can live on a static field.


# Spans & Distributed Tracing

How Triton builds a parent-child trace out of spans — one level deeper than the transaction id, recording which work happened inside which.

The [transaction id](https://triton.pharos.ai/end-to-end/transactions-and-cache) answers one question: *which logs belong to the same operation?* **Spans** answer the next one: *how are they nested?* A span marks a single unit of work, and a parent span points at the work that contains it. Chain them together and a flat list of logs becomes a tree — the button click, the backend call it triggered, the step that call ran inside.

Every Triton log carries two span fields:

| Field               | Builder method          | Meaning                               |
| ------------------- | ----------------------- | ------------------------------------- |
| `Span_Id__c`        | `.spanId(String)`       | Identifies this unit of work.         |
| `Parent_Span_Id__c` | `.parentSpanId(String)` | Points at the enclosing unit of work. |

Set both across a set of logs and you've described a hierarchy.

## Spans in LWC — automatic hierarchy

The LWC logger builds the span tree for you. It keeps a **span context stack** whose root is the transaction id, and it stamps every log with a freshly generated `spanId` and a `parentSpanId` taken from the top of that stack.

You don't call `spanId()` by hand for ordinary logs — `makeBuilder()` (and therefore `debug()`, `info()`, `error()`, etc.) already does it:

{% code lineNumbers="true" %}

```javascript
// Each of these logs gets a unique spanId and, as its parent,
// the current top of the span stack (the transaction root by default).
this.triton.log(
    this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
        .summary('Loaded account panel')
);
```

{% endcode %}

### Logical steps

For multi-step UIs (wizards, multi-screen flows), `enterStep()` resets the stack back to the transaction root and pushes a new span for the step. Everything logged afterward hangs off that step:

{% code lineNumbers="true" %}

```javascript
const stepSpan = this.triton.enterStep();   // start "Step 2"
this.triton.log(
    this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
        .summary('Entered shipping details')
);
// → this log's parentSpanId is the step span
```

{% endcode %}

### Performance calls nest automatically

The profiling helpers — `timeBackendCall(...)`, `timeUserInteraction(...)`, and performance marks — push their own span while they run and pop it when they finish. Their start/complete/failure logs share that span, and any logs you emit *during* the call become children of it. That's how a backend call and everything it did end up neatly grouped. (See [Profiling](https://triton.pharos.ai/beyond-apex/profiling) for the full API.)

### Surviving navigation

If a logical operation spans multiple page loads, call `enableSpanPersistence()` to back the span stack with `sessionStorage`, so the hierarchy survives navigation instead of resetting.

## Spans in Apex

Apex has the same two defaults, one for each situation.

**Outside a mark**, the shape is the simple one: if you don't set a span id, the builder fills `Span_Id__c` with the current request id at build time, and `Parent_Span_Id__c` stays null. Every log in one Apex request shares a span, without any effort and without any change to what you have today.

### Marks build the tree

**Inside a mark**, Apex behaves like LWC. [Performance marks](https://triton.pharos.ai/common-apex-usage-patters/performance-marks) keep a span stack, and while a mark is open every log you emit gets its own span id and hangs off the innermost mark:

{% code lineNumbers="true" %}

```apex
Triton.startMark();                                        // OrderService.submit
try {
    Triton.info(Triton.t.summary('Validating orders'));    // ← child of the mark
    Triton.startMark('pricing');                           // ← child mark
    try {
        applyPricing(orders);
    } finally {
        Triton.endMark();
    }
} finally {
    Triton.endMark();
}
```

{% endcode %}

The rules are short:

* The **outermost** mark parents to the transaction span, so a top-level mark anchors to the same tree everything else in the transaction hangs from. Depth is a fact the framework reads, not something you declare — which is why there's no boundary-specific method.
* A **nested** mark parents to the mark enclosing it.
* An **ordinary log** inside a mark becomes a leaf under the innermost mark.
* An **id you set yourself always wins.** `.spanId(...)` / `.parentSpanId(...)` are never overwritten — that's what keeps LWC → Apex traces intact, because the ids forwarded from the browser arrive already set.
* A mark **filtered out by log levels** is transparent: its children re-parent to the nearest surviving ancestor rather than pointing at a span that was never published.

{% hint style="warning" %}
**`Span_Id__c` inside a mark is no longer the request id.** It's a fresh UUID. Any query or dashboard that used `Span_Id__c == requestId` to mean "this log belongs to request X" should read **`pharos__Request_Id_External__c`** instead.
{% endhint %}

### Setting ids by hand

When you want structure without marks — say, a parent log for an operation and child logs for its sub-steps — set the ids yourself:

{% code lineNumbers="true" %}

```apex
String parent = Triton.TRANSACTION_ID;   // or any id you choose as the root

Triton.info(Triton.t
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.OpportunityManagement)
    .summary('Sync started')
    .spanId('sync-root')
    .parentSpanId(parent));

Triton.info(Triton.t
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.OpportunityManagement)
    .summary('Pushed line items')
    .spanId('sync-line-items')
    .parentSpanId('sync-root'));   // ← nested under the sync root
```

{% endcode %}

## `traceable` and `tracePoint`

Beyond parent/child structure, Triton can mark a log as an explicit **trace point** for Pharos. Two builder methods control this, and they work as a pair:

* **`.traceable(Boolean)`** — opts this builder into tracing. Passing `true` also flags the log for issue creation.
* **`.tracePoint()`** — records a trace point on the underlying Pharos log builder — but **only if `traceable` is `true`**. If tracing wasn't enabled, it's a no-op.

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.t
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.RestAPI)
    .summary('Callout dispatched')
    .traceable(true)     // enable tracing for this log
    .tracePoint());      // now this actually records a trace point
```

{% endcode %}

{% hint style="info" %}
Triton calls `tracePoint()` for you as part of preparing every buffered/immediate log, so you generally only need to set `.traceable(true)` on the logs you want traced. `tracePoint()` stays inert on everything else, which keeps tracing strictly opt-in.
{% endhint %}

## How this maps to OpenTelemetry

This mapping is what people mean when they call a Triton 2.0 org **"OpenTelemetry-ready."** If you think in [OpenTelemetry](https://opentelemetry.io/docs/concepts/signals/traces/) terms, Triton's model lines up cleanly with the tracing vocabulary — the same trace/span/parent-span shape an observability stack expects. The mapping is **conceptual** — it helps you reason about the data, and it's a foundation to build an OTel integration on — not a wire-format integration that ships today:

| OpenTelemetry concept                    | Triton equivalent                                                                                            |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| **Trace** (one end-to-end operation)     | The **transaction id** (`Triton.TRANSACTION_ID` / `this.triton.transactionId`) that correlates all the logs. |
| **Span** (a unit of work within a trace) | `Span_Id__c`, set via `.spanId(...)`.                                                                        |
| **Parent span** (the enclosing work)     | `Parent_Span_Id__c`, set via `.parentSpanId(...)`.                                                           |
| **Span nesting / trace tree**            | The span stacks — the LWC span-context stack and the Apex mark stack — plus any ids you set by hand.         |
| **Marking a span of interest**           | `.traceable(true)` + `.tracePoint()`.                                                                        |

{% hint style="warning" %}
**Readiness, not a shipped exporter.** Triton is **not** an OpenTelemetry SDK and doesn't export OTLP — there's no OTEL exporter in the package. These spans live on Pharos `Log__c` records and are visualized in Pharos. The table above is a mental model for anyone fluent in OTel — treat "trace / span / parent span" as an accurate alignment with Triton's transaction id and span fields, and as a foundation for a future OTel integration, not a drop-in pipeline that ships today.
{% endhint %}

### Getting this shape everywhere

The mapping only pays off if your logs actually carry span structure across Apex, LWC, and Flow. That's exactly what the [Instrumentation Skills](https://triton.pharos.ai/instrumentation-skills) roll out for you: the Apex skill threads one transaction id through async hops, the LWC skill's `timeBackendCall` carries span context across a backend call, and the Flow skill stitches the Flow leg into the same transaction — so the trace/span/parent-span shape is applied consistently instead of by hand.

## Do / Don't

{% hint style="success" %}
**Do**

* **Lean on the LWC defaults** — the span stack builds a sensible hierarchy without any manual `spanId` calls.
* **Use** [**performance marks**](https://triton.pharos.ai/common-apex-usage-patters/performance-marks) **in Apex** — `startMark()` / `endMark()` build the same hierarchy there, and every log inside the mark joins it automatically.
* **Use `enterStep()`** to give multi-step UIs clean, per-step subtrees.
* **Set explicit `spanId` / `parentSpanId` in Apex** only when you want a structure marks don't give you — a set value is always respected.
* **Set `.traceable(true)`** on the specific logs you want as trace points.
  {% endhint %}

{% hint style="danger" %}
**Don't**

* **Don't confuse spans with the transaction id.** The transaction id groups the whole operation; spans structure it. You need both for a useful trace.
* **Don't expect `.tracePoint()` to do anything without `.traceable(true)`** — it's intentionally inert otherwise.
* **Don't reuse the same `spanId` for unrelated units of work** — duplicate span ids blur the hierarchy.
  {% endhint %}

## Related reading

* [Transactions & Platform Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache) — the correlation id that spans hang off of.
* [End-to-End Logging](https://triton.pharos.ai/end-to-end) — spans in the context of a full LWC → Apex → Flow trace.
* [Profiling](https://triton.pharos.ai/beyond-apex/profiling) — performance helpers that create spans automatically.
* [Instrumentation Skills](https://triton.pharos.ai/instrumentation-skills) — slash commands that roll this tracing shape out across Apex, LWC, and Flow.


# Instrumentation Skills

Agent-agnostic skills that add production-grade Triton instrumentation to Apex, LWC, and Flows — one file or a whole org — with a human-reviewed diff first.

Adding good logging to an existing codebase is the least glamorous job in the world. You know what a well-instrumented class looks like — entry-point templates, resume-first transactions, `logNow` in every catch, `dmlResults` on partial DML — but hand-applying that pattern to a backlog of hundreds of Apex classes, LWCs, and Flows is a slog nobody volunteers for.

The **instrumentation skills** do that slog for you. They're a set of **portable, agent-agnostic recipes** — the Triton conventions plus a step-by-step, human-in-the-loop workflow — that any AI coding agent can follow to read a file, classify its structure, and add convention-following Triton instrumentation, then show you a diff and let you accept, tweak, or skip it before anything is written. Nothing is applied blindly.

{% hint style="info" %}
**Not tied to any one agent.** These skills are plain Markdown playbooks that target the Triton 2.0 static API. They were first shipped as Claude Code slash commands under the `/pharos:` namespace, but the logic is tool-neutral — the same recipe runs in Cursor, GitHub Copilot, Windsurf, the Codex CLI, or any agent you can point at a file. See [Running these in your agent](#running-these-in-your-agent) below.
{% endhint %}

{% hint style="warning" %}
**Companion tooling, not part of the package.** The skills ship **alongside** Triton 2.0 as developer tooling — they are not part of the Triton package you install into an org. You run them from your coding agent against your local Salesforce project; the logging code they generate targets the Triton 2.0 static API.
{% endhint %}

## The skill catalog

The three per-technology skills are the primitives. Everything else composes them.

| Skill              | What it does                                                   | Page                                                                                    |
| ------------------ | -------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `instrument-apex`  | Instruments Apex classes and triggers                          | [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex)      |
| `instrument-lwc`   | Instruments Lightning Web Components                           | [Instrument LWC](https://triton.pharos.ai/instrumentation-skills/instrument-lwc)        |
| `instrument-flows` | Instruments Flow metadata XML                                  | [Instrument Flows](https://triton.pharos.ai/instrumentation-skills/instrument-flows)    |
| `instrument-org`   | Orchestrates the three across a whole project/org              | [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org)    |
| `audit-logging`    | Read-only coverage & gap report (no writes)                    | [Audit Logging Coverage](https://triton.pharos.ai/instrumentation-skills/audit-logging) |
| `migrate-to-2.0`   | Mechanically converts 1.x singleton code to the 2.0 static API | [Migrate to 2.0](https://triton.pharos.ai/instrumentation-skills/migrate-to-2.0)        |
| `setup-standards`  | Generates CI guardrails and `Log_Level__mdt` config            | [Set Up Standards](https://triton.pharos.ai/instrumentation-skills/setup-standards)     |

For the "point at an org and instrument everywhere" experience, package the whole catalog behind one persona — see [The Triton Instrumentation Agent](https://triton.pharos.ai/instrumentation-skills/instrumentation-agent).

## Running these in your agent

Each skill is a Markdown file describing a capability. How you *invoke* it depends on your agent, but the behavior is identical.

| Agent                             | How to run a skill                                                                                                                                                                                                                                                                               |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Claude Code**                   | Copy two folders from the Triton repository into your project: `agent-skills/` (the skills) and `.claude/commands/pharos/` (the slash commands). Each command reads `agent-skills/<skill>.md` from the project root, so both must be there. Then call it, e.g. `/pharos:instrument-apex <path>`. |
| **Cursor**                        | Add the skill as a [Command](https://docs.cursor.com/) or a Rule, then invoke it from chat, or `@`-mention the skill file and give it the path.                                                                                                                                                  |
| **GitHub Copilot**                | Reference the skill file in your prompt (or add it to `.github/copilot-instructions.md`) and ask it to instrument the file.                                                                                                                                                                      |
| **Windsurf / Codex CLI / others** | Point the agent at the skill file and the target path, e.g. *"Follow `instrument-apex.md` to instrument `AccountService.cls`."*                                                                                                                                                                  |
| **Any agent**                     | Paste the skill's instructions plus the target file and ask it to apply them. The diff-review loop still applies — you approve before anything is written.                                                                                                                                       |

{% hint style="info" %}
Throughout these pages we use the `/pharos:instrument-*` slash-command form as a concise, readable stand-in for "invoke this skill." Read it as *"run the instrument-apex skill on this path"* — substitute your agent's own invocation syntax.
{% endhint %}

## The workflow — human in the loop

Every per-file skill runs the same seven-beat loop. The important part is **Step 4**: the skill never writes to your file until you've seen the diff and said yes.

1. **Step 0 — Prerequisites.** Confirm the [Salesforce CLI](https://developer.salesforce.com/tools/salesforcecli) (`sf` or `sfdx`) is installed and a default org is connected. The Flow skill additionally verifies that Triton is installed in the target org (its `TritonFlow` invocable has to exist). If a prerequisite is missing, the skill stops and tells you exactly what to run.
2. **Parse arguments.** Read the target path and flags; ask for anything required that wasn't supplied.
3. **Analyze.** Read the file and classify its structure — trigger vs. `@AuraEnabled` controller vs. batch vs. queueable, wired vs. imperative LWC, screen vs. autolaunched Flow — because the transaction and flush pattern differs per structure. This is also where the skill infers the **Area**.
4. **Apply.** Generate the instrumented version in memory, following the 2.0 static API and Triton best practices.
5. **Review the diff — `yes` / `modify` / `skip`.** The skill presents a summary plus the key changes. Say `yes` to apply, `modify` to give free-form corrections (it re-applies and asks again), or `skip` to walk away with nothing written.
6. **Write.** On `yes`, the instrumented content is written back to the **original** file — no new files, no renames.
7. **Optional deploy.** If you passed `--deploy` (or answer yes when asked), the skill runs `sf project deploy start` for just the file or component directory it touched.

{% hint style="success" %}
**Area gets special attention.** Area is the primary grouping and search key in Pharos, so the skills work hard to keep it consistent: they first look for the Area already used by *related* code — the same-object trigger, the paired Apex controller, the LWC or Flow on the other side of the call — and reuse that exact value so a whole feature's logs group together. `.area(...)` accepts a plain String, so the `TritonTypes.Area` enum values are treated as examples, not a required mapping.
{% endhint %}

## Two rules every skill enforces

* **Cacheable and `@wire` Apex never stitches through Platform Cache.** `@AuraEnabled(Cacheable=true)` methods — what `@wire` calls — can't write to Platform Cache, so `Triton.withCache()` can't carry a transaction id there and the stitch silently breaks. The skills pass `transactionId` explicitly and call `Triton.resumeTransaction(...)` on the server instead. See [LWC and Apex → With `@wire`](https://triton.pharos.ai/beyond-apex/lwc-and-apex#with-wire).
* **Per-log data scales with the level.** `ERROR`, `WARNING`, and `INFO` logs carry the most context — serialized inputs and state, plus every related record id. `DEBUG` carries named values only, and `FINE`/`FINER`/`FINEST` stay terse markers. The skills add *more* low-level tracing points, because `Log_Level__mdt` decides at runtime which ones are kept, but keep each one lean. Secrets and personal data are never logged at any level: the skills serialize a redacted copy, or leave the field out.

## Instrumentation at scale

The single-file loop is the primitive. The real payoff is running it **across a backlog** — and you no longer have to hand-loop it.

Because the skills follow shared conventions — resume-first transactions, one Area per feature, `logNow` + rethrow in catches, flush at boundaries — you get *consistent* instrumentation no matter who (or what) runs them. There are two ways to work at scale:

* **Drive the primitives yourself.** Run `instrument-apex` down a list of classes in a service layer, reusing one `--area` so the feature groups cleanly; loop an agent over a directory of LWCs or `.flow-meta.xml` files, reviewing each diff as it comes; add `--deploy` once you trust the pattern for a batch.
* **Let the orchestrator do it.** [`instrument-org`](https://triton.pharos.ai/instrumentation-skills/instrument-org) inventories your whole project, prioritizes it using the [Legacy Code Logging Rollout](https://triton.pharos.ai/triton-best-practices/legacy-migration) strategy, threads one Area per feature across Apex/LWC/Flow, and works the backlog with review checkpoints and batched deploys — then hands you a coverage report.

{% hint style="info" %}
**"Instrument everything" without giving up control.** The orchestrator is the closest thing to an "instrument the whole org" button, but it keeps the human-in-the-loop diff at its core: it batches changes and checks in at boundaries instead of writing hundreds of files blindly. You automate the tedious 90% while staying in control of every change. Start with [`audit-logging`](https://triton.pharos.ai/instrumentation-skills/audit-logging) to see the map before you drive.
{% endhint %}

## OpenTelemetry readiness

Triton 2.0's [distributed tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) — a transaction id that correlates a whole operation, plus `Span_Id__c` / `Parent_Span_Id__c` for parent-child structure — gives your logs a shape that maps cleanly onto OpenTelemetry's vocabulary: **trace**, **span**, and **parent span**. The instrumentation skills are how you get that shape *everywhere* without hand-writing it: the Apex skill threads one transaction id through async hops, the LWC skill's `timeBackendCall` carries span context across the call, and the Flow skill stitches the Flow leg into the same transaction.

{% hint style="warning" %}
**"OTEL-ready" means aligned, not exported.** Triton is not an OpenTelemetry SDK and does not emit OTLP. What 2.0 gives you is a data model whose concepts line up with OTel's, so instrumented Triton logs are a solid foundation for an observability story and a future OTel integration. See [Spans & Distributed Tracing → How this maps to OpenTelemetry](https://triton.pharos.ai/end-to-end/spans-and-tracing#how-this-maps-to-opentelemetry) for the full mapping.
{% endhint %}

## Where to go next

* [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex) — classes and triggers, transaction resume/stitching, DML and callout logging.
* [Instrument LWC](https://triton.pharos.ai/instrumentation-skills/instrument-lwc) — `c/triton`, `bindToComponent`, `timeBackendCall`, transaction stitching to Apex.
* [Instrument Flows](https://triton.pharos.ai/instrumentation-skills/instrument-flows) — the `TritonFlow` "Log" action, fault-path logging, the never-pass-a-collection rule.
* [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org) — the orchestrator that rolls the three out across a whole project.
* [Audit Logging Coverage](https://triton.pharos.ai/instrumentation-skills/audit-logging) — see where the gaps are before you start.
* [Migrate to 2.0](https://triton.pharos.ai/instrumentation-skills/migrate-to-2.0) · [Set Up Standards](https://triton.pharos.ai/instrumentation-skills/setup-standards) — convert 1.x code and lock in CI guardrails.
* [The Triton Instrumentation Agent](https://triton.pharos.ai/instrumentation-skills/instrumentation-agent) — package the whole catalog as one reusable, agent-agnostic persona.
* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) — the tracing model these skills roll out, and the OpenTelemetry mapping.


# Instrument Apex

The instrument-apex skill adds Triton logging to an Apex class or trigger — transactions, catch blocks, DML and callout payloads — then optionally deploys it.

The **instrument-apex** skill reads an Apex class or trigger, works out what *kind* of code it is, and adds Triton 2.0 instrumentation that follows the same patterns you'd write by hand — the entry-point template, resume-first transactions, `logNow` in every catch, `dmlResults` on partial DML, callout payloads, and flush at the right boundaries. Then it shows you the diff and, if you want, deploys.

{% hint style="info" %}
**Invocation is agent-specific.** In agents that support slash commands (Claude Code, Cursor) you invoke it as `/pharos:instrument-apex <path>`; in others you point the agent at this skill and give it the path. See [Running these in your agent](https://triton.pharos.ai/instrumentation-skills#running-these-in-your-agent). The `/pharos:` form below is a readable stand-in for "run this skill."
{% endhint %}

## Usage

{% code lineNumbers="true" %}

```bash
/pharos:instrument-apex <path> [--area <Area>] [--type <Type>] [--deploy]
```

{% endcode %}

| Argument   | Required | Meaning                                                                                                                                                                      |
| ---------- | :------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<path>`   |     ✅    | The `.cls` or `.trigger` file to instrument. If omitted, the skill asks.                                                                                                     |
| `--area`   |          | The business/functional Area for these logs. If omitted, the skill **infers** it from the code and matches related code. Accepts any String — enum values are just examples. |
| `--type`   |          | Technical classification. Defaults to `Backend`; inferred per method (e.g. `BackendCall` for callouts). Accepts any String.                                                  |
| `--deploy` |          | Deploy the file after you accept the diff. Without it, the skill asks at the end.                                                                                            |

{% hint style="info" %}
Logs are created by passing a fluent `TritonBuilder` to `Triton.log(...)` (buffered) or `Triton.logNow(...)` (immediate). Builders come from `Triton.t` — the template-derived builder that auto-stamps the current transaction id — or from `Triton.makeBuilder()` for a fresh one.
{% endhint %}

## What it instruments

The skill classifies the file's **structure** first, because the transaction and flush pattern depends on it — a trigger handler, an `@AuraEnabled` controller, a batch, a queueable, an `@future`, and a plain service class each get treated differently. Test classes (`@isTest`) are left alone entirely.

From there it applies:

* **Entry-point template.** At the start of the entry-point method (never a shared `static {}` block — the template is a shared static and the last writer wins), it sets the template with the Category, Type, and Area, then creates each log from `Triton.t`.
* **Resume-first transactions.** It always resumes an existing transaction before starting a new one, per the structure (see below).
* **Try/catch logging.** Every catch gets a `Triton.logNow(...)` with `.exception(e)` before the original `throw` — the flow is preserved, only logging is added.
* **DML result logging.** After partial-success DML (`allOrNone = false`), it adds `.dmlResults(results)`. A failure becomes a `DMLResult` log at ERROR with an issue; when every row succeeded, nothing is emitted, so the skill never wraps it in an `if`.
* **Callout / integration logging.** HTTP calls get `.integrationPayload(req, res)` and `Type.BackendCall` — the category stays the default `Apex`.
* **`System.debug` → Triton.** Every `System.debug(...)` in non-test code becomes a buffered `Triton.debug(...)`. (Debug lines are safe in production — verbosity is governed by Log Level metadata.)
* **Performance marks, where a span earns its place.** For a stretch of work that should show up as a span rather than as one timed log, the skill wraps it in `Triton.startMark()` / `Triton.endMark()` (closed in a `finally`), using `Triton.startTriggerMark()` in trigger handlers. Everything logged inside nests under the mark, and names are derived from the stack trace, so no strings are hand-typed. Marks are not added to every entry point; a one-off duration on a single log is still timed by hand. See [Performance Marks in Apex](https://triton.pharos.ai/common-apex-usage-patters/performance-marks).
* **Flush at boundaries.** `Triton.flush()` is added at the end of triggers, each batch `execute` chunk and `finish`, `Queueable`/`Schedulable` `execute`, `@future`, `@AuraEnabled`, and REST/invocable methods — **never** inside a loop.
* **Related objects.** Record ids flowing through a method are attached with `.relatedObject(id)` / `.relatedObjects(ids)`, prioritized on error and DML logs.

{% hint style="success" %}
**Auto-enrichment — don't add it by hand.** `Triton.log()` captures the stack trace, operation name, governor **limit info**, and (for Apex-category logs) the execution context automatically at log time. The skill deliberately does *not* add these manually, and neither should you.
{% endhint %}

### Template initialization

The entry-point method opens with the template:

{% code lineNumbers="true" %}

```apex
Triton.setTemplate(
    Triton.makeBuilder()                       // makeBuilder() defaults Category = Apex
        .type(TritonTypes.Type.Backend)
        .area(TritonTypes.Area.OpportunityManagement)
);

// then, per log:
Triton.info(Triton.t.summary('Fetching opportunities'));
```

{% endcode %}

### Transaction management (resume-first, per structure)

The goal is **one correlated transaction** across the whole call chain, so the skill always resumes first.

**Synchronous entry points** (`@AuraEnabled`, REST, `@InvocableMethod`) resume a caller-supplied id if there is one:

{% code lineNumbers="true" %}

```apex
if (String.isNotBlank(transactionId)) {
    Triton.resumeTransaction(transactionId);
} else {
    Triton.startTransaction();
}
```

{% endcode %}

{% hint style="info" %}
**The sanctioned signature exception.** Adding an optional `transactionId` parameter to an *entry-point* method — so it can stitch into an instrumented LWC's transaction — is the one time the skill will change a method signature. It's flagged explicitly in the diff. Everywhere else, signatures, access modifiers, and return types are left untouched. If you'd rather not touch the signature at all, the skill can use `Triton.withCache()` at entry instead, which carries the id via platform cache with zero param changes. Pick one mechanism per call chain and keep the LWC side consistent (the LWC skill passes a param named `transactionId`).
{% endhint %}

Other structures each get their own handling:

* **Trigger handlers** guard the start (`if (Triton.TRANSACTION_ID == null) Triton.startTransaction();`) so before/after and recursion don't reset the id, and log affected ids with `.relatedObjects(...)`, built null-safely — see [Trigger handlers](#trigger-handlers-logging-never-fails-the-write) below.
* **Batchable** classes implement `Database.Stateful` and take the caller's id in the constructor, but only *store* it there: the constructor runs in the caller's transaction, so `startTransaction()` there would overwrite the caller's id. `start` resumes that id (or starts one if there's none), `resumeTransaction(this.txId)` re-establishes it at the top of each `execute` and in `finish`, and the class **flushes per `execute` chunk** and in `finish` (each chunk is its own transaction).
* **Queueable / Schedulable** take a `String txId` constructor arg, resume it at the top of `execute`, and flush before returning.
* **@future** takes a `String transactionId` param (only primitives cross the boundary), resumes it, and flushes before returning.
* **Async dispatch sites** thread the current id through the hop:

{% code lineNumbers="true" %}

```apex
System.enqueueJob(new MyQueueable(payload, Triton.TRANSACTION_ID));
// or: myFutureMethod(recordId, Triton.TRANSACTION_ID);
```

{% endcode %}

* **Private / service methods** never start, resume, or stop a transaction — they use the ambient one set by the entry point. `Triton.stopTransaction()` is only ever called at a true end-of-chain boundary (batch `finish`, top-level entry-point completion).

### Try/catch — log and rethrow

`.exception(e)` sets the type, ERROR level, summary, stack trace, details, and flags issue creation — so no redundant `.level(...)`. Downgrading it — `Triton.warning(Triton.t.exception(e))` — keeps the exception detail but withdraws the issue; an explicit `.createIssue()` keeps it. A custom summary must chain **after** `.exception(e)`, or it gets overwritten:

{% code lineNumbers="true" %}

```apex
} catch (Exception e) {
    Triton.logNow(
        Triton.t
            .exception(e)
            .summary('AccountService.recalculate failed')  // optional; MUST follow .exception()
    );
    throw e;   // original throw behavior preserved
}
```

{% endcode %}

### DML result logging

{% code lineNumbers="true" %}

```apex
List<Database.SaveResult> results = Database.insert(records, false);
Triton.log(
    Triton.makeBuilder()
        .area(TritonTypes.Area.Accounts)   // Area set on the builder (or via template)
        .dmlResults(results)               // nothing is emitted when every row succeeded
);
```

{% endcode %}

### Callout / integration logging

{% code lineNumbers="true" %}

```apex
HttpResponse res;
try {
    res = new Http().send(req);
    if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
        Triton.logNow(
            Triton.makeBuilder()
                .type(TritonTypes.Type.BackendCall)
                .area(TritonTypes.Area.RestAPI)
                .summary('Callout failed: ' + res.getStatus())
                .details('statusCode=' + res.getStatusCode())
                .integrationPayload(req, res)
                .error()
        );
    }
} catch (Exception e) {
    Triton.logNow(
        Triton.makeBuilder()
            .area(TritonTypes.Area.RestAPI)
            .exception(e)
            .integrationPayload(req, res)
    );
}
```

{% endcode %}

### Trigger handlers: logging never fails the write

A trigger runs inside someone else's DML. On a managed-package object — or any object a system or integration user writes to — a throw from your handler rolls back a write you don't own and may not be able to test as. Logging must never be the reason that happens.

**What Triton guarantees.** `Triton.log` and the level methods, `logNow`, `flush`, `flushTop`, the Flow **Log** action, and the LWC endpoint catch their own failures. If Pharos refuses a publish, those logs are dropped and the failure is written to the Apex debug log at `ERROR`; the business write goes ahead.

**What the skill still takes care of in your code:**

* **Null-safe builder arguments.** The builder expression runs in your code before Triton is called, so Triton can't catch what throws there — `Trigger.newMap.keySet()` in before insert, `record.Parent__r.Name` on an unqueried relationship, `e.getCause().getMessage()` when there's no cause. Record ids are built like this:

{% code lineNumbers="true" %}

```apex
Set<Id> recordIds = Trigger.newMap != null ? Trigger.newMap.keySet()
                  : Trigger.oldMap != null ? Trigger.oldMap.keySet()
                  : new Set<Id>();
Triton.info(Triton.t.summary('AccountTriggerHandler ' + Trigger.operationType).relatedObjects(recordIds));
```

{% endcode %}

* **Governor limits.** `System.LimitException` can't be caught by anyone. In a 200-record trigger the skill buffers with `Triton.log(...)` — never `logNow` in a loop — flushes once at the end of the handler, and keeps per-record details lean.
* **No new `try/catch` around business logic.** Where a catch already exists, it logs and keeps the existing throw or return.
* **One publish on managed-package objects.** `Triton.log(...)` plus a single `Triton.flush()` as the handler's last statement, rather than `logNow`. The [audit](https://triton.pharos.ai/instrumentation-skills/audit-logging) flags `logNow` and `flush` on these paths for review.

**The test it adds.** The skill adds a test that performs the triggering DML as a low-privilege user and asserts the write landed:

{% code lineNumbers="true" %}

```apex
@IsTest
private static void test_accountTrigger_write_survives_a_restricted_user() {
    User restricted = new User(
        ProfileId = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1].Id,
        Alias = 'trtnrst', Email = 'restricted@example.com',
        Username = 'restricted.' + System.currentTimeMillis() + '@example.com',
        LastName = 'Restricted', TimeZoneSidKey = 'GMT', LocaleSidKey = 'en_US',
        EmailEncodingKey = 'UTF-8', LanguageLocaleKey = 'en_US');
    insert restricted;
    // Assign only the permission sets the object needs.

    System.runAs(restricted) {
        Test.startTest();
        insert new Account(Name = 'Acme');
        Test.stopTest();
    }
    System.assertEquals(1, [SELECT COUNT() FROM Account], 'The instrumented trigger must not fail the write');
}
```

{% endcode %}

Know what this doesn't prove. `System.runAs` enforces record sharing only, not object or field permissions, and a user you can create in a test can't reproduce a hidden platform integration user. A passing test shows the handler survives a restricted human user; Triton's never-throw guarantee is what covers the rest. To prove your code survives a refused publish, see [`TritonTestFactory.failPublishing()`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritontestfactory#failpublishing).

## Review the diff

Before writing anything, the skill presents a summary — the structure it classified, the template it set, how it handled transactions, and counts of try/catch, DML, callout, `System.debug`, and flush changes (plus any sanctioned signature change) — followed by the key changes. You answer:

* **`yes`** — apply and write the file.
* **`modify`** — give free-form corrections; the skill re-applies and asks again.
* **`skip`** — stop without writing.

## Deploy

The instrumented content is written back to the **original** file (never a new one). Then, with `--deploy` or on confirmation:

{% code lineNumbers="true" %}

```bash
sf project deploy start --source-dir <path-to-file> --json
# or, if only sfdx is available:
sfdx force:source:deploy -p <path-to-file> --json
```

{% endcode %}

A `"status": "Succeeded"` reports the deployed component; failures show the component-failures table and stop without reverting your file.

## Where to go next

* [Instrument LWC](https://triton.pharos.ai/instrumentation-skills/instrument-lwc) — the front-end half of a stitched transaction.
* [Instrument Flows](https://triton.pharos.ai/instrumentation-skills/instrument-flows) — the Flow leg of the same trace.
* [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org) — run this skill across every class and trigger at once.
* [Logging in Apex](https://triton.pharos.ai/common-apex-usage-patters) · [Transaction Management](https://triton.pharos.ai/triton-best-practices/transaction-management) — the hand-written patterns the skill automates.
* [Performance Marks in Apex](https://triton.pharos.ai/common-apex-usage-patters/performance-marks) — the mark API the skill wraps entry points in.
* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) — how these correlated transactions map to OpenTelemetry.


# Instrument LWC

The instrument-lwc skill adds Triton logging to a Lightning Web Component — timed backend calls with span context and transaction stitching to Apex.

The **instrument-lwc** skill reads a Lightning Web Component, adds the `c/triton` logger, and instruments its imperative Apex calls, `@wire` adapters, event handlers, and error paths — preferring `timeBackendCall` so backend calls are timed and carry span context automatically. Then it shows you the diff and, if you want, deploys the whole component directory.

{% hint style="info" %}
**Invocation is agent-specific.** In agents that support slash commands (Claude Code, Cursor) you invoke it as `/pharos:instrument-lwc <path>`; in others you point the agent at this skill and give it the path. See [Running these in your agent](https://triton.pharos.ai/instrumentation-skills#running-these-in-your-agent).
{% endhint %}

## Usage

{% code lineNumbers="true" %}

```bash
/pharos:instrument-lwc <path> [--area <Area>] [--type <Type>] [--perf essential|standard|deep] [--deploy]
```

{% endcode %}

| Argument   | Required | Meaning                                                                                                                                                                                                                                                                                                                                                                      |
| ---------- | :------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<path>`   |     ✅    | The component **directory** (e.g. `force-app/main/default/lwc/myComponent/`) or the `.js` file directly. If a directory is given, the skill finds `<componentName>.js`.                                                                                                                                                                                                      |
| `--area`   |          | The feature's area. Inferred from the code and matched to the paired Apex controller if omitted. Any string works, exactly as in Apex and Flow, so the skill reuses the Apex area verbatim (`.area('OrderEntry')`). The `AREA` constants (`ACCOUNTS`, `COMMUNITY`, `LEAD_CONVERSION`, `OPPORTUNITY_MANAGEMENT`, `REST_API`) land as the Apex names (`Accounts` … `RestAPI`). |
| `--type`   |          | A `TYPE` constant: `BACKEND`, `FRONTEND`, `BACKEND_CALL`, `COMPONENT_LIFECYCLE`, `COMPONENT_RENDER`, `USER_INTERACTION`, `PERFORMANCE`. Defaults to `FRONTEND`.                                                                                                                                                                                                              |
| `--perf`   |          | How much profiling to add: `essential` (default), `standard`, or `deep`. See [Performance tiers](#performance-tiers).                                                                                                                                                                                                                                                        |
| `--deploy` |          | Deploy the component directory after you accept the diff.                                                                                                                                                                                                                                                                                                                    |

{% hint style="info" %}
The import is `import Triton, { TYPE, AREA, LEVEL } from 'c/triton';`. `new Triton()` returns a **module-scoped singleton** that already starts/resumes a transaction (from `sessionStorage`) on construction — so a transaction is always active, and every log builder is auto-stamped with the current `transactionId`. That's why LWC-originated logs correlate automatically.
{% endhint %}

## What it instruments

The skill reads the `.js` file (and the `.html` template for context), then identifies the existing Triton import, lifecycle hooks, `@wire` adapters, imperative Apex calls, `handle*` event handlers, and existing error handling.

### The import and the bound instance

It adds the import, then a class-level `triton` property bound once — **`constructor` is preferred** because it covers `@wire` (which fires early); `connectedCallback` is acceptable for purely imperative components. It **always** calls `bindToComponent`.

{% code lineNumbers="true" %}

```javascript
import Triton, { TYPE, AREA, LEVEL } from 'c/triton';

// ...

triton;

constructor() {
    super();
    this.triton = new Triton().bindToComponent('myComponent');
    this.triton.setTemplate(
        this.triton.makeBuilder()
            .type(TYPE.FRONTEND)
            .area(AREA.ACCOUNTS)   // the paired Apex controller's area: an AREA constant or the same string; omit if none
    );
}
```

{% endcode %}

{% hint style="warning" %}
`new Triton()` returns the shared singleton and binds it to this component — it does **not** create an isolated instance, and it **already** starts/resumes a transaction, so the skill never calls `startTransaction()` in the constructor. Logs are created with `this.triton.fromTemplate()`, which clones the template and stamps the current `transactionId`.
{% endhint %}

Where the paired Apex code uses an area that isn't one of the `AREA` constants, the skill passes that string as-is (`.area('OrderEntry')`), and the server keeps it. Only when the feature has no area at all does it omit `.area(...)`; those logs record under `LWC`.

### Instrumenting imperative Apex calls — `timeBackendCall` preferred

`timeBackendCall` auto-logs start / success / failure with duration **and span context**, so the backend call and everything it does nest cleanly under one span. Only the rethrow needs handling:

{% code lineNumbers="true" %}

```javascript
async handleSave() {
    try {
        const result = await this.triton.timeBackendCall('saveRecord', () =>
            saveRecord({
                recordId: this.recordId,
                transactionId: this.triton.transactionId   // Option A stitching; omit if using withCache
            })
        ).execute();
        // ...use result
    } catch (error) {
        // timeBackendCall already logged the failure; handle UI state here
    }
}
```

{% endcode %}

Use `.withoutRethrow()` to swallow, or `.withCustomErrorHandler(fn)` for custom handling. When not using `timeBackendCall`, the skill falls back to a manual `try/catch` with `this.triton.log(...)` on success and `this.triton.logNow(this.triton.exception(error))` on failure. `.exception(error)` — on `this.triton` or on any builder — sets `ERROR`, so the server opens an issue, exactly like Apex's `.exception(e)`. `logNow` and `flush` never reject: if the server can't take the logs they're kept for the next flushes and dropped after three failures in a row, so awaiting them can't derail your catch block.

### Transaction stitching to Apex

LWC logs are already correlated. To extend the **same** transaction into your Apex controller, the skill uses **one** of two mechanisms — and never invents an Apex parameter:

* **Option A — pass the id** *only when the Apex method declares it.* The Apex side (see [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex)) resumes a param named `transactionId`. Passing a key the Apex signature doesn't declare fails at runtime.
* **Option B — platform cache.** Leave the Apex call unchanged and have the Apex method call `Triton.withCache()`; the id rides platform cache with no param threading.

It never starts or stops a transaction inside a handler — that would split a component's logs across transactions and `stopTransaction()` clears the shared id. For a genuine multi-step wizard, it uses `this.triton.enterStep()` to segment logical steps within the one transaction.

### Wires, handlers, milestones, and errors

* **`@wire` adapters** — errors are logged from the callback with `this.triton.logNow(...)`.
* **Event handlers** (`handle*`) — get DEBUG-level entry logging (`this.triton.debug(TYPE.FRONTEND, AREA.X)`), reserving INFO for business milestones.
* **Business milestones** (save, submit, approve) — get INFO logging at completion with `.relatedObjects([this.recordId])`.
* **Error handlers** — every existing `catch` uses `logNow` (immediate) so the error persists before UI state changes; `log` is reserved for buffered debug/info.
* **`disconnectedCallback` flush** — optional belt-and-suspenders; flushing is already automatic.

### Performance tiers

`--perf` sets how much profiling the skill adds. Each tier includes the ones before it:

| `--perf`              | Adds                                                                                                                        | Records log at                              |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| `essential` (default) | `timeBackendCall` around imperative Apex calls, `timeUserInteraction` around `handle*` handlers                             | `FINE`; a failure at `ERROR`, with an issue |
| `standard`            | `trackComponentLifecycle` in `connectedCallback` / `disconnectedCallback`, and custom marks around notable client-side work | lifecycle at `FINER`, marks at `FINE`       |
| `deep`                | `trackComponentRender` in `renderedCallback`                                                                                | `FINEST`                                    |

Profiling records inherit the Area from the component's template, so the skill sets the template first. Because each tier maps to a level, one `Log_Level__mdt` threshold picks the tier you keep: a production LWC rule at `INFO` or stricter drops everything but failures, `FINE` keeps the essential tier, and render tracking should run at `FINEST` only mid-investigation. When it adds render tracking, the skill says so in the diff.

## Review the diff

The skill presents a summary — the bind and template, the stitching mechanism, and counts of instrumented Apex calls, error handlers, and event handlers — then the key changes. Answer **`yes`** to apply, **`modify`** for corrections, or **`skip`** to write nothing.

## Deploy

The `.js` content is written back to the original file. Because an LWC's HTML and metadata must deploy together, deploy targets the **entire component directory**:

{% code lineNumbers="true" %}

```bash
sf project deploy start --source-dir <component-directory> --json
# or:
sfdx force:source:deploy -p <component-directory> --json
```

{% endcode %}

A `"status": "Succeeded"` confirms the component deployed; failures show the failures table without reverting your file.

## Where to go next

* [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex) — the controller that resumes the id this component passes.
* [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org) — run this skill across every component at once.
* [Logging in LWC](https://triton.pharos.ai/beyond-apex/lwc) · [LWC and Apex](https://triton.pharos.ai/beyond-apex/lwc-and-apex) — the hand-written patterns the skill automates.
* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) — how `timeBackendCall`'s span context maps to OpenTelemetry spans.


# Instrument Flows

The instrument-flows skill inserts Triton Log actions into a Flow's metadata XML at entry, fault paths, and record operations, then optionally deploys it.

The **instrument-flows** skill reads a Flow's metadata XML, parses its elements, and inserts Triton **Log** actions at the moments that matter — flow entry, every fault connector, negative decision branches, record operations, and subflow boundaries — using the `TritonFlow` invocable. Then it shows you the diff and, if you want, deploys.

{% hint style="info" %}
**Invocation is agent-specific.** In agents that support slash commands (Claude Code, Cursor) you invoke it as `/pharos:instrument-flows <path>`; in others you point the agent at this skill and give it the path. See [Running these in your agent](https://triton.pharos.ai/instrumentation-skills#running-these-in-your-agent).
{% endhint %}

## Usage

{% code lineNumbers="true" %}

```bash
/pharos:instrument-flows <path> [--area <Area>] [--level <Level>] [--deploy]
```

{% endcode %}

| Argument   | Required | Meaning                                                                                                                                              |
| ---------- | :------: | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<path>`   |     ✅    | The `.flow-meta.xml` file to instrument. If omitted, the skill asks.                                                                                 |
| `--area`   |          | The business/functional Area (a free String, required on every log action). Inferred from the flow's purpose and matched to related code if omitted. |
| `--level`  |          | Default level for informational checkpoints. Defaults to `INFO`. Fault paths always use `ERROR`.                                                     |
| `--deploy` |          | Deploy the flow after you accept the diff.                                                                                                           |

{% hint style="warning" %}
**Extra prerequisite: Triton must be in the target org.** On top of the shared Salesforce-CLI-and-default-org check, this skill verifies that the `TritonFlow` invocable actually exists in the connected org (it runs a tiny anonymous-Apex probe). If Triton isn't installed there, the skill stops and tells you to deploy the Triton package first — otherwise the Log actions wouldn't save or deploy.
{% endhint %}

## How Flow logging works — individual named inputs

Flow logging calls the `TritonFlow` invocable — an Apex action labeled **Log**, under the **TritonLogging** category. The crucial detail: the log record is built **in Apex**, and the Flow supplies **individual named String inputs**. Each field is its own `<inputParameters>` element.

{% hint style="danger" %}
**Never pass a collection or an SObject — this is a hard constraint.** There is no `flowLogs` collection input and no `pharos__Log__c` / SObject input; those parameters don't exist, and a Flow that references them won't save or deploy. Every log point is a single `<actionCalls>` with individual primitive inputs.
{% endhint %}

### Required inputs on every log action

| Input           | Required | Notes                                                               |
| --------------- | :------: | ------------------------------------------------------------------- |
| `area`          |     ✅    | Area string (free-form; matched to related code).                   |
| `summary`       |     ✅    | The log's one-line headline.                                        |
| `interviewGUID` |     ✅    | Always `{!$Flow.InterviewGuid}` — **exact casing `interviewGUID`**. |

Optional inputs the skill sets where relevant: `category` (recommend `Flow`; invalid values fall back to `Flow`), `type` (from `<processType>`, e.g. `Screen Flow`), `level`, `details`, `operation`, `flowApiName` (the plain API name — no version suffix), `flowVersion`, `transactionId`, `additionalFields` (a JSON string), and `stacktrace` / `fullStacktrace` for chaining.

{% hint style="info" %}
**Split the name and the version.** `flowApiName` takes the **plain** API name; the version number goes in `flowVersion`. Component-scoped `Log_Level__mdt` rules match the Flow API Name in full, so `My_Flow-4` won't match a rule naming `My_Flow`. See [Logging in Flow](https://triton.pharos.ai/flows#flow-api-name-and-flow-version).
{% endhint %}

{% hint style="info" %}
**Chaining stack traces.** The `fullStacktrace` **output** is populated; the `stacktrace` output is **always null — don't rely on it.** To carry context forward, assign `fullStacktrace` to a variable and pass it as the `fullStacktrace` **input** of a later action.
{% endhint %}

### The canonical log action

{% code lineNumbers="true" %}

```xml
<actionCalls>
    <name>Triton_Log_FlowStart</name>
    <label>Triton Log — Flow Start</label>
    <locationX>50</locationX>
    <locationY>120</locationY>
    <actionName>TritonFlow</actionName>
    <actionType>apex</actionType>
    <connector>
        <targetReference>Next_Element</targetReference>
    </connector>
    <inputParameters>
        <name>area</name>
        <value><stringValue>PartnerIntake</stringValue></value>
    </inputParameters>
    <inputParameters>
        <name>summary</name>
        <value><stringValue>Flow started: Partner_Intake</stringValue></value>
    </inputParameters>
    <inputParameters>
        <name>interviewGUID</name>
        <value><elementReference>$Flow.InterviewGuid</elementReference></value>
    </inputParameters>
    <inputParameters>
        <name>category</name>
        <value><stringValue>Flow</stringValue></value>
    </inputParameters>
    <inputParameters>
        <name>level</name>
        <value><stringValue>INFO</stringValue></value>
    </inputParameters>
</actionCalls>
```

{% endcode %}

## What it instruments

After parsing the flow's `<processType>`, elements, fault connectors, start node, and any existing `TritonFlow` actions (already-instrumented elements are skipped), the skill adds:

* **Flow entry** — an INFO log after the start connector's first target: `Flow started: <FlowApiName>`.
* **Fault paths (most critical)** — for **every** element with a `<faultConnector>`, an `ERROR` log as the first element on the fault path, with `details` = `{!$Flow.FaultMessage}`. This is how Pharos surfaces unhandled Flow errors, and an `ERROR` level auto-creates an issue — so fault instrumentation is non-negotiable.
* **Negative decision branches** — a `WARNING` log on `<decisions>` outcomes representing error states or empty results (happy paths stay at `DEBUG` to keep noise down).
* **Record operations** — a `DEBUG` log after `<recordCreates>` / `<recordUpdates>` / `<recordDeletes>` success paths.
* **Subflow boundaries** — an INFO log before each `<subflows>` element.

The skill never removes existing elements or connectors — it only inserts new `<actionCalls>` — and it never adds logs inside `<loops>` (log before/after the loop, not per iteration).

### Fault-path logging

{% code lineNumbers="true" %}

```xml
<actionCalls>
    <name>Triton_Log_Create_Lead_Fault</name>
    <label>Triton Log — Create Lead fault</label>
    <locationX>350</locationX>
    <locationY>480</locationY>
    <actionName>TritonFlow</actionName>
    <actionType>apex</actionType>
    <inputParameters>
        <name>area</name>
        <value><stringValue>PartnerIntake</stringValue></value>
    </inputParameters>
    <inputParameters>
        <name>summary</name>
        <value><stringValue>Create_Lead fault</stringValue></value>
    </inputParameters>
    <inputParameters>
        <name>interviewGUID</name>
        <value><elementReference>$Flow.InterviewGuid</elementReference></value>
    </inputParameters>
    <inputParameters>
        <name>details</name>
        <value><elementReference>$Flow.FaultMessage</elementReference></value>
    </inputParameters>
    <inputParameters>
        <name>level</name>
        <value><stringValue>ERROR</stringValue></value>
    </inputParameters>
</actionCalls>
```

{% endcode %}

### Transaction stitching

To tie the Flow into an existing LWC/Apex transaction, the skill passes the id as the `transactionId` input on **every** log action. If the flow already has a transaction-id input variable, it references it; otherwise, when the flow is invoked from Apex/LWC, it adds an input variable and passes it:

{% code lineNumbers="true" %}

```xml
<variables>
    <name>TritonTransactionId</name>
    <dataType>String</dataType>
    <isCollection>false</isCollection>
    <isInput>true</isInput>
    <isOutput>false</isOutput>
</variables>
```

{% endcode %}

If no id is supplied, `TritonFlow` starts/uses one automatically and correlates via the Interview GUID — so `transactionId` is optional.

## Review the diff

The skill summarizes what it added — flow entry, fault paths, decision branches, record operations, subflow calls, the `category`/`type` it set, and the transaction-id approach — plus the key XML. Answer **`yes`** to apply, **`modify`** for corrections, or **`skip`** to write nothing. On write, the modified XML goes back to the original `.flow-meta.xml`, preserving existing indentation and structure.

## Deploy

{% code lineNumbers="true" %}

```bash
sf project deploy start --source-dir <path-to-flow-xml> --json
# or:
sfdx force:source:deploy -p <path-to-flow-xml> --json
```

{% endcode %}

{% hint style="warning" %}
**Draft-version activation reminder.** Deploying a Flow creates a **new version in Draft state** — it isn't live yet. After a successful deploy, activate it: **Setup → Flows → `<FlowApiName>` → Activate.**
{% endhint %}

## Where to go next

* [Logging in Flow](https://triton.pharos.ai/flows) — the no-code walkthrough of the same Log action.
* [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex) · [Instrument LWC](https://triton.pharos.ai/instrumentation-skills/instrument-lwc) — the other legs of a stitched, cross-technology trace.
* [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org) — run this skill across every flow at once.
* [End-to-End Logging](https://triton.pharos.ai/end-to-end) — how the Flow leg folds into one transaction with LWC and Apex.


# Instrument the Org

The instrument-org skill runs the Apex, LWC, and Flow skills across a Salesforce project — inventory, prioritize, instrument, deploy — in reviewed batches.

The **instrument-org** skill is the "instrument everything" entry point. Point it at a project (or a subtree of it) and it inventories every Apex class, trigger, LWC, and Flow, prioritizes the backlog the way the [Legacy Code Logging Rollout](https://triton.pharos.ai/triton-best-practices/legacy-migration) strategy recommends, and then drives [`instrument-apex`](https://triton.pharos.ai/instrumentation-skills/instrument-apex), [`instrument-lwc`](https://triton.pharos.ai/instrumentation-skills/instrument-lwc), and [`instrument-flows`](https://triton.pharos.ai/instrumentation-skills/instrument-flows) across it — feature by feature, with one Area per feature and a review checkpoint at every batch boundary. When it's done, it hands you a coverage report.

It is not a new instrumentation engine — it's an **orchestrator** over the three primitives. Every file it touches is instrumented by exactly the same skill, following exactly the same conventions, that you'd run by hand.

{% hint style="info" %}
**Invocation is agent-specific.** In agents that support slash commands (Claude Code, Cursor) you invoke it as `/pharos:instrument-org <path>`; in others you point the agent at this skill and a directory. See [Running these in your agent](https://triton.pharos.ai/instrumentation-skills#running-these-in-your-agent). For a hands-off, "point at an org" experience, run it through [The Triton Instrumentation Agent](https://triton.pharos.ai/instrumentation-skills/instrumentation-agent).
{% endhint %}

{% hint style="warning" %}
**Run** [**`audit-logging`**](https://triton.pharos.ai/instrumentation-skills/audit-logging) **first.** The audit is read-only and gives you the map — how much code exists, where the gaps are, and a suggested order — before `instrument-org` starts writing. `instrument-org` can run the audit itself as Step 1, but seeing it on its own first is the safer habit on a large org.
{% endhint %}

## Usage

{% code lineNumbers="true" %}

```bash
/pharos:instrument-org [<path>] [--area-map <file>] [--phase <n>] [--tech apex,lwc,flow] [--batch-size <n>] [--deploy] [--dry-run]
```

{% endcode %}

| Argument       | Required | Meaning                                                                                                                                     |
| -------------- | :------: | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `<path>`       |          | Project root or a subtree (e.g. `force-app/main/default/`). Defaults to the detected project root.                                          |
| `--area-map`   |          | A file (or inline list) mapping folders/features to Area strings, so the skill doesn't have to infer every Area. Inference is the fallback. |
| `--phase`      |          | Run only one rollout phase (see [The rollout phases](#the-rollout-phases)). Omit to run phases in order with checkpoints between them.      |
| `--tech`       |          | Restrict to some technologies, e.g. `--tech apex,flow`. Defaults to all three.                                                              |
| `--batch-size` |          | How many files to instrument before pausing for a batch review. Defaults to a feature or folder boundary.                                   |
| `--deploy`     |          | Deploy each batch after you accept it. Without it, the skill asks per batch.                                                                |
| `--dry-run`    |          | Inventory and plan only — produce the report and the proposed order, write nothing.                                                         |

## How it works

### Step 1 — Inventory

The skill walks the project and catalogs everything instrumentable:

* Apex classes and triggers (skipping `@isTest` classes).
* LWCs (component directories under `lwc/`).
* Flows (`.flow-meta.xml`), noting `<processType>`.

For each item it records the current instrumentation state — already-instrumented, partially instrumented, or untouched — so a re-run only fills gaps and never double-instruments. This is the same signal [`audit-logging`](https://triton.pharos.ai/instrumentation-skills/audit-logging) produces.

### Step 2 — Group into features

Raw files aren't the unit of work; **features** are. The skill clusters related code so a whole feature's logs share one Area and one correlated transaction:

* A trigger, its handler class, and the service classes it calls.
* An LWC and the Apex controller it calls (and any Flow that controller invokes).
* A screen Flow and the subflows/record operations beneath it.

It resolves the Area for each cluster **once** — from your `--area-map`, from an Area already used by related code, or by inference — and reuses it across every file in the cluster. This is what keeps a feature's logs grouping cleanly in Pharos.

### Step 3 — Prioritize (the rollout phases)

The backlog is ordered by value and risk, not alphabetically — mirroring the [Legacy Code Logging Rollout](https://triton.pharos.ai/triton-best-practices/legacy-migration) phasing:

1. **Edge entry points.** Public `@AuraEnabled` controllers, REST endpoints, Queueables, Batch `start`/`finish`, global callouts, and the LWCs/Flows that call them. Highest visibility, well-understood boundaries — and where cross-boundary transaction correlation gets established.
2. **High-value internals.** Trigger handlers and core service classes.
3. **Broad sweep.** Low-risk utilities and everything remaining; retire the last `System.debug`.

The skill also respects the **comfort tiers** from the rollout guide: it flags business-critical, low-comfort code (old, untested, no author) and proposes *minimal* instrumentation there — or defers it for a human — rather than aggressively rewriting code nobody understands.

### Step 4 — Instrument, batch by batch

For each batch (a feature, a folder, or `--batch-size` files), the skill runs the matching per-technology skill on every file, threading the cluster's shared Area and stitching transactions across the LWC → Apex → Flow legs. Then it pauses:

{% code lineNumbers="true" %}

```
Batch 3/17 — Opportunity Management (Area: OpportunityManagement)
  ✎ OpportunityController.cls        @AuraEnabled  · txn resume + 2 catches + flush
  ✎ opportunityCard (LWC)            timeBackendCall · stitches via transactionId
  ✎ Recalc_Opportunity.flow-meta.xml 1 fault path + flow entry
Review: [yes] apply & continue · [modify] · [skip file] · [pause]
```

{% endcode %}

You review the batch as a unit — the same `yes` / `modify` / `skip` choices as a single-file run, plus `pause` to stop and resume later. Nothing in the batch is written until you accept it.

### Step 5 — Deploy (optional, per batch)

With `--deploy` (or on confirmation), each accepted batch deploys before the next one starts, so instrumented code lands incrementally and you can watch logs appear in Pharos as you go. A failed deploy stops the run without reverting files, exactly like the single-file skills.

### Step 6 — Coverage report

At the end (or on `pause`), the skill writes a summary: how many files of each type were instrumented, skipped, or deferred; the Areas assigned; transactions correlated; and what's left. Re-running picks up where it left off.

{% code lineNumbers="true" %}

```
Triton instrumentation coverage — force-app/main/default
  Apex     124/141 instrumented · 9 tests skipped · 8 deferred (low-comfort)
  LWC       38/40  instrumented · 2 deferred
  Flows     19/22  instrumented · 3 deferred (managed)
  Areas assigned: 11 · Transactions correlated across 27 LWC→Apex chains
  Deferred items and reasons: see report.md
```

{% endcode %}

## Staying in control at scale

The point of the human-in-the-loop diff doesn't disappear just because you're running org-wide — it moves to the **batch** boundary:

* **Checkpoints, not a firehose.** You approve a feature at a time, not hundreds of files at once.
* **Resumable.** `pause` and re-run; the inventory tracks what's done.
* **`--dry-run` first.** See the full plan and Area assignments before a single write.
* **Defers instead of guesses.** Low-comfort, business-critical code is surfaced for a human rather than rewritten blindly.

{% hint style="success" %}
**This is the "instrument everywhere" button — with a seatbelt.** You get the leverage of one command across an entire org, but the tedious 90% is what's automated, not the judgment. Every change still passes a review before it's written or deployed.
{% endhint %}

## Where to go next

* [Audit Logging Coverage](https://triton.pharos.ai/instrumentation-skills/audit-logging) — the read-only map to run before you start.
* [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex) · [Instrument LWC](https://triton.pharos.ai/instrumentation-skills/instrument-lwc) · [Instrument Flows](https://triton.pharos.ai/instrumentation-skills/instrument-flows) — the primitives this skill orchestrates.
* [Legacy Code Logging Rollout](https://triton.pharos.ai/triton-best-practices/legacy-migration) — the strategy the phasing is built on.
* [The Triton Instrumentation Agent](https://triton.pharos.ai/instrumentation-skills/instrumentation-agent) — package this behind a persona for a "point at an org" experience.
* [Set Up Standards](https://triton.pharos.ai/instrumentation-skills/setup-standards) — lock in CI guardrails so instrumented code stays instrumented.


# Audit Logging Coverage

The audit-logging skill scans a Salesforce project read-only, reports where Triton logging is missing or wrong, and produces a prioritized rollout plan.

The **audit-logging** skill answers the question you have before any rollout: *how bad is it, and where do I start?* It reads a project **without writing anything** and produces two things — a **coverage report** (what's instrumented, what isn't, and what's wrong) and a **prioritized plan** you can hand straight to [`instrument-org`](https://triton.pharos.ai/instrumentation-skills/instrument-org).

It's the read-only sibling of the instrumentation skills. Nothing it finds is changed; it only tells you what it found.

{% hint style="info" %}
**Invocation is agent-specific.** In agents that support slash commands (Claude Code, Cursor) you invoke it as `/pharos:audit-logging <path>`; in others you point the agent at this skill and a directory. See [Running these in your agent](https://triton.pharos.ai/instrumentation-skills#running-these-in-your-agent).
{% endhint %}

## Usage

{% code lineNumbers="true" %}

```bash
/pharos:audit-logging [<path>] [--format md|json] [--fail-on error,debug] [--tech apex,lwc,flow]
```

{% endcode %}

| Argument    | Required | Meaning                                                                        |
| ----------- | :------: | ------------------------------------------------------------------------------ |
| `<path>`    |          | Project root or subtree. Defaults to the detected project root.                |
| `--format`  |          | `md` (default, human-readable) or `json` (machine-readable, for CI).           |
| `--fail-on` |          | Exit non-zero when a given class of finding is present — for use as a CI gate. |
| `--tech`    |          | Restrict to some technologies. Defaults to all three.                          |

## What it checks

The checks mirror the [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement) review checklist, sorted into hard failures (a machine can be certain) and judgment calls (flagged for a human).

### Hard findings — unambiguous

| Finding                                 | Why it matters                                                                                                                                                  |
| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`System.debug` in application code**  | Invisible telemetry — should be a `Triton.debug(...)`.                                                                                                          |
| **`Triton.instance` usage**             | The removed 1.x singleton; its presence means un-migrated code. Route it to [`migrate-to-2.0`](https://triton.pharos.ai/instrumentation-skills/migrate-to-2.0). |
| **Catch-but-not-logged**                | A `catch` block with no Triton call — the most common way errors go dark.                                                                                       |
| **Missing flush at a boundary**         | A method that buffers logs but has no `Triton.flush()` at the end of the handler/`execute`/`finally`.                                                           |
| **Un-logged entry points**              | `@AuraEnabled`, REST, Queueable `execute`, Batch `start`/`finish` with no logging at all.                                                                       |
| **Flow fault paths with no Log action** | A `<faultConnector>` with no `TritonFlow` action — unhandled Flow errors going unseen.                                                                          |

### Judgment findings — flagged, not failed

* **Ad-hoc taxonomy strings** — `.area('...')` / `.type('...')` literals where an enum value exists, hinting at drift.
* **Honesty of levels** — `ERROR` used for non-failures, or loop chatter above `FINE`.
* **Missing context** — record-oriented logs with no `.relatedObject(s)`; callouts with no `.integrationPayload(...)`.
* **Low-comfort code** — old, untested, business-critical files that a rollout should treat gently (see the [comfort tiers](https://triton.pharos.ai/triton-best-practices/legacy-migration#start-by-assessing-your-comfort-with-the-code)).
* **Publishes in managed-package-object triggers** — `Triton.logNow(...)`, `Triton.flush()`, or `Triton.flushTop()` on a path reached from a trigger on another package's object (an SObject name carrying that package's namespace). The write belongs to the package, often under an integration user you can't test as. Triton 2.0.0 and later never throws on a failed publish, but an exhausted governor limit still fails the write, and a copy of Triton vendored before 2.0.0 does throw. The audit notes the Triton version it found and recommends `Triton.log(...)` plus one `Triton.flush()` as the handler's last statement, and the restricted-user test from [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex#trigger-handlers-logging-never-fails-the-write).

{% hint style="info" %}
The audit uses the same static, grep-level signals the [CI guardrails](https://triton.pharos.ai/instrumentation-skills/setup-standards) use, plus structural analysis (it parses classes and flows, not just text). The hard findings are exactly what you'd want to block in CI; the judgment findings are what a reviewer should eyeball.
{% endhint %}

## The report

The default Markdown report leads with a scoreboard, then the prioritized plan, then the detail.

{% code lineNumbers="true" %}

```
Triton logging audit — force-app/main/default

Coverage
  Apex     62/141 instrumented (44%) · 79 gaps
  LWC       9/40  instrumented (23%) · 31 gaps
  Flows     4/22  instrumented (18%) · 18 gaps

Hard findings (block-worthy)
  System.debug ............ 213 occurrences in 47 classes
  Triton.instance (1.x) ... 12 classes  → migrate-to-2.0
  catch-not-logged ........ 88 blocks
  missing flush ........... 34 methods
  un-logged entry points .. 51
  flow faults unlogged .... 15

Suggested order (by value/risk)
  Phase 1 — entry points .. 51 files  (start here)
  Phase 2 — internals ..... 63 files
  Phase 3 — sweep ......... 40 files
  Deferred (low-comfort) .. 8 files   (review by hand)

Next: /pharos:instrument-org --phase 1
```

{% endcode %}

The `json` format emits the same data as structured findings (file, line, rule, severity) so you can gate CI or feed a dashboard.

## Where this fits

`audit-logging` is the front door of the whole workflow:

1. **Audit** — run this, read the report. *(read-only)*
2. **Fix version drift** — [`migrate-to-2.0`](https://triton.pharos.ai/instrumentation-skills/migrate-to-2.0) on anything using the 1.x singleton.
3. **Instrument** — [`instrument-org`](https://triton.pharos.ai/instrumentation-skills/instrument-org) works the prioritized plan.
4. **Lock it in** — [`setup-standards`](https://triton.pharos.ai/instrumentation-skills/setup-standards) wires the hard findings into CI so gaps can't creep back.

{% hint style="success" %}
**Re-run it as a ratchet.** With `--fail-on error,debug` in CI, the audit becomes a regression gate: once you've cleared `System.debug` and un-logged catches from an area, the build fails if they come back.
{% endhint %}

## Where to go next

* [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org) — act on the plan this audit produces.
* [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement) — the checklist and CI rules these checks come from.
* [Set Up Standards](https://triton.pharos.ai/instrumentation-skills/setup-standards) — turn the hard findings into automated guardrails.
* [Migrate to 2.0](https://triton.pharos.ai/instrumentation-skills/migrate-to-2.0) — clear the `Triton.instance` findings.


# Migrate to 2.0

The migrate-to-2.0 skill rewrites 1.x Triton.instance code to the 2.0 static API and flags the immediate-vs-buffered publishing gotcha for you to confirm.

The **migrate-to-2.0** skill automates the mechanical half of [Migrating from Triton 1.x to 2.0](https://triton.pharos.ai/migration): it finds every `Triton.instance.*` call and rewrites it to the 2.0 static, builder-first API, using the same method mapping the migration guide documents. Where a rename could quietly change behavior, it **stops and asks** rather than guessing.

This skill is about **converting existing logging**, not adding new logging. If a class has no logging at all, that's a job for [`instrument-apex`](https://triton.pharos.ai/instrumentation-skills/instrument-apex). A typical org runs `migrate-to-2.0` first (to clear the 1.x singleton) and `instrument-org` second (to fill the gaps).

{% hint style="info" %}
**Invocation is agent-specific.** In agents that support slash commands (Claude Code, Cursor) you invoke it as `/pharos:migrate-to-2.0 <path>`; in others you point the agent at this skill and a path. See [Running these in your agent](https://triton.pharos.ai/instrumentation-skills#running-these-in-your-agent).
{% endhint %}

## Usage

{% code lineNumbers="true" %}

```bash
/pharos:migrate-to-2.0 <path> [--collapse-exceptions] [--collapse-dml] [--deploy]
```

{% endcode %}

| Argument                | Required | Meaning                                                                                                                                            |
| ----------------------- | :------: | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<path>`                |     ✅    | A `.cls`/`.trigger` file, or a directory to sweep.                                                                                                 |
| `--collapse-exceptions` |          | While migrating, collapse hand-assembled error logs down to `.exception(e)`. On by default; pass `--no-collapse-exceptions` to keep them verbatim. |
| `--collapse-dml`        |          | Collapse hand-built bulk-DML failure logs to `.dmlResults(results)`.                                                                               |
| `--deploy`              |          | Deploy after you accept the diff.                                                                                                                  |

## If you vendor Triton as source

When the `Triton*.cls` files live in your repository instead of arriving as a package, the library upgrade is part of the change: 2.0 removes `Triton.instance`, so the library and every caller have to land together. Before rewriting a single caller, the skill has you settle three things:

* **Re-add org-local enum values.** Diff your `TritonTypes` against the incoming 2.0 one; a wholesale copy drops any values you added, and every reference to them stops compiling. (Org-local `Category` values are better retired than preserved — see the note on removed categories in the [migration guide](https://triton.pharos.ai/migration#use-real-enum-values).)
* **Sweep the right branch.** The sweep is only as complete as its path and its branch, so run it on the branch that holds every caller.
* **Keep Jest tests out of deploys.** Add `**/__tests__/**` and `**/__mocks__/**` to your project's `.forceignore`. Triton's own repository already ignores them, but a `.forceignore` only governs the project it sits in.

## What it rewrites

The skill applies the [method mapping](https://triton.pharos.ai/migration#method-mapping) call by call:

* **Drops `.instance`** — every `Triton.instance.<method>(...)` becomes a static `Triton.<method>(...)`.
* **Moves positional args onto a builder** — old positional signatures become `Triton.t.area(...).summary(...)...` builder chains.
* **Maps level methods correctly** (see the gotcha below).
* **Collapses hand-set error fields** to `.exception(e)` and hand-built DML summaries to `.dmlResults(...)` when the flags allow.
* **Covers every 1.x overload.** It lists every distinct `Triton.instance.<member>` in scope — including property reads such as `TRANSACTION_ID` — and matches each by name *and* argument shape against the mapping table. A call whose exact overload isn't in the table stops the skill; it never guesses a mapping.
* **Sweeps test classes too.** `@isTest` classes are migrated as well: 1.x calls in tests won't compile against 2.0 either.
* **Leaves post-processing alone.** 2.0 sets no post-processing controls on Apex logs, so the narrower set the 1.x warning, debug, and event methods asked for (stack trace, user info, related objects) isn't restated by default. If you want it back, the skill appends `.postProcessing(...)` to those calls and flags each one.
* **Flags ad-hoc taxonomy strings** — `.area('InvoiceSync')` and the like — suggesting a `public static final String` constant per [Custom Classifications](https://triton.pharos.ai/core-concepts/custom-classifications), and never editing the shipped `TritonTypes` enums.

## The one gotcha it will not guess on

The migration guide's [behavioral change](https://triton.pharos.ai/migration#the-behavioral-change-to-audit-for) is the reason this can't be a blind find-and-replace:

* In 1.x, **bare** methods (`error`, `warning`, `debug`, `event`, `dmlResult`, `integrationError`, and `log`) published **immediately**; `add*` methods **buffered**.
* In 2.0, **all** level methods buffer — you opt into immediate publishing with **`Triton.logNow(...)`**.

So the mapping sends old **bare** methods to `Triton.logNow(...)` and old **`add*`** methods to the buffering level methods. But whether a given old bare call *relied* on immediate publishing is a judgment the skill won't make silently:

{% hint style="danger" %}
**Every old bare-method call is surfaced for confirmation.** For each bare call — `Triton.instance.error(...)` and the other immediate methods — the skill proposes `Triton.logNow(...)` **and** shows you the alternative (buffer + ensure a `flush()` covers it), asking you to confirm. Getting this wrong is how a migrated log silently disappears when a transaction dies before flushing — so the skill refuses to auto-decide it.
{% endhint %}

It also **audits flush coverage** as it goes: now that level methods buffer, any path that logs must also flush (end of handler/`execute`, or a `finally`). Missing flushes are reported alongside the diff.

## Successful DML: check the library, not the call site

1.x `addDMLResult` and `dmlResult` logged only when a row failed. The 2.0 mapping — `Triton.error(Triton.t.area(area).dmlResults(results))` — keeps that by itself: from Triton 2.0.0, `dmlResults(...)` emits nothing when every row succeeded, or the list is null or empty, whichever method it's passed to. So the rewrite is correct as written, with or without a failure check around the call.

What the skill verifies is the library you're migrating **to**. A copy of the 2.0 source vendored before 2.0.0 has no such skip, and there the same rewrite would log an empty ERROR record — and open an issue — on every successful DML. The skill checks the vendored `TritonBuilder.cls` for an `isSuppressed()` method; if it's missing, it has you upgrade the library in the same change rather than adding guards at each call site.

## Example rewrite

{% code lineNumbers="true" %}

```apex
// Before (1.x)
Triton.instance.error(TritonTypes.Area.Accounts, e);
Triton.instance.addDebug(t, TritonTypes.Area.Accounts, 'Rollups done', details);

// After (2.0) — bare error → logNow (confirmed), addDebug → buffering debug
Triton.logNow(Triton.t.area(TritonTypes.Area.Accounts).exception(e));
Triton.debug(Triton.t.type(t).area(TritonTypes.Area.Accounts).summary('Rollups done').details(details));
```

{% endcode %}

## Review and deploy

Before it shows you anything, the skill runs two checks a reviewer reading a diff would miss:

1. **No 1.x member survives** — no `Triton.instance` left in scope, and no half-migrated static call to a method 2.0 doesn't have (`Triton.addError(...)` and friends).
2. **Every enum reference resolves** — each `TritonTypes.<enum>.<value>` exists in the 2.0 `TritonTypes`. This catches removed values such as `TritonTypes.Category.Event`, and org-local values a re-vendored library dropped.

Re-run the first check right before merge, not just at sweep time: a 1.x caller merged in the meantime leaves the branch uncompilable. The [`setup-standards`](https://triton.pharos.ai/instrumentation-skills/setup-standards) CI check that fails the build on any `Triton.instance` makes that automatic.

Like every skill here, it then presents a summary — calls migrated, bare-method confirmations pending, the library-version check, collapses applied, flush gaps found, any `.attribute(...)` fallbacks — then the diff, with `yes` / `modify` / `skip`. On `yes` it writes back to the original file; with `--deploy` it runs `sf project deploy start`.

{% hint style="warning" %}
**After deploying, re-assign the permission sets** (`Triton_Read` / `Triton_Write`) so the new 2.0 fields are visible — see the [2.0 release notes](https://triton.pharos.ai/release-notes/2.0). And remember the migration guide's [checklist](https://triton.pharos.ai/migration#migration-checklist) items a code rewrite can't do for you (permission sets, template placement review).
{% endhint %}

{% hint style="info" %}
**Deploying into an org that still runs 1.x?** `--deploy` fails there, because the migrated code calls 2.0 methods the org doesn't have yet. Follow [Upgrading an Org from 1.x](https://triton.pharos.ai/migration/upgrading-an-org) to land it together with 2.0.
{% endhint %}

## What it doesn't touch

The skill rewrites **Apex only**. Check these by hand, using [LWC changes to check](https://triton.pharos.ai/migration#lwc-changes-to-check) and the `Log_Level__mdt` item in the [2.0 upgrade notes](https://triton.pharos.ai/release-notes/2.0#upgrade-notes):

* **LWC** — removed `CATEGORY` keys (`WARNING`, `DEBUG`, `EVENT`), code that compares area strings, and code that relied on `logNow()` rejecting.
* **Flow XML** — **Log** actions that pass a removed category (`Integration`, `Warning`, `Event`, `Debug`) or a version-suffixed `flowApiName`.
* **`Log_Level__mdt` rules** keyed on a removed category, which silently stop matching.

## Where to go next

* [Migrating from Triton 1.x to 2.0](https://triton.pharos.ai/migration) — the conceptual guide this skill automates; read the gotcha section.
* [Audit Logging Coverage](https://triton.pharos.ai/instrumentation-skills/audit-logging) — finds the `Triton.instance` usage to point this skill at.
* [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org) — add logging where there was none, after migration.
* [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing) — why the immediate-vs-buffered change matters.


# Set Up Standards

The setup-standards skill scaffolds CI checks, a review checklist, and Log\_Level\_\_mdt defaults so Triton instrumentation stays consistent as your org grows.

Instrumenting an org is only half the battle; the other half is keeping it instrumented. The **setup-standards** skill scaffolds the guardrails from [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement) into your repo so regressions get caught by a machine instead of a tired reviewer — the two hard CI rules, the higher-value checks, a short review checklist, and sensible `Log_Level__mdt` defaults.

It writes config, not application code, and it tailors what it generates to the CI system it detects.

{% hint style="info" %}
**Invocation is agent-specific.** In agents that support slash commands (Claude Code, Cursor) you invoke it as `/pharos:setup-standards`; in others you point the agent at this skill. See [Running these in your agent](https://triton.pharos.ai/instrumentation-skills#running-these-in-your-agent).
{% endhint %}

## Usage

{% code lineNumbers="true" %}

```bash
/pharos:setup-standards [--ci github|gitlab|bitbucket|generic] [--pmd] [--checklist] [--log-levels]
```

{% endcode %}

| Argument       | Required | Meaning                                                                                         |
| -------------- | :------: | ----------------------------------------------------------------------------------------------- |
| `--ci`         |          | Which pipeline to target. Auto-detected from the repo (e.g. `.github/workflows/`) when omitted. |
| `--pmd`        |          | Also emit PMD rules, not just grep-level checks.                                                |
| `--checklist`  |          | Drop the PR review checklist into the repo (e.g. a pull-request template).                      |
| `--log-levels` |          | Scaffold `Log_Level__mdt` records with per-environment defaults.                                |

## What it generates

### The two hard CI rules

The non-negotiables that are cheap to automate — no `System.debug` in application code, no `Triton.instance` (the removed 1.x singleton). As a grep-level check for the detected pipeline:

{% code lineNumbers="true" %}

```bash
# Fail the build on System.debug in application code (tests excepted)
if grep -rn "System.debug" force-app/main --include=*.cls | grep -v "Test.cls"; then
  echo "❌ System.debug found — use Triton logging instead."
  exit 1
fi

# Fail on any lingering 1.x singleton usage
if grep -rn "Triton\.instance" force-app/main --include=*.cls; then
  echo "❌ Triton.instance is 1.x — migrate to the static API (Triton.log/Triton.t)."
  exit 1
fi
```

{% endcode %}

With `--pmd`, the same two rules are emitted as `RegexRule` entries for your ruleset so they land in the same report as the rest of your static analysis.

### The review checklist

With `--checklist`, it writes the short, actually-usable list from [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement#the-review-checklist) — template set, real taxonomy, honest levels, exceptions logged, flush coverage, context present, transactions correlated — as a PR template so a reviewer just ticks boxes.

### `Log_Level__mdt` defaults

With `--log-levels`, it scaffolds per-environment log-level records so verbosity is tuned by metadata, not code — quiet in production, chatty in a scratch org.

{% hint style="warning" %}
**It won't over-fit your CI.** Following the guidance in [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement#ci-guardrails), the skill only automates checks with crisp true/false answers (`System.debug`, `Triton.instance`). Judgment calls — "is this the right Area?", "should this be `ERROR`?" — stay on the review checklist for humans, not in brittle regexes that cry wolf.
{% endhint %}

## The ratchet

Pair this with [`audit-logging`](https://triton.pharos.ai/instrumentation-skills/audit-logging) to turn standards into a one-way ratchet:

1. `audit-logging --fail-on error,debug` runs in CI as a gate.
2. `setup-standards` installs the hard rules so new `System.debug` / `Triton.instance` can't merge.
3. As [`instrument-org`](https://triton.pharos.ai/instrumentation-skills/instrument-org) clears each area, the gate holds it clean — gaps can't creep back in.

## Where to go next

* [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement) — the full rationale and the higher-value checks worth building once.
* [Audit Logging Coverage](https://triton.pharos.ai/instrumentation-skills/audit-logging) — the read-only report that feeds the CI gate.
* [Taxonomy & Standards](https://triton.pharos.ai/triton-best-practices/taxonomy-and-standards) — the vocabulary these checks defend.
* [Legacy Code Logging Rollout](https://triton.pharos.ai/triton-best-practices/legacy-migration) — how to enforce on new code first while retrofitting old code gradually.


# The Triton Instrumentation Agent

The whole instrumentation skill catalog behind one portable, agent-agnostic persona you point at a Salesforce org to audit, migrate, instrument, and guard it.

The individual skills each do one job. The **Triton Instrumentation Agent** is what you get when you package them behind a single persona: *"Here's my org — instrument it."* It's not a new engine and not a new product — it's the [skill catalog](https://triton.pharos.ai/instrumentation-skills#the-skill-catalog) plus a bit of orchestration glue, delivered in whatever form your coding agent understands.

Think of it as the answer to "would an agent be better than a pile of commands?" — yes, when the goal is a full rollout. You hand it a project; it decides what to run and in what order, checking in with you at the boundaries.

{% hint style="info" %}
**Agent-agnostic by construction.** The agent is just three portable pieces — a **system prompt** (the persona and guardrails), the **shared playbook** (the Triton conventions the skills already encode), and a **tool allow-list** (read files, run `sf`/`grep`, write files on approval). Any framework that accepts those runs it. There's no dependency on a specific vendor.
{% endhint %}

## What it bundles

| Framework              | How the agent ships                                                          |
| ---------------------- | ---------------------------------------------------------------------------- |
| **Claude Code**        | A subagent/persona plus the `/pharos:*` commands as its toolbelt.            |
| **Cursor**             | A custom mode (or an `AGENTS.md` persona) with the skills as rules/commands. |
| **Codex CLI / OpenAI** | An `AGENTS.md` describing the persona and the skill files it may follow.     |
| **Windsurf / others**  | A system prompt plus the skill Markdown, loaded as project context.          |
| **Any agent**          | Paste the persona prompt and point it at the skill files and the repo.       |

Because all five share the same playbook, the agent behaves identically wherever it runs — the only thing that changes is how you launch it.

## What it does, end to end

The agent runs the full workflow the separate skills perform, in order, so you don't have to sequence them yourself:

1. **Audit** — runs [`audit-logging`](https://triton.pharos.ai/instrumentation-skills/audit-logging) read-only and presents the coverage report and a proposed plan.
2. **Migrate** — where the audit found `Triton.instance`, runs [`migrate-to-2.0`](https://triton.pharos.ai/instrumentation-skills/migrate-to-2.0), surfacing every immediate-vs-buffered decision for you.
3. **Instrument** — drives [`instrument-org`](https://triton.pharos.ai/instrumentation-skills/instrument-org) through the prioritized phases, one Area per feature, stitching transactions across LWC → Apex → Flow, with a review checkpoint per batch.
4. **Guard** — offers [`setup-standards`](https://triton.pharos.ai/instrumentation-skills/setup-standards) to wire the hard findings into CI so the work can't regress.
5. **Report** — leaves you a coverage summary and a list of anything it deferred for a human.

{% hint style="success" %}
**The "point at an org, instrument everywhere" experience.** This is the highest-leverage way to use Triton's tooling: one persona, one instruction, a whole org instrumented consistently — and still a human approving every batch before it's written or deployed.
{% endhint %}

## Guardrails baked into the persona

The persona isn't "instrument aggressively." It carries the same discipline the docs preach, so autonomy never becomes recklessness:

* **Human-in-the-loop stays.** It approves changes at batch boundaries; it never writes hundreds of files unattended.
* **Do no harm on legacy code.** It respects the [comfort tiers](https://triton.pharos.ai/triton-best-practices/legacy-migration#start-by-assessing-your-comfort-with-the-code) — minimal edits to old, untested, business-critical code, and it defers rather than rewrites when unsure.
* **One mechanism per call chain.** It keeps transaction stitching consistent (param *or* cache, not both) across the LWC/Apex/Flow legs of a feature.
* **Real taxonomy, upgrade-safe.** It reuses existing Areas, and steers org-specific values to `String` constants rather than editing the shipped enums (see [Custom Classifications](https://github.com/Pharos-AI/triton-docs/tree/release/2.0/core-concepts/custom-classifications.md)).
* **Never lets logging throw.** It follows the [risk-mitigation patterns](https://triton.pharos.ai/triton-best-practices/legacy-migration#risk-mitigation) — feature flags and guarded logging calls in the riskiest code.

## When to reach for it (vs. a single skill)

| Situation                                             | Use                                                                                                        |
| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| One class/component/flow to instrument                | The matching [per-technology skill](https://triton.pharos.ai/instrumentation-skills#the-skill-catalog).    |
| A feature or folder                                   | [`instrument-org`](https://triton.pharos.ai/instrumentation-skills/instrument-org) scoped to that subtree. |
| A whole org, or a repeatable rollout across many orgs | **The agent.**                                                                                             |
| Just want to see the gaps                             | [`audit-logging`](https://triton.pharos.ai/instrumentation-skills/audit-logging).                          |

## Where to go next

* [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org) — the orchestrator at the agent's core.
* [Audit Logging Coverage](https://triton.pharos.ai/instrumentation-skills/audit-logging) · [Migrate to 2.0](https://triton.pharos.ai/instrumentation-skills/migrate-to-2.0) · [Set Up Standards](https://triton.pharos.ai/instrumentation-skills/setup-standards) — the stages the agent sequences.
* [Legacy Code Logging Rollout](https://triton.pharos.ai/triton-best-practices/legacy-migration) — the strategy the persona is built to follow.
* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) — the correlated, OTEL-ready shape the agent rolls out everywhere.


# Best Practices & Standards

Opinionated, field-tested standards for rolling out Pharos Triton logging across Apex, LWC, and Flow, and keeping it consistent as your org grows.

The [Core Concepts](https://triton.pharos.ai/core-concepts) tell you *how* the Triton API works. This section is about *how to use it well* — the judgment calls that separate logs you're glad you have from noise you'll end up filtering out.

It's written for the person standing up Triton across a real org: architects and senior developers who have to make logging consistent across a dozen teams, a pile of legacy triggers, and every technology Salesforce throws at them (Apex, LWC, Flow). The advice here is opinionated on purpose. When there's a right answer, we'll give it to you.

Everything is on the **2.0 static, builder-first API** — `Triton.log(Triton.t...)`, no `Triton.instance`. If you're coming from 1.x, read [Migrating from Triton 1.x to 2.0](https://triton.pharos.ai/migration) first, then come back here.

## The short version

If you read nothing else, internalize these five:

* **Build every log the same way.** Set a [template](https://triton.pharos.ai/triton-best-practices/templates-and-builder-pattern) once per unit of work, then log from `Triton.t`. Consistency is what makes logs searchable.
* **Buffer the routine, publish the critical.** Queue progress logs and [flush at boundaries](https://triton.pharos.ai/triton-best-practices/buffering-and-flushing); send exceptions with `logNow` so you never lose the one that mattered.
* **Log at the right level and let metadata decide.** Don't gate logs behind `if (debug)` — pick a [level](https://triton.pharos.ai/triton-best-practices/log-levels-and-usage) and tune volume through `Log_Level__mdt`.
* **Correlate across hops.** Start a [transaction](https://triton.pharos.ai/triton-best-practices/transaction-management) at the entry point and carry it through LWC → Apex → Flow so one user action reads as one trace.
* **Use the real** [**taxonomy**](https://triton.pharos.ai/triton-best-practices/taxonomy-and-standards)**.** Category/Type/Area from the enums, extended deliberately — never ad-hoc strings.

## How this section is organized

Read it in order the first time; each page assumes the one before it.

| Page                                                                                                            | What it covers                                                                           |
| --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| [Core Principles](https://triton.pharos.ai/triton-best-practices/core-principles)                               | The handful of ideas the rest of the section is built on, plus the master Do/Don't list. |
| [Log Levels: When to Use What](https://triton.pharos.ai/triton-best-practices/log-levels-and-usage)             | Picking `ERROR` vs `WARNING` vs `INFO` vs `DEBUG`, and tuning verbosity per environment. |
| [Templates & the Builder Pattern](https://triton.pharos.ai/triton-best-practices/templates-and-builder-pattern) | Setting a template per unit of work and logging from `Triton.t`.                         |
| [Buffering & Flushing](https://triton.pharos.ai/triton-best-practices/buffering-and-flushing)                   | Conserving platform events without losing critical logs.                                 |
| [Transaction Management](https://triton.pharos.ai/triton-best-practices/transaction-management)                 | Stitching logs together across LWC, Apex, and Flow.                                      |
| [Implementation Patterns](https://triton.pharos.ai/triton-best-practices/implementation-patterns)               | Copy-ready patterns for triggers, batches, queueables, REST, schedulers, LWC, and Flow.  |
| [Context & Related Objects](https://triton.pharos.ai/triton-best-practices/context-and-related-objects)         | Making each log carry enough context to debug from.                                      |
| [Taxonomy & Standards](https://triton.pharos.ai/triton-best-practices/taxonomy-and-standards)                   | Designing a Category/Type/Area vocabulary that scales.                                   |
| [Exception Handling](https://triton.pharos.ai/triton-best-practices/exception-handling)                         | Turning caught exceptions into actionable, correlated error logs.                        |
| [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement)                   | Code-review checklists and CI guardrails that keep standards from rotting.               |
| [Legacy Code Logging Rollout](https://triton.pharos.ai/triton-best-practices/legacy-migration)                  | Adding observability to old, poorly-understood code without breaking it.                 |

{% hint style="info" %}
**Why any of this matters.** A single user action might cross an LWC, an Apex controller, a Flow, and a callout. When it breaks at 2am, the difference between a five-minute fix and a five-hour investigation is whether those five layers produced one coherent, well-labeled trace — or five disconnected piles of text. The standards here exist to make the first outcome the default.
{% endhint %}


# Core Principles

The handful of ideas that make Triton logging worth having — and a master Do/Don't list you can hand to a new team member on day one.

Good logging isn't about logging *more*. An org drowning in undifferentiated `System.debug` output is worse off than one with a few well-placed, well-labeled logs, because volume without structure is just noise you pay to store. Everything in this section comes back to a small set of principles. Learn these and the specific patterns on the following pages will feel obvious.

## Consistency beats cleverness

The single most valuable property of a log is that it looks like every other log of its kind. If one developer writes `.area(TritonTypes.Area.Accounts)` and another writes `.area('Account')` and a third writes `.area('acct')`, no filter, dashboard, or alert will ever line them up — and the whole point of structured logging evaporates.

This is why the [template pattern](https://triton.pharos.ai/triton-best-practices/templates-and-builder-pattern) exists and why we lean on it so hard: set the shared fields once, log from `Triton.t`, and every log in that unit of work is automatically consistent.

{% code lineNumbers="true" %}

```apex
// Set the shape of your logs once, at the top of the unit of work
Triton.setTemplate(Triton.makeBuilder()
    .category(TritonTypes.Category.Apex)
    .area(TritonTypes.Area.OpportunityManagement));

// Every log from here shares category + area, for free
Triton.info(Triton.t.summary('Sync started'));
Triton.error(Triton.t.summary('Sync failed').exception(e));
```

{% endcode %}

## A log is only as good as its context

A log that says `"Update failed"` is almost useless. A log that says `"Update failed"`, is tied to the three records involved, carries the transaction id, and captures the stack trace and governor limits, is something you can actually debug from.

The good news: Triton does most of the heavy lifting automatically. When you call `Triton.log(...)`, the framework captures the stack trace, derives the operation (class/method), records governor-limit usage, and — for Apex logs — stamps the execution context (trigger operation, batch size, async type). Your job is to add the business context only Triton can't infer: which records this is about (`.relatedObject(s)`), and a human-readable `.summary()`. See [Context & Related Objects](https://triton.pharos.ai/triton-best-practices/context-and-related-objects).

## Right level, right volume

Every log gets a [level](https://triton.pharos.ai/triton-best-practices/log-levels-and-usage), and the level does double duty: it tells a human how urgent the record is, and it lets you tune volume per environment through `Log_Level__mdt` — no code change. Reserve `ERROR` for things a person should actually look at, make `INFO` your production signal, and push loop-level chatter down to `FINE` and below where filtering can switch it off cheaply.

The anti-pattern to avoid: gating logs behind your own flags (`if (debugMode) Triton.debug(...)`). Log at the honest level and let metadata decide what persists. That's the whole point of the level system.

## Correlate across boundaries

Modern Salesforce work rarely stays in one place. A button click runs an LWC, calls Apex, commits a DML that fires a Flow, which enqueues a Queueable. If each of those logs in isolation, you get five disconnected stories. Start a [transaction](https://triton.pharos.ai/triton-best-practices/transaction-management) at the entry point and carry the id across the hops, and you get one trace you can read top to bottom.

## Safe by default

Logs are durable and widely readable, so treat them like it. Never log secrets, tokens, passwords, or regulated PII. Do log the things that make debugging possible without exposing anything sensitive: record ids, correlation ids, counts, durations, and status codes. When you attach an integration payload, sanitize it first.

## The master Do / Don't list

Hand this to anyone new to Triton. It's the whole section compressed to one screen.

{% hint style="success" %}
**Do**

* **Set a template** per unit of work and log from `Triton.t`.
* **Use `.exception(e)`** for errors — it sets the level, type, summary, stack trace, and issue flag in one call.
* **Buffer routine logs**, and publish critical ones immediately with `Triton.logNow(...)`.
* **Flush at boundaries** — end of a trigger handler, batch `execute`, or in a `finally` block.
* **Attach related records** with `.relatedObject(s)` so logs correlate to data.
* **Start/resume/stop transactions** across LWC → Apex → Flow.
* **Use stable values** for Category/Type/Area — the built-in enums where they fit, and your own `String` constants for org-specific Types and Areas, never edits to the shipped enums.
  {% endhint %}

{% hint style="danger" %}
**Don't**

* **Don't use `System.debug`** in application code — it vanishes with the debug log.
* **Don't reach for `Triton.instance`** — that's the 1.x singleton; 2.0 is fully static.
* **Don't log PII or secrets**, and don't dump raw payloads without sanitizing.
* **Don't gate logs** behind `if (debug)` flags — set the level and let `Log_Level__mdt` filter.
* **Don't over-log tight loops** at `INFO` — that's what `FINE`/`FINER`/`FINEST` are for.
* **Don't swallow exceptions** after logging unless the design genuinely calls for recovery.
* **Don't invent ad-hoc classification strings** — extend the taxonomy instead.
  {% endhint %}

## Where to go next

These principles are the "why." The rest of the section is the "how":

* Put them into practice with [Templates & the Builder Pattern](https://triton.pharos.ai/triton-best-practices/templates-and-builder-pattern).
* See them applied to real contexts in [Implementation Patterns](https://triton.pharos.ai/triton-best-practices/implementation-patterns).
* Keep them alive on a growing team with [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement).


# Log Levels: When to Use What

Choosing the right log level for each situation — and using Log\_Level\_\_mdt to turn the volume up in a sandbox and down in production without touching code.

The mechanics of levels — the seven-value scale and how `Log_Level__mdt` filters them at runtime — live in [Core Concepts → Log Levels](https://triton.pharos.ai/core-concepts/log-levels). This page is about the judgment call: given a specific thing that just happened in your code, which level does it deserve?

Get this wrong in one direction and you drown real problems in trivia. Get it wrong in the other and the log you needed at 2am was filtered out in production. So it's worth being deliberate.

## The decision, in one table

| Level                     | Reach for it when…                           | Real examples                                                                               | Don't use it for…                                        |
| ------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| **ERROR**                 | Something failed that a human should look at | Uncaught exception, failed callout, broken invariant, DML that lost data                    | Expected/benign conditions ("no records to process")     |
| **WARNING**               | Something recoverable or suspicious happened | Retry after a timeout, partial DML failure, fallback path taken, governor limit approaching | Every retry attempt — one warning per *distinct* problem |
| **INFO**                  | A notable business event completed           | "Order placed", "Batch finished: 240 processed", "12 leads converted"                       | Per-record chatter inside a loop                         |
| **DEBUG**                 | Developer detail useful while diagnosing     | Branch decisions, query shapes, intermediate state                                          | Anything you'd be embarrassed to leave on in prod        |
| **FINE / FINER / FINEST** | Increasingly verbose tracing                 | Loop-body detail, payload snippets, micro-timing                                            | The signal you actually want in production               |

{% hint style="info" %}
**The one-sentence heuristic:** if you'd want to see it in production, it's `INFO` or higher; if it only helps while you're actively debugging, it's `DEBUG` or below. `ERROR` is reserved for "wake someone up" — if everything is an error, nothing is.
{% endhint %}

## A worked example: a processing batch

Notice how one method spans four levels — routine progress buffered at `INFO`, a per-record diagnostic at `FINE` (invisible in prod, available on demand), and the failure published immediately at `ERROR`.

{% code lineNumbers="true" %}

```apex
public class OrderProcessingBatch implements Database.Batchable<SObject> {
    public void execute(Database.BatchableContext bc, List<Order> scope) {
        Long startTime = System.now().getTime();

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

        // INFO — a business milestone worth seeing in production
        Triton.info(Triton.t.summary('Processing order batch').details('batchSize=' + scope.size()));

        try {
            for (Order ord : scope) {
                // FINE — per-record trace, filtered out in prod, switch on when investigating
                Triton.fine(Triton.t
                    .summary('Processing order')
                    .details('status=' + ord.Status)
                    .relatedObject(ord.Id));
                processOrder(ord);
            }

            // INFO — completion with a duration you can trend
            Triton.info(Triton.t
                .summary('Order batch completed')
                .details('processed=' + scope.size())
                .duration(System.now().getTime() - startTime));

        } catch (Exception e) {
            // ERROR — publish immediately so a mid-batch failure is never lost
            Triton.logNow(Triton.t
                .exception(e)
                .relatedObjects(new Map<Id, Order>(scope).keySet()));
            throw e;
        } finally {
            Triton.flush();   // publish the buffered INFO/FINE logs together
        }
    }
}
```

{% endcode %}

A few things to note about the 2.0 API here: `Triton.info(...)` and `Triton.fine(...)` **buffer** — they don't publish until `flush()`. `.exception(e)` sets the level to `ERROR` for you (no `.error()` needed), and `Triton.logNow(...)` gets that failure out immediately. See [Buffering & Flushing](https://triton.pharos.ai/triton-best-practices/buffering-and-flushing) for why the split matters.

## Level, by intent

If you're unsure, match the *intent* of the log to a level:

* **"A person needs to act on this."** → `ERROR`. Exceptions, integration failures that break a process, data integrity problems.
* **"This is off, but we handled it."** → `WARNING`. Fallbacks, retries, partial failures, nearing a governor limit. One warning per distinct condition — don't spam.
* **"This is the story of what the system did."** → `INFO`. Lifecycle events and business milestones: jobs started/finished, records created, conversions completed. This is your production baseline.
* **"I'm explaining a decision to my future self."** → `DEBUG`. Which branch ran, what a query returned, why a value was chosen.
* **"I need the firehose."** → `FINE` / `FINER` / `FINEST`. Loop bodies, payload dumps, step-by-step traces. Cheap to leave in code because filtering keeps them out of prod.

## Tuning by environment — through metadata, not code

Because `Log_Level__mdt` sets thresholds per environment, you don't hard-code environment behavior — you deploy different metadata. A practical baseline:

| Environment              | Typical threshold                             | Why                                                                     |
| ------------------------ | --------------------------------------------- | ----------------------------------------------------------------------- |
| Dev / scratch            | `FINE` or `FINEST`                            | See everything while you build.                                         |
| QA / staging             | `INFO`                                        | Production-like signal, still enough to investigate.                    |
| Production               | `INFO` (or `WARNING` for very chatty areas)   | Business events and problems, minimal noise.                            |
| Production, mid-incident | temporarily `FINE` for one Category/Type/Area | Turn the firehose on for *just* the flaky area, then turn it back down. |

That last row is the payoff of doing this right: when an integration starts misbehaving, you bump the threshold for that integration's Area to `FINE`, capture a few detailed traces, and drop it back — all without a deploy of Apex. For the full precedence rules, see [Core Concepts → Log Levels](https://triton.pharos.ai/core-concepts/log-levels).

{% hint style="warning" %}
**`ERROR` should never be filtered out.** Don't configure a `Log_Level__mdt` threshold below `ERROR` for a slice of logs that can actually fail — you'd be dropping the exact records you'll wish you had. When in doubt, keep the floor at `ERROR`/`WARNING` in production.
{% endhint %}

## Related reading

* The filtering mechanics and precedence order: [Core Concepts → Log Levels](https://triton.pharos.ai/core-concepts/log-levels).
* How level ties into the classification fields: [Taxonomy & Standards](https://triton.pharos.ai/triton-best-practices/taxonomy-and-standards).


# Templates & the Builder Pattern

The one habit that keeps logging consistent at scale — set a template per unit of work, then log from Triton.t — plus when to override and the LWC equivalent.

If you adopt one habit from this entire section, make it this one: **set a template at the top of each unit of work, then build every log from `Triton.t`.** It's the difference between logs that line up perfectly across your whole org and logs that *almost* match — and "almost" is worthless when you're filtering.

The builder itself (every method you can chain) is documented in [Core Concepts → The Builder & Templates](https://triton.pharos.ai/core-concepts/builder-and-templates). This page is about using it with discipline.

## The problem templates solve

Watch what happens without a template. Every log has to repeat the category and area, and the moment someone gets lazy or fat-fingers a value, your data quietly fragments:

{% code lineNumbers="true" %}

```apex
// Repetitive, and one typo away from an orphaned log
Triton.info(Triton.t.category(TritonTypes.Category.Apex).area(TritonTypes.Area.Accounts).summary('Fetched accounts'));
Triton.info(Triton.t.category(TritonTypes.Category.Apex).area(TritonTypes.Area.Accounts).summary('Recalculated rollups'));
Triton.error(Triton.t.category(TritonTypes.Category.Apex).area(TritonTypes.Area.Accounts).exception(e));
```

{% endcode %}

A template collapses the repetition to a single source of truth:

{% code lineNumbers="true" %}

```apex
// Set the shared shape once
Triton.setTemplate(Triton.makeBuilder()
    .category(TritonTypes.Category.Apex)
    .area(TritonTypes.Area.Accounts));

// ...then only say what's different about each log
Triton.info(Triton.t.summary('Fetched accounts'));
Triton.info(Triton.t.summary('Recalculated rollups'));
Triton.error(Triton.t.exception(e));
```

{% endcode %}

## How `Triton.t` actually works

`Triton.t` is shorthand for `Triton.fromTemplate()`. Each time you touch it, you get a **fresh clone** of the template with the current transaction id already stamped on. That cloning is the whole trick: the shared fields (category, area, any related object you baked in) come along, but per-log fields — summary, details, exception — never leak from one log into the next.

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t.summary('First'));    // fresh clone, summary = 'First'
Triton.info(Triton.t.summary('Second'));   // another fresh clone, summary = 'Second'
```

{% endcode %}

{% hint style="info" %}
**Set the template where the unit of work begins.** A trigger handler constructor, the top of a batch `execute`, the first line of an `@AuraEnabled` method. Because the template is static per-transaction, setting it once at the entry point means everything logged downstream inherits it — no passing anything around.
{% endhint %}

## `makeBuilder()` vs `t` — which do I use?

* **`Triton.t`** — your default. A clone of the template. Use it for essentially every log once a template is set.
* **`Triton.makeBuilder()`** — a plain builder pre-set to the `Apex` category, with *no* template fields. Use it to **build the template itself**, or for a genuine one-off that shouldn't inherit the current template.

{% code lineNumbers="true" %}

```apex
Triton.setTemplate(Triton.makeBuilder()      // makeBuilder to define the template
    .category(TritonTypes.Category.Apex)
    .area(TritonTypes.Area.OpportunityManagement));

Triton.info(Triton.t.summary('Using the template'));   // t for everything after
```

{% endcode %}

## Overriding — welcome, in moderation

A template is a starting point, not a straitjacket. Override any field on a per-log basis just by chaining it; the override wins:

{% code lineNumbers="true" %}

```apex
Triton.setTemplate(Triton.makeBuilder()
    .category(TritonTypes.Category.Apex)
    .area(TritonTypes.Area.Accounts)
    .relatedObject(accountId));

// This one log escalates to WARNING and points at a different record
Triton.warning(Triton.t
    .summary('Account flagged for manual review')
    .relatedObject(caseId));
```

{% endcode %}

{% hint style="warning" %}
**Don't override the classification fields casually.** Bumping the level or pointing one log at a different record is normal — `.relatedObject(...)` replaces the template's related records rather than adding to them. But if you find yourself overriding `category`/`type`/`area` all over a method, that's a sign the template is set at the wrong scope — split the method, or set a more specific template for the inner section.
{% endhint %}

## Do this / not that

{% hint style="success" %}
**Do**

* Set a template at the top of each unit of work.
* Build every log from `Triton.t`.
* Override only the fields that genuinely differ per log (summary, details, related objects, level).
* Use `.exception(e)` for errors instead of hand-setting type/summary/stack.
  {% endhint %}

{% hint style="danger" %}
**Don't**

* Rebuild the full classification on every call with `makeBuilder()` — that's what a template is for.
* Reach for `Triton.instance` — there is no instance in 2.0; the API is static.
* Reuse a builder across two logs — always start fresh from `Triton.t`.
  {% endhint %}

## The LWC equivalent

LWC has its own logger (a component-scoped instance you create with `new Triton().bindToComponent(...)`), but the template idea is identical: set it once in `connectedCallback`/`constructor`, then log from `fromTemplate()`.

{% code lineNumbers="true" %}

```javascript
import Triton, { TYPE, AREA, LEVEL } from 'c/triton';

export default class CaseConsole extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('caseConsole');

        // Component-scoped template
        this.triton.setTemplate(
            this.triton.makeBuilder()
                .type(TYPE.FRONTEND)
                .area(AREA.COMMUNITY)
                .level(LEVEL.INFO)
                .relatedObjects([this.recordId])
        );
    }

    async handleCreateCase() {
        try {
            const result = await createCase({ caseData: this.caseForm });
            this.triton.log(
                this.triton.fromTemplate()
                    .summary('Case created')
                    .relatedObjects([result.Id])
            );
        } catch (error) {
            // Template fields are preserved even on the error path
            this.triton.logNow(
                this.triton.fromTemplate()
                    .exception(error)
                    .summary('Case creation failed')
            );
        }
    }
}
```

{% endcode %}

The full LWC logger surface — binding, enums, and lifecycle timing — is covered in [Beyond Apex → LWC](https://triton.pharos.ai/beyond-apex/lwc).

## Related reading

* Every builder method, in detail: [Core Concepts → The Builder & Templates](https://triton.pharos.ai/core-concepts/builder-and-templates).
* Adding your own typed builder methods for custom fields: same page, [Custom attributes](https://triton.pharos.ai/core-concepts/builder-and-templates).


# Buffering & Flushing

The discipline that keeps you under platform-event limits without losing the logs that matter — buffer the routine, publish the critical, flush at boundaries.

Triton publishes logs as platform events, and Salesforce caps how many of those you can fire per transaction. Buffering is how you stay under that ceiling: queue logs in memory, then publish them together. The full mechanics — `flush`, `flushTop`, `drain`, and what happens when a publish fails — are in [Core Concepts → Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing). This page is the practical rule you actually apply.

## The one rule

**Buffer the routine. Publish the critical immediately. Flush at boundaries.**

That's it. Everything below is just that rule applied to specific situations.

Here's the shape it takes in almost every method you'll write:

{% code lineNumbers="true" %}

```apex
try {
    for (Account a : scope) {
        // ... work ...
        Triton.info(Triton.t.summary('Processed ' + a.Id));   // buffered — cheap
    }
    Triton.flush();   // publish the whole batch as one platform event
} catch (Exception e) {
    Triton.logNow(Triton.t.exception(e));   // never lose this one
}
```

{% endcode %}

The `Triton.info(...)` calls buffer. The single `Triton.flush()` publishes them all together. The exception goes out immediately via `logNow` so a mid-loop failure can't take your logs down with it.

{% hint style="info" %}
**Remember the 2.0 default flipped.** All the level methods — `Triton.info`, `Triton.error`, `Triton.warning`, and friends — **buffer**. You opt *into* immediate publishing with `Triton.logNow(...)`. If you're coming from 1.x, where bare `error(...)` published instantly, audit that assumption. See [Migrating from Triton 1.x to 2.0](https://triton.pharos.ai/migration).
{% endhint %}

## When to buffer

Buffer anything that's part of the normal, happy path and can safely wait until a flush:

* **Progress and milestones** — "step 1 done", "240 records processed".
* **Loop-body diagnostics** — per-record `FINE` logs where you'd otherwise fire hundreds of events.
* **Debug context** — the breadcrumbs you leave for your future self.

In a trigger over 200 records, buffering is the difference between **one** platform event and **two hundred**. This isn't a micro-optimization; it's the difference between a logging strategy that scales and one that gets switched off after the first governor-limit incident.

## When to publish immediately

Reach for `Triton.logNow(...)` when losing the log would hurt:

* **Exceptions you must not lose** — especially before a `throw` that ends the transaction.
* **Failures right before a risky operation** — a callout, a `Database.` operation, anything that might blow up and skip your flush.
* **The last thing you'll ever log in this path** — if there's no reliable flush after it, publish it now.

{% code lineNumbers="true" %}

```apex
try {
    chargeCard(payment);
} catch (Exception e) {
    Triton.logNow(Triton.t.area(TritonTypes.Area.OpportunityManagement).exception(e));
    throw e;   // safe — the log is already persisted
}
```

{% endcode %}

## Where to flush

Flush at the natural seams of your code, where you know the work is done and the transaction is still healthy:

* **End of a trigger handler.**
* **End of a batch `execute`** (each chunk is its own transaction — flush per chunk).
* **End of an `@AuraEnabled` method or REST handler.**
* **In a `finally` block**, when there's real risk of an exception between your logs and the flush.

{% hint style="warning" %}
**A buffered log that never flushes is a log you'll wish you had.** The classic bug: you buffer progress logs, then an exception fires before your `flush()` line, and the whole buffer evaporates. Two defenses — put the `flush()` in a `finally`, and publish anything genuinely critical with `logNow` the moment you create it.
{% endhint %}

## The `finally` pattern, in full

This is the shape worth memorizing for anything non-trivial:

{% code lineNumbers="true" %}

```apex
public static void processPayment(Id accountId, Decimal amount) {
    Long startTime = System.now().getTime();
    Triton.setTemplate(Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .area(TritonTypes.Area.OpportunityManagement)
        .relatedObject(accountId));

    Triton.debug(Triton.t.summary('Payment started').details('amount=' + amount));   // buffered

    try {
        HttpResponse res = callGateway(accountId, amount);
        if (res.getStatusCode() == 200) {
            Payment__c p = new Payment__c(Account__c = accountId, Amount__c = amount, Status__c = 'Completed');
            insert p;
            Triton.info(Triton.t                                   // buffered
                .summary('Payment processed')
                .relatedObject(p.Id)
                .duration(System.now().getTime() - startTime));
        } else {
            Triton.logNow(Triton.t                                 // published now
                .warning()
                .summary('Payment gateway returned ' + res.getStatusCode()));
        }
    } catch (Exception e) {
        Triton.logNow(Triton.t.exception(e));                      // published now
        throw e;
    } finally {
        Triton.flush();   // guarantees the buffered logs go out, success or failure
    }
}
```

{% endcode %}

## What Triton handles for you

Two things you don't have to manage:

* **A failed publish never fails your code.** `log`, the level methods, `logNow`, `flush`, and `flushTop` catch their own failures: if Pharos refuses a publish, those logs are dropped and the failure is noted in the Apex debug log. There's no automatic throttling, so the rule above — buffer, then flush in bulk — is what keeps you inside your platform-event allocation.
* **`drain()` for very high-volume producers.** Flows that would burn allocations inline hand their buffer to a batch that publishes later. You rarely call `drain()` in Apex yourself; it powers the Flow flush batch. See [Core Concepts → Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).

## Async: each execution is its own transaction

In Batch and Queueable, statics reset between executions — so the buffer doesn't carry across chunks. Flush **within** each `execute` (typically at the end), not once at the very end of the job. The [Batch Logging](https://triton.pharos.ai/common-apex-usage-patters/batch-logging) pattern shows this in context.

## Related reading

* The methods, and what happens when a publish fails, in depth: [Core Concepts → Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).
* Applying the pattern per context: [Implementation Patterns](https://triton.pharos.ai/triton-best-practices/implementation-patterns).


# Transaction Management

Stitching logs from LWC, Apex, and Flow into a single trace — starting, resuming, and stopping transactions, and passing the id versus using platform cache.

A transaction id is the thread that ties otherwise-disconnected logs into one story. Without it, a user clicking "Convert" produces an LWC log here, an Apex log there, and a Flow log somewhere else — three records you have to correlate by hand, by timestamp, at 2am. With it, they're one trace you read top to bottom.

Triton keeps a transaction id as static state for the life of an Apex transaction, and gives you three verbs to manage it — `startTransaction`, `resumeTransaction`, `stopTransaction` — plus `withCache` for the hands-off approach. This page is about using them across boundaries.

## The three verbs

* **`Triton.startTransaction()`** — mint a fresh correlation id and return it. Call this at a true entry point (a user action, a scheduled job kicking off).
* **`Triton.resumeTransaction(id)`** — adopt an id that was created elsewhere. This is how a hop *joins* an existing trace.
* **`Triton.stopTransaction()`** — clear the id at the end of the unit of work.

{% code lineNumbers="true" %}

```apex
String txId = Triton.startTransaction();   // begin a trace
// ... log some things — they all carry txId ...
Triton.stopTransaction();                  // end it
```

{% endcode %}

{% hint style="info" %}
**You don't always need to start one explicitly.** Within a single Apex transaction, logs already share static state and correlate fine on their own. Explicit transaction management earns its keep when you're crossing a boundary — LWC → Apex, Apex → Flow, or one async hop to the next — where the static state would otherwise reset.
{% endhint %}

## The pattern: start at the edge, resume on each hop, stop at the end

The rule of thumb:

1. **Start** the transaction at the outermost entry point (usually the LWC, or the first Apex if there's no UI).
2. **Carry** the id across each boundary and **resume** it on the other side.
3. **Stop** it when the top-level unit of work finishes.

## Crossing LWC → Apex

Two ways to move the id across the wire. Pick based on how complex the flow is.

### Approach 1 — pass the id explicitly

The most explicit and the easiest to debug. Start the transaction in the LWC, read `triton.transactionId`, and pass it as a method parameter. On the Apex side, resume it.

{% code lineNumbers="true" %}

```javascript
// opportunityList.js
import loadOpps from '@salesforce/apex/OppController.loadOpps';
import Triton, { TYPE, AREA } from 'c/triton';

export default class OpportunityList extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('opportunityList');
        this.triton.startTransaction();
        this.triton.setTemplate(
            this.triton.makeBuilder()
                .type(TYPE.FRONTEND)
                .area(AREA.OPPORTUNITY_MANAGEMENT)
                .relatedObjects([this.recordId])
        );
    }

    async loadData() {
        try {
            // Hand the transaction id to Apex
            const data = await loadOpps({
                accountId: this.recordId,
                txId: this.triton.transactionId
            });
            this.triton.log(this.triton.fromTemplate().summary(`Rendered ${data.length} opportunities`));
        } catch (error) {
            this.triton.logNow(this.triton.fromTemplate().exception(error).summary('Failed to load opportunities'));
        }
    }

    disconnectedCallback() {
        this.triton.stopTransaction();
    }
}
```

{% endcode %}

{% code lineNumbers="true" %}

```apex
// OppController.cls
public with sharing class OppController {
    @AuraEnabled(cacheable=false)
    public static List<Opportunity> loadOpps(Id accountId, String txId) {
        // Join the trace the LWC started
        if (String.isNotBlank(txId)) {
            Triton.resumeTransaction(txId);
        } else {
            Triton.startTransaction();
        }

        Triton.setTemplate(Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .area(TritonTypes.Area.OpportunityManagement)
            .relatedObject(accountId));

        try {
            List<Opportunity> opps = [SELECT Id, Name, Amount FROM Opportunity WHERE AccountId = :accountId LIMIT 200];
            Triton.info(Triton.t.summary('Loaded opportunities').details('count=' + opps.size()));
            return opps;
        } catch (Exception e) {
            Triton.logNow(Triton.t.exception(e));
            throw e;
        } finally {
            Triton.flush();
        }
    }
}
```

{% endcode %}

### Approach 2 — let platform cache carry it

For complex UIs with many components and async calls, threading a `txId` parameter through everything gets tedious. `Triton.withCache()` backs the transaction id with platform cache, so Apex can pick up the LWC's id automatically — no parameter required.

{% code lineNumbers="true" %}

```apex
@AuraEnabled
public static void doWork() {
    Triton.withCache();   // resumes the cached transaction id if one exists, else starts one
    Triton.setTemplate(Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .area(TritonTypes.Area.Community));
    // ... logs here automatically join the LWC's trace ...
    Triton.flush();
}
```

{% endcode %}

The trade-offs and setup are covered in [Beyond Apex → Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache). Quick guidance:

| Use explicit passing when…               | Use `withCache()` when…                                     |
| ---------------------------------------- | ----------------------------------------------------------- |
| The path is simple and linear            | Many components / async calls make passing an id cumbersome |
| You want maximum clarity while debugging | You'd rather not thread a parameter everywhere              |
| You're just getting started              | Platform cache is available and configured in the org       |

## Crossing Apex → Flow

Flow correlation is largely automatic. When Apex commits a DML that fires an autolaunched Flow, and the Flow's **Log** actions pass `$Flow.InterviewGuid`, Triton groups the Flow's logs under the same transaction — and even attaches any **unhandled** Flow exception to the trace with no extra code. Always pass `$Flow.InterviewGuid` on every Flow log action. The full walkthrough (LWC → Apex → Flow, both approaches) is in [End-to-End Logging](https://triton.pharos.ai/end-to-end).

## Async hops: Queueable, Batch, Future

Each async execution is a *new* Apex transaction with fresh statics — so the id doesn't ride along automatically. If you want a chained job to stay on the same trace, capture the id before enqueuing and resume it inside:

{% code lineNumbers="true" %}

```apex
public class ChainedJob implements Queueable {
    private final String txId;
    public ChainedJob(String txId) { this.txId = txId; }

    public void execute(QueueableContext qc) {
        Triton.resumeTransaction(txId);   // rejoin the originating trace
        Triton.setTemplate(Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .area(TritonTypes.Area.OpportunityManagement));
        try {
            // ... work ...
            Triton.info(Triton.t.summary('Chained job done'));
        } finally {
            Triton.flush();
        }
    }
}

// Enqueue with the current trace id so the job stays correlated
System.enqueueJob(new ChainedJob(Triton.TRANSACTION_ID));
```

{% endcode %}

## What good looks like

Done right, one user action reads as one tree in Pharos:

{% code lineNumbers="true" %}

```
Transaction: 7fb8c320-e8f9-4f1b-9742-1a5768b9e0d2
├── LWC log (button clicked)
├── Apex log (DML performed)
└── Flow execution
    ├── Flow start
    ├── Flow operation
    └── Unhandled Flow error (auto-captured)
```

{% endcode %}

{% hint style="warning" %}
**Always stop what you start, and flush before you stop.** Leaving a transaction open risks bleeding context into unrelated work if statics are reused; forgetting to flush first loses buffered logs. In LWC, `stopTransaction()` in `disconnectedCallback` flushes remaining logs for you — but in Apex, put your `flush()` before `stopTransaction()` (a `finally` block is the safe home for both).
{% endhint %}

## Related reading

* End-to-end walkthrough across all three layers: [End-to-End Logging](https://triton.pharos.ai/end-to-end).
* Cache-backed correlation setup: [Beyond Apex → Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache).
* LWC-side transaction details: [Beyond Apex → LWC Transaction Management](https://triton.pharos.ai/beyond-apex/lwctransaction).


# Implementation Patterns

Copy-ready logging patterns for the contexts you actually work in — triggers, queueables, batches, REST, schedulers, LWC, and Flow — all on the 2.0 static API.

The principles from the earlier pages are the same everywhere; what changes is where the "unit of work" begins and ends and where you can safely flush. This page walks the contexts you'll actually meet, each as a small, correct, copy-ready pattern on the 2.0 static, builder-first API.

## Where logs go, regardless of context

Before the specifics, the general skeleton. In any unit of work, you want logs at:

* **Entry** — start/resume the transaction, set the template, log intent at `INFO`.
* **Milestones** — key steps with counts and durations (`INFO`/`DEBUG`).
* **Decision points** — which branch you took (`DEBUG`/`FINE`).
* **External calls** — before/after callouts, with a sanitized payload.
* **Errors** — `.exception(e)`, published immediately with `logNow`.
* **Exit** — a result summary, then `flush()` (ideally in `finally`).

## Trigger handler

Set the template in the handler entry point. You don't need to hand-capture the trigger operation or timestamp — for Apex logs, Triton stamps the execution context (operation type, sObject, batch size) automatically.

{% code lineNumbers="true" %}

```apex
public with sharing class AccountTriggerHandler {
    public static void beforeUpdate(List<Account> newList, Map<Id, Account> oldMap) {
        Triton.setTemplate(Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .type(TritonTypes.Type.AccountTrigger)
            .area(TritonTypes.Area.Accounts));

        Set<Id> scopeIds = new Map<Id, Account>(newList).keySet();

        Triton.info(Triton.t
            .summary('Account before update')
            .details('count=' + scopeIds.size())
            .relatedObjects(scopeIds));

        // ... handler logic ...

        Triton.flush();   // triggers are their own transaction — flush before you exit
    }
}
```

{% endcode %}

## Queueable

An async job is a fresh transaction. If it's part of a larger trace, resume the id you were constructed with; otherwise start one. Flush in `finally`.

{% code lineNumbers="true" %}

```apex
public class PriceSyncQueueable implements Queueable, Database.AllowsCallouts {
    private final Set<Id> productIds;
    private final String txId;

    public PriceSyncQueueable(Set<Id> productIds, String txId) {
        this.productIds = productIds;
        this.txId = txId;
    }

    public void execute(QueueableContext qc) {
        if (String.isNotBlank(txId)) Triton.resumeTransaction(txId);
        else Triton.startTransaction();

        Triton.setTemplate(Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .area(TritonTypes.Area.OpportunityManagement)
            .relatedObjects(productIds));

        Long started = System.now().getTime();
        try {
            // ... callouts and DML ...
            Triton.info(Triton.t
                .summary('Price sync complete')
                .details('synced=' + productIds.size())
                .duration(System.now().getTime() - started));
        } catch (Exception e) {
            Triton.logNow(Triton.t.exception(e));
            throw e;
        } finally {
            Triton.flush();
            Triton.stopTransaction();
        }
    }
}
```

{% endcode %}

## Batchable

The key subtlety: **`start`, each `execute`, and `finish` are separate transactions**, so statics — the buffer, the transaction id, and the template — start empty in each. Flush inside every chunk, re-establish the transaction id and the template at the top of every method, and carry the id across chunks in a `Database.Stateful` field. Take the caller's id in the constructor, but only store it there: the constructor runs in the caller's transaction, so `startTransaction()` there would overwrite the caller's id.

{% code lineNumbers="true" %}

```apex
global class LeadQualifyBatch implements Database.Batchable<SObject>, Database.Stateful {
    private String txId;   // the caller's transaction id, carried across chunks by Database.Stateful

    global LeadQualifyBatch(String txId) {
        this.txId = txId;  // store only: the constructor runs in the caller's transaction
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        if (String.isBlank(txId)) {
            txId = Triton.startTransaction();
        } else {
            Triton.resumeTransaction(txId);
        }
        setTemplate();
        Triton.info(Triton.t.summary('Lead qualify started'));
        Triton.flush();
        return Database.getQueryLocator([SELECT Id, Status FROM Lead WHERE IsConverted = FALSE]);
    }

    global void execute(Database.BatchableContext bc, List<Lead> scope) {
        Triton.resumeTransaction(txId);   // a new transaction: statics start empty
        setTemplate();
        Long t0 = System.now().getTime();
        try {
            // ... work ...
            Triton.info(Triton.t
                .summary('Executed batch chunk')
                .details('size=' + scope.size())
                .duration(System.now().getTime() - t0)
                .relatedObjects(new Map<Id, Lead>(scope).keySet()));
        } catch (Exception e) {
            Triton.error(Triton.t
                .exception(e)
                .relatedObjects(new Map<Id, Lead>(scope).keySet()));
            // continue or rethrow per your design
        } finally {
            Triton.flush();   // publish this chunk's logs before the next transaction
        }
    }

    global void finish(Database.BatchableContext bc) {
        Triton.resumeTransaction(txId);
        setTemplate();
        Triton.info(Triton.t.summary('Lead qualify finished'));
        Triton.flush();
        Triton.stopTransaction();
    }

    private static void setTemplate() {
        Triton.setTemplate(Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .area(TritonTypes.Area.LeadConversion));
    }
}

// The caller passes its own transaction id
Database.executeBatch(new LeadQualifyBatch(Triton.TRANSACTION_ID));
```

{% endcode %}

For a deeper treatment (stateful buffering, log grouping across chunks), see [Common Apex Usage → Batch Logging](https://triton.pharos.ai/common-apex-usage-patters/batch-logging).

## REST resource

Callout-style entry point. It's still an ordinary `Apex` log — what makes it an integration log is the request/response payload you attach with `.integrationPayload(...)`, which accepts `RestRequest`/`RestResponse` directly.

{% code lineNumbers="true" %}

```apex
@RestResource(urlMapping='/api/accounts/*')
global with sharing class AccountRestAPI {
    @HttpGet
    global static void getAccount() {
        Triton.startTransaction();
        Triton.setTemplate(Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .area(TritonTypes.Area.RestAPI));

        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        try {
            String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
            // ... process ...
            Triton.info(Triton.t
                .summary('REST GET handled')
                .relatedObject(accountId)
                .integrationPayload(req, res));
        } catch (Exception e) {
            Triton.logNow(Triton.t.exception(e).integrationPayload(req, res));
            throw e;
        } finally {
            Triton.flush();
            Triton.stopTransaction();
        }
    }
}
```

{% endcode %}

More on integration logging: [Common Apex Usage → Apex Rest Logging](https://triton.pharos.ai/common-apex-usage-patters/apex-rest-logging) and [Integration Logs](https://triton.pharos.ai/common-apex-usage-patters/integration-logs).

## Scheduled job

{% code lineNumbers="true" %}

```apex
global class DataSyncScheduler implements Schedulable {
    global void execute(SchedulableContext sc) {
        Triton.startTransaction();
        Triton.setTemplate(Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .area(TritonTypes.Area.OpportunityManagement));
        try {
            Triton.info(Triton.t.summary('Data sync scheduled job started'));
            // ... enqueue / sync ...
            Triton.info(Triton.t.summary('Data sync scheduled job completed'));
        } catch (Exception e) {
            Triton.logNow(Triton.t.exception(e));
            throw e;
        } finally {
            Triton.flush();
            Triton.stopTransaction();
        }
    }
}
```

{% endcode %}

## LWC — with `@wire`

For components with `@wire`, initialize in the constructor so early wire callbacks are captured. Log both the success and error branches.

{% code lineNumbers="true" %}

```javascript
import Triton, { TYPE, AREA } from 'c/triton';
import getCases from '@salesforce/apex/CaseController.getCases';
import { wire } from 'lwc';

export default class CaseList extends LightningElement {
    triton;

    constructor() {
        super();
        this.triton = new Triton().bindToComponent('caseList');
        this.triton.setTemplate(
            this.triton.makeBuilder().type(TYPE.FRONTEND).area(AREA.COMMUNITY)
        );
    }

    @wire(getCases, { contactId: '$recordId' })
    wiredCases({ data, error }) {
        if (data) {
            this.triton.log(
                this.triton.fromTemplate()
                    .summary(`Wire loaded ${data.length} cases`)
                    .relatedObjects([this.recordId])
            );
        } else if (error) {
            this.triton.logNow(
                this.triton.fromTemplate()
                    .exception(error)
                    .summary('Wire error loading cases')
                    .relatedObjects([this.recordId])
            );
        }
    }
}
```

{% endcode %}

## LWC — imperative

{% code lineNumbers="true" %}

```javascript
async loadOrders() {
    try {
        const data = await loadOrders({ accountId: this.recordId, txId: this.triton.transactionId });
        this.triton.log(this.triton.fromTemplate().summary(`Orders loaded: ${data.length}`));
    } catch (e) {
        await this.triton.logNow(this.triton.fromTemplate().exception(e).summary('Load orders failed'));
    }
}
```

{% endcode %}

The transaction is established when the component binds Triton; handlers never start or stop it.

The LWC logger surface and lifecycle guidance live in [Beyond Apex → LWC](https://triton.pharos.ai/beyond-apex/lwc).

## Flow

Flow logging is declarative: drop the Triton **Log** invocable action at the points that matter. The principles carry straight over — log at the start, at decisions, around DML/callouts, and in fault paths.

The two rules that make Flow logging pay off:

* **Always pass `$Flow.InterviewGuid`** to every **Log** action. It's what groups a Flow's logs together and lets Triton attach any unhandled Flow exception to the same trace automatically.
* **Use constants and text templates** for `Area`/`Category`/`Type` and for detail strings, so a taxonomy change is a one-place edit.

The complete Flow setup — configuring parameters, naming conventions, additional fields — is in [Beyond Apex → Flows](https://triton.pharos.ai/flows).

## How logs reach Pharos

A couple of things worth knowing about the plumbing behind these patterns:

* **Platform events.** Buffered Apex logs publish as a batch of platform events on `flush()`. There's no automatic throttling, so flush in bulk at boundaries. A publish Pharos refuses is dropped and noted in the Apex debug log rather than thrown into your code.
* **Issue creation.** `.exception(e)` (and `.error()`) flag the log for **Pharos Issue** creation. That's exactly what you want for genuine failures — and exactly what you *don't* want on routine warnings, or you'll create alert fatigue. Reserve issue-flagging (i.e., error-level exception logs and explicit `.createIssue()`) for things a human should triage. Downgrading an exception log — `Triton.warning(Triton.t.exception(e))` — keeps the detail and withdraws the issue.
* **LWC bridge.** LWC logs batch to the server via an `@AuraEnabled` bridge; the same buffer-then-flush discipline applies, with `logNow` for the ones you can't lose.

## Related reading

* The buffer/flush discipline these patterns rely on: [Buffering & Flushing](https://triton.pharos.ai/triton-best-practices/buffering-and-flushing).
* Correlating them across boundaries: [Transaction Management](https://triton.pharos.ai/triton-best-practices/transaction-management).
* Making each log carry enough context: [Context & Related Objects](https://triton.pharos.ai/triton-best-practices/context-and-related-objects).


# 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). 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) and [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing).

## 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) and the [TritonBuilder reference](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder).
* Turning exceptions into rich error logs: [Exception Handling](https://triton.pharos.ai/triton-best-practices/exception-handling).


# Taxonomy & Standards

Designing a Category / Type / Area vocabulary that scales — what each field is for, the values that ship, and how to extend them without fragmenting your data.

Three fields classify every Triton log — **Category**, **Type**, and **Area** — and they're what turn a pile of records into something you can filter, group, alert on, and learn from. A good taxonomy is boring on purpose: everyone uses the same small vocabulary, so every dashboard lines up. This page is about designing that vocabulary for your org. The mechanics of the enums live in [Core Concepts → Enums](https://triton.pharos.ai/core-concepts/enums).

## The three fields, and what each is *for*

They're not interchangeable — each answers a different question.

| Field        | Answers                                  | Perspective      | Affects rendering?                                    |
| ------------ | ---------------------------------------- | ---------------- | ----------------------------------------------------- |
| **Category** | What technology produced this?           | Technical, broad | **Yes** — Pharos picks the layout/detail view from it |
| **Type**     | What kind of operation, specifically?    | Technical, fine  | No                                                    |
| **Area**     | What part of the business is this about? | Business         | No                                                    |

The Category caveat matters: because it drives which detail view renders, mislabeling an Apex log as `Flow` still captures your data but shows you the wrong debug view. **Match Category to the technology you're logging from** — `Apex` from Apex, `LWC` from a component, `Flow` from a Flow. A callout is no exception: it's still an `Apex` log — what makes it an *integration* log is the request/response you attach with `.integrationPayload(...)`, not a separate category. (`Triton.makeBuilder()` starts you on `Apex` already.)

The same discipline applies to severity: **it never belongs in Category.** A warning logged from Apex is an `Apex` log at the `WARNING` **Level**, not a "warning" category — severity lives in the log's [Level](https://triton.pharos.ai/core-concepts/log-levels) and the Log Level rules that filter on it. Every log has a knowable origin technology, so Category always has a real answer; keep it that way.

## The values that ship

Straight from `TritonTypes` — use these before inventing anything.

**Category:** `Apex` · `Flow` · `LWC` · `Aura`

**Type:** `Backend` · `Frontend` · `DMLResult` · `LongRunningRequest` · `ConcurrentRequestsLimit` · `AccountTrigger` · `BackendCall` · `ComponentLifecycle` · `ComponentRender` · `UserInteraction` · `Performance`

**Area:** `OpportunityManagement` · `LeadConversion` · `Community` · `RestAPI` · `Accounts` · `LWC` · `Flow`

Area is deliberately thin — it's the most org-specific of the three, and you're **expected** to add your own.

## Adding your own values — the right way

Don't edit `TritonTypes.cls` to add values. It's a Triton file: the next upgrade overwrites your additions, or leaves you resolving merge conflicts every time. `type(...)` and `area(...)` accept plain strings, so keep your org's vocabulary in a class of `public static final String` constants that you own:

{% code lineNumbers="true" %}

```apex
public class TritonArea {
    public static final String PAYMENT_PROCESSING = 'PaymentProcessing';
    public static final String CREDIT_SCORING = 'CreditScoring';
    public static final String INVOICE_SYNC = 'InvoiceSync';
    public static final String CUSTOMER_ONBOARDING = 'CustomerOnboarding';
}
```

{% endcode %}

Then use it like any shipped value:

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t.area(TritonArea.INVOICE_SYNC).summary('Invoice pushed to ERP'));
```

{% endcode %}

{% hint style="info" %}
**Constants, not scattered literals.** A constant gives you autocomplete, one place to see the whole vocabulary, and no risk of `'InvoiceSync'` vs `'Invoice_Sync'` drift. Flows and LWCs pass the same string (`InvoiceSync`) through their Area input and `.area(...)`, so a feature groups together across all three tiers. The full pattern is in [Custom Classifications](https://triton.pharos.ai/core-concepts/custom-classifications).
{% endhint %}

## Designing Area so it stays useful

Area is where most teams either succeed or make a mess. A few rules that keep it healthy:

* **Name for features and domains, not tables.** `DealRegistration`, `PartnerCommunity`, `InvoiceSync` — the things you'd actually want to filter or alert on. Not `Trigger1` or `Utils`.
* **Pick a granularity you'd filter at.** Too coarse (`Backend`) and everything lands in one bucket; too fine (one per method) and no two logs share a value. Aim for "a feature a product owner would recognize."
* **Add sparingly and deliberately.** Every new Area is a commitment the whole org has to honor. Grow it on purpose, not by reflex.
* **Business-oriented and stable.** Areas should outlive refactors. If renaming a class forces an Area rename, the Area was too technical.

## Mapping your work to the taxonomy

A quick reference for how common work classifies. Extend the Area column for your own domains.

| Work                      | Category | Type             | Area                  |
| ------------------------- | -------- | ---------------- | --------------------- |
| Lead conversion service   | `Apex`   | `Backend`        | `LeadConversion`      |
| Account trigger           | `Apex`   | `AccountTrigger` | `Accounts`            |
| Bulk DML outcome          | `Apex`   | `DMLResult`      | *(your domain)*       |
| Payment gateway callout   | `Apex`   | `Backend`        | `PaymentProcessing`\* |
| Customer portal component | `LWC`    | `Frontend`       | `Community`           |
| REST endpoint             | `Apex`   | `Backend`        | `RestAPI`             |
| Autolaunched Flow         | `Flow`   | *(flow type)*    | *(your domain)*       |

\* `PaymentProcessing` is an example of an org-specific Area you'd keep in your own constants class (`TritonArea.PAYMENT_PROCESSING`).

## Governance without bureaucracy

A taxonomy is only worth having if it stays consistent, and that takes a little upkeep — not a committee.

* **One owner (or a small group).** Someone signs off on new Category/Type/Area values so the vocabulary doesn't sprawl.
* **Document as you go.** A short living list of your custom Areas and what each means, so a new hire uses the existing value instead of inventing a synonym.
* **Enforce in review.** The [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement) checklist catches ad-hoc strings and off-taxonomy values before they merge.

{% hint style="success" %}
**The whole point is that everyone uses the same words.** A perfectly-designed taxonomy that half the team ignores is worse than a simple one everyone follows. Keep it small, document it, and enforce it lightly but consistently.
{% endhint %}

## Related reading

* Enum mechanics and how filtering uses these same three fields: [Core Concepts → Enums](https://triton.pharos.ai/core-concepts/enums).
* Keeping the taxonomy clean over time: [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement).


# Exception Handling

Turning caught exceptions into actionable, correlated error logs — the one-call pattern, partial-DML results, and when to publish now or create an issue.

Error logging is where a logging framework earns its keep. When something breaks in production, the quality of your exception logs decides whether the fix takes five minutes or five hours. Triton makes doing it right almost effortless — the trick is knowing the one call that does the work, and the handful of judgment calls around it.

## The entire pattern: `.exception(e)`

You almost never hand-assemble an error log. `.exception(e)` does all of it in one call — 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.logNow(Triton.t.area(TritonTypes.Area.OpportunityManagement).exception(e));
    throw e;
}
```

{% endcode %}

That's it. Set the area (or let a template do it), pass the exception, publish it, rethrow. Everything else is handled.

{% hint style="info" %}
**Don't spell out what `.exception(e)` already does.** Setting `.level(ERROR)`, `.type(...)`, `.summary(e.getMessage())`, and `.stackTrace(...)` by hand is redundant — and easy to get subtly wrong. Pass the exception and let the builder do it. If you want to add context, chain `.details(...)` or `.relatedObject(...)` *in addition*.
{% endhint %}

## Buffer or publish?

For errors, the answer is usually **publish immediately with `logNow`** — because the very next line is often a `throw` that ends the transaction and would take a buffered log down with it.

* **`Triton.logNow(Triton.t.exception(e))`** — the default for a real failure. Persisted before anything else can go wrong.
* **`Triton.error(Triton.t.exception(e))`** — buffers at ERROR. Fine when you're confident a `flush()` will run (e.g. a batch chunk's `finally`) and you're batching several logs together.

When in doubt, `logNow`. A lost error log is the worst kind to lose.

## Add context, then get out of the way

`.exception(e)` captures the technical picture; you add the business picture:

{% code lineNumbers="true" %}

```apex
try {
    updateAccount(accountId, payload);
} catch (Exception e) {
    Triton.logNow(Triton.t
        .area(TritonTypes.Area.Accounts)
        .exception(e)
        .relatedObject(accountId)          // which record
        .details('operation=update'));     // what we were doing
    throw e;
}
```

{% endcode %}

## Catch specifically when you'll act differently

If different exception types warrant different handling, catch them separately — but the logging call is the same shape each time. Let the exception's own type flow through; don't override it.

{% code lineNumbers="true" %}

```apex
try {
    processRecord(recordId);
} catch (DmlException e) {
    Triton.logNow(Triton.t.area(TritonTypes.Area.Accounts).exception(e).relatedObject(recordId));
    // ...DML-specific recovery...
} catch (CalloutException e) {
    Triton.logNow(Triton.t.area(TritonTypes.Area.RestAPI).exception(e).relatedObject(recordId));
    // ...retry / fallback...
} catch (Exception e) {
    Triton.logNow(Triton.t.area(TritonTypes.Area.Accounts).exception(e).relatedObject(recordId));
    throw e;
}
```

{% endcode %}

Note the Type field will read `DmlException`, `CalloutException`, etc. automatically — that's `.exception(e)` doing its job, and it makes filtering by failure kind trivial.

## Partial DML: use `.dmlResults(...)`, not a hand-rolled loop

For allow-partial DML (`Database.insert(records, false)`), don't loop over the results assembling a failure string. Pass the results straight to the builder — it tallies successes and failures, collects the failed ids as related objects, formats the messages, sets Type to `DMLResult`, writes a failure-count summary, and sets ERROR with an issue. When every row succeeded, nothing is logged at all — no `if` needed.

{% 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`. Passing it to `Triton.warning(...)`, as here, records expected partial failures at WARNING without opening an issue; use `Triton.error(...)` or `Triton.logNow(...)` when a failed row needs triage.

## Errors around callouts

Attach the sanitized payload so you can see what actually went over the wire:

{% code lineNumbers="true" %}

```apex
HttpRequest req = buildRequest(endpoint, payload);
try {
    HttpResponse res = new Http().send(req);
    if (res.getStatusCode() != 200) {
        Triton.logNow(Triton.t
            .area(TritonTypes.Area.RestAPI)
            .warning()
            .summary('Callout returned ' + res.getStatusCode())
            .integrationPayload(req, res));   // sanitize first
    }
} catch (CalloutException e) {
    Triton.logNow(Triton.t
        .area(TritonTypes.Area.RestAPI)
        .exception(e)
        .integrationPayload(req, null));
    throw e;
}
```

{% endcode %}

## Issue creation — deliberate, not automatic-everywhere

`.exception(e)` and `.error()` flag the log for **Pharos Issue** creation, which is exactly right for genuine failures a human should triage. But that's a double-edged sword: flag every recoverable hiccup and you get alert fatigue, and real incidents drown in noise.

{% hint style="warning" %}
**Reserve issue creation for things worth waking someone for.** Genuine, user-impacting failures → `ERROR` via `.exception(e)` (issue flagged, as you want). Recoverable, expected conditions (a retry that succeeded, a fallback path) → `WARNING`, which does **not** flag an issue — even when you log the exception itself: `Triton.warning(Triton.t.exception(e))` keeps the exception detail and withdraws the issue `.exception(e)` would otherwise open. You can also opt in explicitly with `.createIssue()`, which stands at any level.
{% endhint %}

## LWC exceptions

Same idea, LWC logger. `.exception(error)` — on `this.triton` or on any builder — builds an `ERROR` log, with an issue, from a JS `Error`; publish it immediately with `logNow`. `logNow` never rejects, so awaiting it inside a `catch` is safe.

{% code lineNumbers="true" %}

```javascript
async handleSave() {
    try {
        const result = await saveRecord({ recordId: this.recordId, data: this.formData });
        this.triton.log(this.triton.fromTemplate().summary('Record saved').relatedObjects([result.Id]));
    } catch (error) {
        await this.triton.logNow(
            this.triton.fromTemplate()
                .exception(error)
                .summary('Save failed')
        );
        this.showError('Something went wrong. Support has been notified.');
    }
}
```

{% endcode %}

Wire errors deserve the same treatment — log the `error` branch of every `@wire` callback. See [Beyond Apex → LWC](https://triton.pharos.ai/beyond-apex/lwc).

## Don't swallow

Logging an exception is not the same as handling it. If the design doesn't genuinely recover from the failure, **rethrow after logging** — otherwise you've hidden a broken operation behind a log entry, and the caller carries on as if nothing happened.

{% code lineNumbers="true" %}

```apex
} catch (Exception e) {
    Triton.logNow(Triton.t.exception(e));
    throw e;   // don't leave this out unless recovery is intentional
}
```

{% endcode %}

## Related reading

* What `.exception(e)` and `.dmlResults(...)` set, field by field: [Core Concepts → The Builder & Templates](https://triton.pharos.ai/core-concepts/builder-and-templates).
* Why errors go out with `logNow`: [Buffering & Flushing](https://triton.pharos.ai/triton-best-practices/buffering-and-flushing).


# Standards Enforcement

Keeping logging standards from rotting on a growing team — a short review checklist, CI guardrails for common regressions, and testing that logs get written.

Standards that live only in a wiki page decay the moment the team gets busy. The ones that stick are the ones a machine checks and a reviewer glances at. This page is the practical layer: a review checklist short enough that people actually use it, a few CI guardrails that catch the regressions that matter, and how to test your logging.

## The review checklist

Keep it short or it won't get used. These are the things worth a reviewer's eyes on any PR that logs:

* **Template set, `Triton.t` used.** Shared fields (category/area) come from a template, not repeated by hand.
* **Real taxonomy.** Category/Type/Area are enum values, not ad-hoc strings; new domains were added to the enum, not smuggled in as text.
* **Honest levels.** `ERROR` only for genuine failures; loop chatter at `FINE` or below; nothing gated behind `if (debug)`.
* **Exceptions logged with `.exception(e)`** and published (`logNow` on the failure path), then rethrown unless recovery is intentional.
* **Flush coverage.** Every path that buffers also flushes — end of handler/execute, or a `finally`.
* **Context present.** Related objects on logs that concern records; durations on work worth trending; sanitized payloads on callouts.
* **Transactions correlated.** Cross-boundary work starts/resumes/stops a transaction; LWC passes the id (or uses cache).
* **No `System.debug`, no `Triton.instance`.** The first is invisible telemetry; the second is the removed 1.x singleton.

{% hint style="info" %}
**Two of these are non-negotiable and cheap to automate:** no `System.debug` in application code, and no `Triton.instance` anywhere (it doesn't exist in 2.0 — its presence means un-migrated code). Put both in CI so no reviewer has to remember them.
{% endhint %}

## CI guardrails

You don't need a heavyweight ruleset — a handful of targeted checks catch the regressions that actually happen. Start with grep-level checks in your pipeline; graduate to PMD when you want structure.

### Grep-level checks (fast, zero setup)

{% code lineNumbers="true" %}

```bash
# Fail the build on System.debug in application code (allow it in tests if you like)
if grep -rn "System.debug" force-app/main --include=*.cls | grep -v "Test.cls"; then
  echo "❌ System.debug found — use Triton logging instead."
  exit 1
fi

# Fail on any lingering 1.x singleton usage
if grep -rn "Triton\.instance" force-app/main --include=*.cls; then
  echo "❌ Triton.instance is 1.x — migrate to the static API (Triton.log/Triton.t)."
  exit 1
fi
```

{% endcode %}

### PMD rules

If you run PMD, encode the same two rules so they show up in the same report as the rest of your static analysis:

{% code lineNumbers="true" %}

```xml
<rule name="NoSystemDebug" language="apex"
      message="Use Triton logging, not System.debug"
      class="net.sourceforge.pmd.lang.rule.regex.RegexRule" severity="3">
  <properties>
    <property name="regex" value="System\.debug\s*\(" />
  </properties>
</rule>

<rule name="NoTritonInstance" language="apex"
      message="Triton.instance is the removed 1.x singleton — use the static API"
      class="net.sourceforge.pmd.lang.rule.regex.RegexRule" severity="3">
  <properties>
    <property name="regex" value="Triton\.instance" />
  </properties>
</rule>
```

{% endcode %}

### Higher-value checks (worth building once)

Regex can't see intent, but a couple of custom rules pay off:

* **Ad-hoc taxonomy strings.** Flag `.area('...')` / `.type('...')` string literals where an enum value exists, to catch drift before it fragments your data.
* **Caught-but-not-logged.** Flag `catch` blocks with no Triton call — the most common way errors go dark.
* **Positive coverage.** Require at least one Triton log in `@AuraEnabled` methods, Queueables, and Batch `start`/`finish` — the entry points where visibility matters most.

{% hint style="warning" %}
**Don't over-fit your CI.** A rule like "every `makeBuilder()` must be near a `setTemplate()`" sounds tidy but produces false positives — `makeBuilder()` is exactly how you *build* a template. Automate the checks with crisp true/false answers (`System.debug`, `Triton.instance`); leave the judgment calls to the review checklist.
{% endhint %}

## Testing your logging

You generally don't want tests coupled to Pharos storage internals, but for critical paths it's reasonable to assert that a log was actually written with the right classification. Logs surface as `pharos__Log__c` records after publishing:

{% code lineNumbers="true" %}

```apex
@IsTest
static void logsAnErrorOnFailure() {
    Test.startTest();
    try {
        MyService.doThatThrows();
    } catch (Exception e) {
        // expected
    }
    Test.stopTest();   // platform events publish here

    List<pharos__Log__c> logs = [
        SELECT Id, pharos__Category__c, pharos__Area__c, Log_Level__c
        FROM pharos__Log__c
    ];
    System.assert(!logs.isEmpty(), 'An error log should have been written');
    System.assertEquals('ERROR', logs[0].Log_Level__c);
}
```

{% endcode %}

{% hint style="info" %}
**Platform events publish on `Test.stopTest()`.** Buffered logs won't exist as `pharos__Log__c` records until the flush completes — so query for them *after* `Test.stopTest()`, not before.
{% endhint %}

For services where you'd rather not touch storage at all, hide logging behind a thin façade you can mock in unit tests, and reserve the `pharos__Log__c` assertions for a few integration-level tests on your highest-value flows.

## Rolling it out on a team

Standards land best gradually and with a light touch:

1. **Publish the vocabulary and the checklist** — the [taxonomy](https://triton.pharos.ai/triton-best-practices/taxonomy-and-standards) and this page. People can't follow what isn't written down.
2. **Automate the two hard rules** — `System.debug` and `Triton.instance` in CI, day one.
3. **Enforce on new code first.** Hold PRs to the standard; don't block on retrofitting everything at once (that's what [Legacy Code Logging Rollout](https://triton.pharos.ai/triton-best-practices/legacy-migration) is for).
4. **Tighten over time.** Add the higher-value checks once the basics are habitual, and revisit the standard as you learn what actually helps in production.

## Related reading

* The vocabulary these checks enforce: [Taxonomy & Standards](https://triton.pharos.ai/triton-best-practices/taxonomy-and-standards).
* Retrofitting standards into old code safely: [Legacy Code Logging Rollout](https://triton.pharos.ai/triton-best-practices/legacy-migration).


# Legacy Code Logging Rollout

A risk-based strategy for rolling Triton logging into existing, poorly-understood code without breaking what you don't fully understand.

This page is about a specific, uncomfortable situation: you've got Triton, and you've got a big pile of *existing* Apex — triggers no one wants to touch, a batch job whose original author left years ago, integrations held together by hope — and you need to add logging to it without becoming the person who broke production.

{% hint style="info" %}
**This is not the version-migration page.** Moving your codebase from the Triton 1.x singleton to the 2.0 static API is a different task, covered in [Migrating from Triton 1.x to 2.0](https://triton.pharos.ai/migration). This page is about a rollout *strategy*: introducing Triton logging into legacy business code, whatever version you're on. All examples here use the 2.0 API.
{% endhint %}

## The mindset: observability first, do no harm

Greenfield code, you write logging as you go. Legacy code, the priorities invert. The number-one goal is **don't change behavior** — you're adding eyes, not rewriting logic. That means smaller changes, more testing, and a healthy respect for code you don't fully understand.

The good news is that Triton gives you a powerful head start before you touch anything: Pharos **automatically captures unhandled exceptions**. So a lot of your worst legacy code — the stuff with no error handling at all — is already producing error logs without a single edit. Lean on that. Watch the automatic logs first; they'll tell you where the real problems are and where to spend your risk budget.

## Start by assessing your comfort with the code

Not all legacy code is equally scary. Before you plan changes, honestly rate each area, because your comfort level should drive how aggressive you get.

| Comfort    | Signals                                                        | Posture                                                    |
| ---------- | -------------------------------------------------------------- | ---------------------------------------------------------- |
| **High**   | Recent (<12mo), author around, documented, well-tested         | Add logging directly and comprehensively                   |
| **Medium** | 1–3 years old, familiar patterns, partial tests                | Gradual, behind a feature flag, dual-log during transition |
| **Low**    | 3+ years, no docs, no author, thin/no tests, business-critical | Minimal edits, heavy testing, non-critical paths first     |

## Match the pattern to what's already there

Most legacy code falls into one of three states. Each calls for a different opening move.

### Pattern A — no error handling at all

The code has no `try/catch`; errors bubble up. **This is the lowest-risk case, and often needs no change.**

{% code lineNumbers="true" %}

```apex
// Don't rush to modify this.
public class LegacyAccountProcessor {
    public static void processAccount(Account acc) {
        update acc;                 // no try/catch — errors bubble up
        processRelatedRecords(acc.Id);
    }
}
```

{% endcode %}

Let Pharos capture the unhandled exceptions automatically, watch the patterns for a while, and only add explicit logging where the automatic capture leaves a real gap. Resist the urge to wrap everything in `try/catch` just to log — you'd be adding behavior (swallowing) to code you don't understand.

### Pattern B — try/catch with `System.debug` (or nothing)

There's error handling, but it logs to the void. **Two phases, lowest-risk first.**

**Phase 1 — swap `System.debug` for Triton, behind a flag.** Minimal, mechanical, safe.

{% code lineNumbers="true" %}

```apex
public class LegacyIntegrationService {
    public static void callExternalAPI(String endpoint) {
        try {
            HttpRequest req = new HttpRequest();
            req.setEndpoint(endpoint);
            HttpResponse res = new Http().send(req);
            if (res.getStatusCode() != 200) {
                throw new CalloutException('API call failed: ' + res.getStatusCode());
            }
        } catch (Exception e) {
            if (LoggingSettings__c.getInstance().EnableTritonLogging__c) {
                Triton.logNow(Triton.t
                    .category(TritonTypes.Category.Apex)
                    .area(TritonTypes.Area.RestAPI)
                    .exception(e)
                    .details('endpoint=' + endpoint));
            }
            throw e;
        }
    }
}
```

{% endcode %}

**Phase 2 — enrich once Phase 1 is proven.** Add success logging, durations, and payloads. Slightly higher risk because you're touching more lines, so do it after Phase 1 has ridden along quietly for a while.

### Pattern C — an existing custom logging framework

There's a homegrown `Log` class or third-party logger. **Bridge, don't rip out.**

**Phase 1 — have the existing framework&#x20;*****also*****&#x20;write to Triton.** One edit in one place lights up every caller, and the old logging keeps working untouched.

{% code lineNumbers="true" %}

```apex
public class CustomLogger {
    public static void logError(String message, Exception e) {
        // Keep the existing behavior exactly as-is
        insert new Log__c(Message__c = message, Error__c = e.getMessage(), Timestamp__c = System.now());

        // Additionally route to Triton behind a flag
        if (LoggingSettings__c.getInstance().EnableTritonLogging__c) {
            Triton.log(Triton.t
                .category(TritonTypes.Category.Apex)
                .area(TritonTypes.Area.Accounts)
                .exception(e)
                .summary(message));
        }
    }
}
```

{% endcode %}

**Phase 2** — widen the façade's signature to pass more context (related ids, area) into Triton. **Phase 3** — once Triton is trusted, retire the old framework.

## A thin adapter buys you a phased rollout

For a large sweep, the highest-leverage move is a small adapter that maps your old logging vocabulary to Triton. Route the whole codebase through it first (mechanically), then improve behind it domain by domain — without another org-wide change.

{% code lineNumbers="true" %}

```apex
public with sharing class LegacyLog {
    public enum LegacyLevel { ERROR, WARN, INFO, DEBUG }

    public static void write(LegacyLevel lvl, String summary, String details, Set<Id> ids) {
        TritonBuilder b = Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .area(TritonTypes.Area.Accounts)     // sensible default; specialize per domain later
            .summary(summary)
            .details(details)
            .relatedObjects(ids);

        switch on lvl {
            when ERROR { Triton.error(b); }
            when WARN  { Triton.warning(b); }
            when INFO  { Triton.info(b); }
            when DEBUG { Triton.debug(b); }
        }
    }
}
```

{% endcode %}

A regex search-and-replace points legacy calls at `LegacyLog.write(...)` in one pass; then you progressively inline proper templates and real Areas, domain by domain.

## Phasing the rollout across the org

For the org as a whole, prioritize by value and risk rather than crawling the codebase alphabetically:

1. **Inventory & prioritize.** Grep for `System.debug` and homegrown loggers; list your triggers, batches, and integrations. Rank customer-facing and integration-heavy paths first.
2. **Edge entry points.** Wrap public controllers, Queueables, Batch `start`/`finish`, and global callouts. Establish transaction correlation across LWC/Apex and batch chunks. Highest visibility, well-understood boundaries.
3. **High-value internals.** Trigger handlers and core services. Replace homegrown logs with the builder; add related objects and real Areas.
4. **Broad replacement.** Sweep low-risk utilities, remove the last `System.debug`, and tighten [CI rules](https://triton.pharos.ai/triton-best-practices/standards-enforcement) to block regressions.
5. **Optimize.** Tune levels via `Log_Level__mdt`, add durations and limit snapshots in hot paths, and turn on issue creation only for genuinely user-impacting failures.

## Risk mitigation

* **Feature flags.** Gate new logging behind a custom setting (as above) so you can turn it off instantly, per org or per domain, without a deploy.
* **Dual-log during transitions.** Keep the old logging running alongside Triton until you trust the new path, then retire the old one.
* **Don't let logging throw.** In the riskiest code, wrap the Triton call itself so a logging failure can never break the business operation:

{% code lineNumbers="true" %}

```apex
try {
    Triton.logNow(Triton.t.exception(e));
} catch (Exception loggingError) {
    // Never let logging take down the main flow
}
```

{% endcode %}

* **Test that behavior didn't change.** For each touched area, assert the original functionality still works *and* that the expected `pharos__Log__c` records appear (query after `Test.stopTest()` — see [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement)).
* **Have a rollback ready.** With a flag, rollback is flipping a boolean:

{% code lineNumbers="true" %}

```apex
LoggingSettings__c s = LoggingSettings__c.getInstance();
s.EnableTritonLogging__c = false;
update s;
```

{% endcode %}

## Do / Don't for legacy work

{% hint style="success" %}
**Do**

* Lean on Pharos' automatic exception capture before writing any code.
* Start with non-critical paths to build confidence.
* Gate changes behind feature flags; dual-log during the transition.
* Test behavior *and* log output before touching critical code.
* Keep each change small and reversible.
  {% endhint %}

{% hint style="danger" %}
**Don't**

* Wrap untested legacy logic in new `try/catch` just to log — you may silently swallow errors that used to surface.
* Rip out existing logging before Triton is proven in that area.
* Assume all code is safe to modify — respect the low-comfort tier.
* Change critical business logic and logging in the same PR.
  {% endhint %}

## Related reading

* Version migration (1.x → 2.0), which is a different task: [Migrating from Triton 1.x to 2.0](https://triton.pharos.ai/migration).
* The CI guardrails that keep legacy regressions from creeping back: [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement).


# Apex

This article covers the base Apex methods you'll need to create log records.

## File Index

#### [`Triton.cls`](https://triton.pharos.ai/methods-reference/apex-methods-reference/triton)

The main class that provides the core logging functionality through a fully static API:

* Static entry point — no instance to manage
* Builder creation and reusable templates
* Buffered (`log`) and immediate (`logNow`) logging, plus per-level shorthands
* Transaction tracking across Apex, LWC, and Flow contexts (optionally cache-backed)
* Configurable log levels via Custom Metadata

#### [`TritonBuilder.cls`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder)

A builder class that provides a fluent interface for creating log records:

* Wraps the core `pharos.LogBuilder` to provide a user-friendly API
* Handles setting of various log attributes (category, type, area, etc.)
* Manages related objects and metadata
* Supports integration payload formatting
* Handles transaction IDs and user context

#### [`TritonTypes.cls`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritontypes)

Defines the classification system and enums used throughout the framework:

* `Area`: Functional areas from a business perspective (e.g., OpportunityManagement, RestAPI)
* `Category`: The technology that produced the log (e.g., Apex, Flow, LWC)
* `Level`: Log severity levels (ERROR to FINEST)
* `Type`: Technical classification (e.g., Backend, Frontend, DMLResult)

### Context-Specific Components

#### [`TritonLwc.cls`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonlwc)

Provides logging capabilities specifically for Lightning Web Components:

* Exposes AuraEnabled methods for LWC logging
* Handles component context capture
* Manages error details and stack traces
* Captures detailed runtime information (performance, memory, network)
* Supports transaction management

#### [`TritonFlow.cls`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflow)

Enables logging from Salesforce Flows and Process Builder:

* Provides invocable methods for Flow Builder
* Handles Flow context capture (Interview GUID, Flow API Name)
* Supports custom field mapping through JSON
* Manages automatic transaction tracking
* Validates and defaults log levels and categories

### Utility Components

#### [`TritonHelper.cls`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonhelper)

Provides utility methods and builder classes:

* The single publish path, which never throws (`publishLogs`)
* Runtime configuration and log-level evaluation (`TritonHelper.Config`)
* Log level comparison
* UUID generation for transaction tracking
* HTTP request/response JSON serialization
* Transaction caching functionality
* Message formatting utilities
* Runtime information formatting
* Stack trace processing

#### [`TritonCacheManager.cls`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritoncachemanager)

Centralizes Salesforce Platform Cache operations (Org cache), with a test-friendly mock backend. Backs cache-based transaction management and Flow-log buffering.

#### [`TritonFlowFlushBatch.cls`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflowflushbatch)

Singleton batch that defers and consolidates Flow log publishing to minimize platform event consumption.

#### [`TritonTestFactory.cls`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritontestfactory)

Shared `@IsTest` helper providing setup, record-creation, flush, query, assertion, and fault-injection utilities for Triton tests.

#### `TritonSpanContext.cls`

The in-memory span stack behind [performance marks](https://triton.pharos.ai/common-apex-usage-patters/performance-marks). `Triton` uses it internally; you don't call it directly.

#### `LogLimitsController.cls`

Serves `getLimitUsage(logId)` to the **Log Limits** component on the Log record page. See [Add the Log Limits component](https://triton.pharos.ai/installing-pharos-triton#add-the-log-limits-component-to-the-log-page).

### Runtime Information Components

#### [`RuntimeInfo` (in TritonLwc)](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonlwc/runtimeinfo)

Captures detailed runtime information from Lightning Web Components:

* Environment details (user agent, platform, language)
* Performance metrics (page load time, DOM events, paint times)
* Memory usage statistics
* Network information (connection type, speed, RTT)
* Device characteristics (form factor, screen dimensions)
* Navigation context (pathname, hostname)


# Triton

The Triton class is the static entry point for all logging — builder creation, buffered and immediate logging, transaction management, and log-level filtering.

The `Triton` class exposes a fully **static** API. There is no instance to manage — every operation is a class method or property. A typical call chains a builder (created from a template) into one of the log methods:

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t
    .summary('Order placed')
    .details('Order 12345 processed'));
Triton.flush();
```

{% endcode %}

{% hint style="info" %}
**Logging never throws into your code.** `log`, the level methods, `logNow`, `flush`, `flushTop`, and the mark methods catch their own failures: a log that can't be built or published is dropped, and the failure is written to the Apex debug log at `ERROR`. A builder argument is evaluated in your code before Triton runs, so Triton can't catch what throws there, and `System.LimitException` can't be caught by any Apex. [`stopTransaction()`](#stoptransaction) can still throw when `withCache()` is enabled. See [When publishing fails](https://triton.pharos.ai/core-concepts/buffering-flushing#when-publishing-fails).
{% endhint %}

## Builder Creation

### makeBuilder()

{% code lineNumbers="true" %}

```apex
public static TritonBuilder makeBuilder()
```

{% endcode %}

Creates a new [`TritonBuilder`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder) with the category defaulted to `Apex`.

**Returns:**

* A new `TritonBuilder` instance

### t

{% code lineNumbers="true" %}

```apex
public static TritonBuilder t { get; }
```

{% endcode %}

Shorthand property for [`fromTemplate()`](#fromtemplate). Returns a copy of the current template builder, stamped with the active transaction ID.

**Example:**

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.t.summary('test').details('test'));
```

{% endcode %}

### fromTemplate()

{% code lineNumbers="true" %}

```apex
public static TritonBuilder fromTemplate()
```

{% endcode %}

Returns a clone of the currently saved template builder, with the active transaction ID applied. If no template was set, a default builder is used.

**Returns:**

* A `TritonBuilder` copy of the template

### setTemplate(TritonBuilder builder)

{% code lineNumbers="true" %}

```apex
public static void setTemplate(TritonBuilder builder)
```

{% endcode %}

Stores a builder to be reused as the base for [`fromTemplate()`](#fromtemplate) / [`Triton.t`](#t). Use this to set common attributes (category, area, post-processing) once per transaction.

**Parameters:**

* `builder` -- the `TritonBuilder` to use as a template

**Example:**

{% code lineNumbers="true" %}

```apex
Triton.setTemplate(Triton.makeBuilder()
    .area(TritonTypes.Area.OpportunityManagement)
    .level(TritonTypes.Level.INFO));
```

{% endcode %}

### makePostProcessingBuilder()

{% code lineNumbers="true" %}

```apex
public static TritonHelper.PostProcessingControlsBuilder makePostProcessingBuilder()
```

{% endcode %}

Creates a new [`PostProcessingControlsBuilder`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonhelper/postprocessingcontrolsbuilder) for configuring Pharos post-processing flags.

**Returns:**

* A new `TritonHelper.PostProcessingControlsBuilder` instance

## Logging Methods

Logs are added to an internal buffer and persisted on [`flush()`](#flush). Each level method overrides the builder's level and then buffers the log.

### log(TritonBuilder builder)

{% code lineNumbers="true" %}

```apex
public static void log(TritonBuilder builder)
```

{% endcode %}

Adds a log to the buffer using the builder's own level. The log is skipped if it fails the current [log-level filter](https://triton.pharos.ai/core-concepts/log-levels) (see [`TritonHelper.Config.isLogAllowed`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonhelper#islogallowed)). Stack trace, operation, tracepoint, and limit info are auto-captured at this point.

**Parameters:**

* `builder` -- a configured `TritonBuilder`

**Example:**

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.t
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.Accounts)
    .summary('Process completed')
    .level(TritonTypes.Level.INFO));
```

{% endcode %}

### logNow(TritonBuilder builder)

{% code lineNumbers="true" %}

```apex
public static void logNow(TritonBuilder builder)
```

{% endcode %}

Buffers the log and immediately flushes it (equivalent to `log()` followed by [`flushTop()`](#flushtop)). Use for critical logs that must persist right away. If a log-level rule filters the log out, nothing is published and the rest of the buffer is left untouched.

**Parameters:**

* `builder` -- a configured `TritonBuilder`

**Example:**

{% code lineNumbers="true" %}

```apex
Triton.logNow(Triton.t.summary('Critical failure').exception(e));
```

{% endcode %}

### error / warning / info / debug / fine / finer / finest (TritonBuilder builder)

{% code lineNumbers="true" %}

```apex
public static void error(TritonBuilder builder)
public static void warning(TritonBuilder builder)
public static void info(TritonBuilder builder)
public static void debug(TritonBuilder builder)
public static void fine(TritonBuilder builder)
public static void finer(TritonBuilder builder)
public static void finest(TritonBuilder builder)
```

{% endcode %}

Convenience methods that override the builder's level to the corresponding [`Level`](https://triton.pharos.ai/core-concepts/log-levels) and buffer the log. `error()` also flags the log to create an issue. An issue implied by an error — from `error()`, `.exception(e)`, or a failed `.dmlResults(...)` — is withdrawn when the final level is below ERROR, so `Triton.warning(Triton.t.exception(e))` records the exception at WARNING with no issue. An explicit `.createIssue()` always stands.

**Parameters:**

* `builder` -- a configured `TritonBuilder`

**Example:**

{% code lineNumbers="true" %}

```apex
Triton.info(Triton.t.summary('Fetching items'));
Triton.error(Triton.t.summary('Failed').exception(e));
```

{% endcode %}

## Buffer Management

### flush()

{% code lineNumbers="true" %}

```apex
public static void flush()
```

{% endcode %}

Publishes every buffered log in one flush and clears the buffer. No-op when the buffer is empty. Never throws: if publishing fails, the buffered logs are dropped (not re-queued) and the failure is written to the Apex debug log at `ERROR`.

### flushTop()

{% code lineNumbers="true" %}

```apex
public static void flushTop()
```

{% endcode %}

Publishes only the most recently buffered log and removes it from the buffer. No-op when the buffer is empty. Never throws; a failed publish drops that one log and leaves the older ones buffered.

### drain()

{% code lineNumbers="true" %}

```apex
public static List<pharos__Log__c> drain()
```

{% endcode %}

Returns all buffered logs and clears the internal buffer **without** publishing them. Used by [`TritonFlow`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflow) to hand logs off to the deferred flush batch.

**Returns:**

* A `List<pharos__Log__c>` of the buffered log records

## Transaction Methods

A transaction ties together logs across multiple Salesforce contexts (Apex, LWC, Flow). It is identified by an auto-generated UUID stored in the static `Triton.TRANSACTION_ID`.

### startTransaction()

{% code lineNumbers="true" %}

```apex
public static String startTransaction()
```

{% endcode %}

Starts a new transaction with an auto-generated UUID. When platform cache is enabled, the ID is also cached. The span hierarchy resets to the request root **only when no** [**performance mark**](https://triton.pharos.ai/common-apex-usage-patters/performance-marks) **is open** — an open mark survives `startTransaction()`, so an LWC log save or a Flow **Log** action firing inside a mark can't destroy it or lose its unwritten completion record.

**Returns:**

* The new transaction ID

### resumeTransaction(String transactionId)

{% code lineNumbers="true" %}

```apex
public static void resumeTransaction(String transactionId)
```

{% endcode %}

Resumes an existing transaction. Use this to correlate logs across different Salesforce transactions.

**Parameters:**

* `transactionId` -- an existing transaction ID to resume

### stopTransaction()

{% code lineNumbers="true" %}

```apex
public static void stopTransaction()
```

{% endcode %}

Ends the current transaction and resets `Triton.TRANSACTION_ID`. Clears the cached ID when platform cache is enabled. Unlike the logging methods, this one is not guarded: with cache enabled, a failure clearing the cached ID is thrown to the caller.

### withCache()

{% code lineNumbers="true" %}

```apex
public static void withCache()
```

{% endcode %}

Enables Salesforce Platform Cache for transaction management. When available, the current transaction ID is resumed from (or written to) the Org cache so it survives across LWC/Apex/Flow round-trips and asynchronous jobs. Falls back to a plain in-memory transaction when cache is unavailable.

## Performance Marks

A **mark** times a stretch of Apex, emits a paired set of `Performance` records, and parents every log created inside it to that mark. Marks nest LIFO. See [Performance Marks in Apex](https://triton.pharos.ai/common-apex-usage-patters/performance-marks) for the full pattern.

Marks always log at `FINE` and always use the buffered path — no mark method flushes. There is no `level` parameter by design: verbosity is controlled by [`Log_Level__mdt`](https://triton.pharos.ai/core-concepts/log-levels), not by the call site.

### startMark()

{% code lineNumbers="true" %}

```apex
public static String startMark()
```

{% endcode %}

Opens a mark whose name is **derived from the stack trace** as `<Class>.<method>`, mints a span id, parents it to the enclosing span (the transaction when nothing else is open), and emits the opening record. Falls back to `AnonymousMark` plus a counter when a name can't be derived.

**Returns:**

* The derived mark name — pass it to [`endMark(String)`](#endmark-string-markname) if you need an out-of-order close

**Example:**

{% code lineNumbers="true" %}

```apex
Triton.startMark();
try {
    recalculate();
} finally {
    Triton.endMark();
}
```

{% endcode %}

### startMark(String markName)

{% code lineNumbers="true" %}

```apex
public static String startMark(String markName)
```

{% endcode %}

As [`startMark()`](#startmark), with the name supplied. Use it when the meaningful name isn't a method name, or to measure one method in several labelled segments. It is **not** a performance escape hatch — both forms cost effectively the same.

**Parameters:**

* `markName` -- the name for this mark

**Returns:**

* The mark name

**Example:**

{% code lineNumbers="true" %}

```apex
Triton.startMark('nightly-reconcile');
```

{% endcode %}

### endMark()

{% code lineNumbers="true" %}

```apex
public static void endMark()
```

{% endcode %}

Closes the innermost open mark, whatever it's called: computes the elapsed milliseconds, pops the span, and emits the completion record. Call it from a `finally` block. No-op when no mark is open.

### endMark(String markName)

{% code lineNumbers="true" %}

```apex
public static void endMark(String markName)
```

{% endcode %}

Closes the newest open mark with that name, for work that legitimately finishes out of order. A blank name, or one matching no open mark, is ignored — instrumentation never throws into business logic.

**Parameters:**

* `markName` -- the name of the mark to close

### clearMarks()

{% code lineNumbers="true" %}

```apex
public static void clearMarks()
```

{% endcode %}

Discards all open marks and resets the span stack to the request root. Call it explicitly when you want that reset: [`startTransaction()`](#starttransaction) does **not** clear marks while one is open. Not needed at the top of a batch chunk, `Queueable`, or `@future` — a fresh execution context already starts with an empty stack.

### startTriggerMark()

{% code lineNumbers="true" %}

```apex
public static String startTriggerMark()
```

{% endcode %}

Opens a mark named `<Handler>.<Trigger.operationType>` — for example `OpportunityHandler.BEFORE_UPDATE`. The handler class comes from the stack trace; the context comes from `Trigger.operationType`, which is the one naming detail a stack trace can't carry. Outside trigger context it behaves exactly like [`startMark()`](#startmark).

**Returns:**

* The mark name

**Example:**

{% code lineNumbers="true" %}

```apex
Triton.startTriggerMark();
try {
    dispatch();
} finally {
    Triton.endMark();
}
```

{% endcode %}

## Log-Level Filtering

Whether a log passes the `Log_Level__mdt` rules is decided by [`TritonHelper.Config.isLogAllowed(log)`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonhelper#islogallowed), which `log()` calls before buffering. See [Log Levels](https://triton.pharos.ai/core-concepts/log-levels) for how rules are scoped and resolved.

## Constants

| Constant                | Description                                                                                                        |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `Triton.TRANSACTION_ID` | The current transaction ID (`String`). Passed around to trace a process spanning multiple Salesforce transactions. |
| `Triton.SPACE_SEP`      | Separator (`'\n\n'`) used when concatenating details fragments.                                                    |


# TritonBuilder

The TritonBuilder class provides a comprehensive, fluent API for creating structured log records in Salesforce.

## Overview

`TritonBuilder` is the fluent builder behind every Triton log. It wraps the managed [`pharos.LogBuilder`](https://triton.pharos.ai/methods-reference/apex-methods-reference/logbuilder) with a friendlier, strongly-typed API for setting category, type, area, level, related objects, spans, limits, and other metadata. Obtain one with [`Triton.makeBuilder()`](https://triton.pharos.ai/methods-reference/apex-methods-reference/triton#makebuilder) or [`Triton.t`](https://triton.pharos.ai/methods-reference/apex-methods-reference/triton#t), then hand it to a [logging method](https://triton.pharos.ai/methods-reference/apex-methods-reference/triton#logging-methods).

{% code lineNumbers="true" %}

```apex
Triton.log(Triton.makeBuilder()
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.Accounts)
    .summary('Process completed')
    .info());
```

{% endcode %}

### Constructor

#### TritonBuilder()

* **Description**: Creates a new builder, seeding the created timestamp and request ID. In practice, prefer `Triton.makeBuilder()`, which also defaults the category to `Apex`.
* **Usage**:

  <pre class="language-apex" data-line-numbers><code class="lang-apex">TritonBuilder builder = new TritonBuilder();
  </code></pre>

## Classification

#### category(TritonTypes.Category c)

* **Description**: Sets the log category from the [`Category` enum](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritontypes#category).
* **Returns**: `TritonBuilder`
* **Usage**: `builder.category(TritonTypes.Category.Apex);`

#### type(TritonTypes.Type t)

* **Description**: Sets the log type from the [`Type` enum](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritontypes#type).
* **Returns**: `TritonBuilder`
* **Usage**: `builder.type(TritonTypes.Type.Backend);`

#### type(String t)

* **Description**: Sets the log type to a raw string. Used when the type comes from an exception or a Flow.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.type('CalloutException');`

#### area(TritonTypes.Area a)

* **Description**: Sets the functional area from the [`Area` enum](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritontypes#area).
* **Returns**: `TritonBuilder`
* **Usage**: `builder.area(TritonTypes.Area.Community);`

#### area(String a)

* **Description**: Sets the functional area to a raw string. Used from Flows.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.area('CustomArea');`

#### level(TritonTypes.Level l)

* **Description**: Sets the log level from the [`Level` enum](https://triton.pharos.ai/core-concepts/log-levels).
* **Returns**: `TritonBuilder`
* **Usage**: `builder.level(TritonTypes.Level.INFO);`

## Level Shorthands

Each level has a no-argument form that sets the level, and a single-string overload that also sets the summary. `error()` additionally requests an issue. That request follows the final level: if a later `.level(...)` or `.warning()` — or a `Triton.warning(...)` call — leaves the log below ERROR, the issue is withdrawn at build time.

{% code lineNumbers="true" %}

```apex
public TritonBuilder error()   // + an issue, while the level stays ERROR
public TritonBuilder error(String summary)
public TritonBuilder warning()
public TritonBuilder warning(String summary)
public TritonBuilder info()
public TritonBuilder info(String summary)
public TritonBuilder debug()
public TritonBuilder debug(String summary)
public TritonBuilder fine()
public TritonBuilder fine(String summary)
public TritonBuilder finer()
public TritonBuilder finer(String summary)
public TritonBuilder finest()
public TritonBuilder finest(String summary)
```

{% endcode %}

* **Returns**: `TritonBuilder`
* **Usage**:

  <pre class="language-apex" data-line-numbers><code class="lang-apex">builder.error('Payment gateway timeout');
  builder.info();
  </code></pre>

## Content

#### summary(String value)

* **Description**: Sets the log summary. Values longer than 255 characters are truncated for the Summary field; the full text is appended to Details automatically at build time.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.summary('Log Summary');`

#### details(String value)

* **Description**: Sets the log details.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.details('Detailed log information');`

#### stackTrace(String stack)

* **Description**: Sets the stack trace. When omitted, one is captured automatically at log time.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.stackTrace('Stack trace details');`

#### operation(String operation)

* **Description**: Sets the operation (Apex Name). When omitted, it is derived from the stack trace.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.operation('AccountService.recalculate');`

#### action(String action)

* **Description**: Sets the action name — e.g. a performance mark, backend call, or user-interaction name. Writes to the `Action__c` field.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.action('loadAccounts');`

## Exceptions & DML Results

#### exception(Exception e)

* **Description**: Configures the builder from an exception: sets the type to the exception's type name (falling back to `Backend`), level to `ERROR`, summary to the message, details and stack trace from the exception, and requests an issue — withdrawn if the final level ends up below ERROR. No-op if `e` is null.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.exception(e);`

#### dmlResults(List\<Object> dmlResults)

* **Description**: Inspects a list of DML result objects. When any row failed, configures the builder as a `DMLResult` log at `ERROR` — with a summary of the failure count, all error messages in details, the failed record IDs as related objects, and an issue request (withdrawn if the final level ends up below ERROR). When every row succeeded, or the list is null or empty, it marks the builder as suppressed, and whichever method you pass it to (`Triton.log`, `logNow`, `error`, `warning`, …) emits nothing. Set the area via template or explicitly before calling; set any custom summary **after** it, since a failure overwrites the summary.
* **Parameters**: `dmlResults` — a `List` of `Database.SaveResult`, `DeleteResult`, `UpsertResult`, `UndeleteResult`, or `MergeResult`
* **Returns**: `TritonBuilder`
* **Usage**:

  <pre class="language-apex" data-line-numbers><code class="lang-apex">List&#x3C;Database.SaveResult> results = Database.insert(accounts, false);
  Triton.log(Triton.t
      .area(TritonTypes.Area.Accounts)
      .dmlResults(results));
  </code></pre>

#### isSuppressed()

* **Description**: `true` when `dmlResults(...)` found nothing to report — every row succeeded, or the list was null or empty. `Triton` checks it and emits nothing for the builder.
* **Returns**: `Boolean`

## Tracing & Spans

#### spanId(String spanId)

* **Description**: Sets the span ID (`Span_Id__c`) identifying this unit of work. When not set, the request ID is used as a fallback for Apex logs — inside an open [performance mark](https://triton.pharos.ai/common-apex-usage-patters/performance-marks) the log gets its own span id instead. A value you set here always wins over either default.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.spanId(mySpanId);`

#### parentSpanId(String parentSpanId)

* **Description**: Sets the parent span ID (`Parent_Span_Id__c`), linking this log to its parent span in a trace hierarchy. Left unset, it stays null — except inside an open [performance mark](https://triton.pharos.ai/common-apex-usage-patters/performance-marks), where the enclosing mark's span is stamped on it automatically. A value you set here is never overwritten.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.parentSpanId(parentSpanId);`

#### traceable(Boolean traceable)

* **Description**: Enables (or disables) trace-point capture for this builder. When set to `true`, an issue is also requested explicitly, so it stands at any level.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.traceable(true);`

#### tracePoint()

* **Description**: Records a Pharos trace point. Only has an effect when the builder is `traceable`.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.tracePoint();`

## Context

#### apexExecutionContext()

* **Description**: Captures the current Salesforce execution context and appends it to details at build time. For triggers: operation type, sObject, and batch size. For async contexts (batch, queueable, scheduled, future): the context type. Applied automatically for Apex-category logs during logging.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.apexExecutionContext();`

#### userId(Id userId)

* **Description**: Sets the user ID associated with the log.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.userId(UserInfo.getUserId());`

#### relatedObject(Id objectId) / relatedObject(String objectId)

* **Description**: Sets the related record to this single ID, **replacing** any related records already on the builder, including a template's. A null or invalid ID is ignored and leaves the existing set in place.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.relatedObject(myAccount.Id);`

#### relatedObjects(List\<Id> / List\<String> / Set\<String> / Set\<Id>)

* **Description**: Sets the related records to these IDs, **replacing** any already on the builder, including a template's — pass every ID in one call. Invalid string IDs are filtered out.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.relatedObjects(new Set<Id>{a.Id, b.Id});`

#### transactionId(String transactionId)

* **Description**: Sets the transaction ID for cross-context correlation. Usually applied automatically from `Triton.TRANSACTION_ID`.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.transactionId('12345-transaction-id');`

#### createIssue()

* **Description**: Flags the log so Pharos creates (or associates) an Issue. Custom logs create no issue by default. An explicit `createIssue()` stands at any level, unlike the issue implied by `error()`, `exception(e)`, or a failed `dmlResults(...)`.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.createIssue();`

#### createdTimestamp(Double timestamp) / createdTimestamp()

* **Description**: Sets the created timestamp. The no-argument form uses the current time (called automatically in the constructor).
* **Returns**: `TritonBuilder`
* **Usage**: `builder.createdTimestamp(Double.valueOf(System.now().getTime()));`

#### duration(Decimal duration)

* **Description**: Sets the duration (milliseconds) for the log.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.duration(123.45);`

## Flow & Integration

#### interviewGuid(String guid)

* **Description**: Sets the Flow interview GUID.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.interviewGuid('interview-guid');`

#### flowApiName(String apiName)

* **Description**: Sets the Flow API name. Use the **plain** API name: component-scoped `Log_Level__mdt` rules match it in full, so a version-suffixed value like `My_Flow-4` won't match a rule naming `My_Flow`. The version goes in [`flowVersion()`](#flowversion-decimal-version).
* **Returns**: `TritonBuilder`
* **Usage**: `builder.flowApiName('My_Flow');`

#### flowVersion(Decimal version)

* **Description**: Sets the Flow version, written to `pharos__Flow_Version__c`. The managed field is Text, so the number is stored in its canonical string form. Pairs with [`flowApiName()`](#flowapiname-string-apiname), which should carry the plain API name — see [Logging in Flow](https://triton.pharos.ai/flows#flow-api-name-and-flow-version).
* **Returns**: `TritonBuilder`
* **Usage**: `builder.flowVersion(4);`

#### integrationPayload(HttpRequest request, HttpResponse response)

* **Description**: Serializes an outbound HTTP request/response pair onto the log for integration logging.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.integrationPayload(request, response);`

#### integrationPayload(RestRequest request, RestResponse response)

* **Description**: Serializes an inbound REST request/response pair onto the log.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.integrationPayload(restRequest, restResponse);`

#### postProcessing(TritonHelper.PostProcessingControlsBuilder postProcessingBuilder)

* **Description**: Attaches Pharos post-processing controls built with [`PostProcessingControlsBuilder`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonhelper/postprocessingcontrolsbuilder).
* **Returns**: `TritonBuilder`
* **Usage**:

  <pre class="language-apex" data-line-numbers><code class="lang-apex">builder.postProcessing(Triton.makePostProcessingBuilder().userInfo(true));
  </code></pre>

## Limit Info

#### limitInfo()

* **Description**: Captures current governor usage and limits as attributes. Captures essential limits (SOQL, DML, CPU, heap, callouts); when [`withFullLimitInfo()`](#withfulllimitinfo) was called, also captures extended limits (aggregates, SOSL, future calls, queueable jobs, email invocations, push notifications, batch jobs, publish-immediate DML). No-op when limit info is disabled. Applied automatically during logging.
* **Returns**: `TritonBuilder`

#### limitInfoLite()

* **Description**: Captures only the essential governor limits.
* **Returns**: `TritonBuilder`

#### withFullLimitInfo()

* **Description**: Requests that extended limits be captured in addition to essential limits when `limitInfo()` runs.
* **Returns**: `TritonBuilder`

#### withoutLimitInfo()

* **Description**: Disables limit-info capture for this log.
* **Returns**: `TritonBuilder`

## Low-Level

#### attribute(String name, Object value)

* **Description**: Sets any field on the underlying log record directly. Use the [field-name constants](#field-name-constants) for well-known fields.
* **Returns**: `TritonBuilder`
* **Usage**: `builder.attribute(TritonBuilder.ACTION, 'loadAccounts');`

#### cloneBuilder()

* **Description**: Returns a deep copy of the builder (populated fields plus configuration flags). Used internally by templates.
* **Returns**: `TritonBuilder`

#### prepareForLogging(String transactionId)

* **Description**: Enriches the builder just before buffering — sets the transaction ID, auto-captures stack trace and operation if missing, records a trace point, captures limit info, and appends Apex execution context. Called internally by `Triton.log()`; you rarely call it directly.
* **Returns**: `TritonBuilder`

#### build()

* **Description**: Builds and returns the final `pharos__Log__c` record, applying defaults (category, summary carryover, execution context).
* **Returns**: `pharos__Log__c`
* **Usage**: `pharos__Log__c logRecord = builder.build();`

## Field-Name Constants

Public constants for the log fields set by the builder. Pass them to [`attribute()`](#attribute-string-name-object-value) when setting a field manually.

| Constant                  | Field API Name                       |
| ------------------------- | ------------------------------------ |
| `APEX_NAME`               | `pharos__Apex_Name__c`               |
| `ACTION`                  | `Action__c`                          |
| `CREATED_TIMESTAMP`       | `pharos__Created_Timestamp__c`       |
| `DURATION`                | `pharos__Duration__c`                |
| `INTERVIEW_GUID`          | `pharos__Interview_GUID_External__c` |
| `LOG_LEVEL`               | `Log_Level__c`                       |
| `RELATED_ID`              | `pharos__Related_Id__c`              |
| `RELATED_OBJECTS`         | `pharos__Related_Objects__c`         |
| `STACKTRACE_PARSE_RESULT` | `pharos__Stacktrace_Parse_Result__c` |
| `USER_ID`                 | `pharos__User_Id__c`                 |
| `FLOW_API_NAME`           | `pharos__Flow_API_Name__c`           |
| `FLOW_VERSION`            | `pharos__Flow_Version__c`            |
| `DO_NOT_CREATE_ISSUE`     | `pharos__Do_Not_Create_Issue__c`     |
| `REQUEST_ID`              | `pharos__Request_Id_External__c`     |
| `SPAN_ID`                 | `Span_Id__c`                         |
| `PARENT_SPAN_ID`          | `Parent_Span_Id__c`                  |


# TritonTypes

This article covers the enums and constants used throughout the Triton logging framework.

## Enums

### Area

Represents the functional area from a business perspective. This value is written to the Functional Area field.

{% code lineNumbers="true" %}

```apex
public enum Area {
    OpportunityManagement,
    LeadConversion,
    Community,
    RestAPI,
    Accounts,
    LWC,
    Flow
}
```

{% endcode %}

These values should represent functional areas from a business perspective (e.g., DealRegistration, PartnerCommunity, CustomPipelineUI).

### Category

Identifies the technology that produced the log entry.

{% code lineNumbers="true" %}

```apex
public enum Category {
    Apex,
    Flow,
    LWC,
    Aura
}
```

{% endcode %}

These values answer "what technology produced this log?" — severity is expressed by `Level`, never by Category.

### Level

Defines log severity levels, listed from least verbose to most verbose.

{% code lineNumbers="true" %}

```apex
public enum Level {
    ERROR,
    WARNING,
    INFO,
    DEBUG,
    FINE,
    FINER,
    FINEST
}
```

{% endcode %}

### Type

Provides more specific technical classification of log entries.

{% code lineNumbers="true" %}

```apex
public enum Type {
    Backend,
    Frontend,
    DMLResult,
    LongRunningRequest,
    ConcurrentRequestsLimit,
    AccountTrigger,
    BackendCall,
    ComponentLifecycle,
    ComponentRender,
    UserInteraction,
    Performance
}
```

{% endcode %}

When an Exception is provided, the logging methods will use the Exception type. If no type is specified for exceptions, Backend is used as default.

The last five values — `BackendCall`, `ComponentLifecycle`, `ComponentRender`, `UserInteraction`, and `Performance` — are set by the LWC profiling APIs. See [Profiling](https://triton.pharos.ai/beyond-apex/profiling). `Performance` is also the type Apex [performance marks](https://triton.pharos.ai/common-apex-usage-patters/performance-marks) emit.


# TritonLwc

Documentation for the TritonLwc Apex class that provides core logging functionality for Lightning Web Components.

## Overview

The TritonLwc class provides the server-side implementation for Lightning Web Component logging. It handles the reception and processing of client-side logs, managing transaction context, and ensuring proper log persistence.

## LWC Logging Methods

### saveComponentLogs

{% code lineNumbers="true" %}

```apex
@AuraEnabled
public static void saveComponentLogs(List<ComponentLog> componentLogs)
```

{% endcode %}

Creates logs from LWC components with automatic transaction management and context capture.

## Field Mapping Reference

### Core Fields

| Builder Method | Component Source                   | Default  | Description                                                                                              |
| -------------- | ---------------------------------- | -------- | -------------------------------------------------------------------------------------------------------- |
| `category()`   | componentLog.category              | LWC      | Component classification                                                                                 |
| `type()`       | componentLog.type/error.type       | Frontend | Technical classification                                                                                 |
| `area()`       | componentLog.area                  | LWC      | Functional area — any non-blank value is kept; a known area is normalized to its `TritonTypes.Area` name |
| `level()`      | componentLog.level                 | INFO     | Log severity                                                                                             |
| `summary()`    | componentLog.summary/error.message | -        | Main log message                                                                                         |
| `details()`    | componentLog.details + validation  | -        | Extended information                                                                                     |
| `stackTrace()` | componentLog.stack                 | -        | Error stack trace                                                                                        |

### Context Fields

> 🔍 **Component Context**\
> The system automatically captures rich component execution context:

{% code lineNumbers="true" %}

```json
{
  "operation": "componentName.functionName",
  "transactionId": "auto-generated or from component",
  "userId": "current user or specified",
  "createdTimestamp": "component time or server time",
  "duration": "execution time if provided",
  "action": "performance mark / backend call / interaction name",
  "spanId": "span identifier from the component",
  "parentSpanId": "parent span identifier from the component"
}
```

{% endcode %}

Span IDs (`spanId` / `parentSpanId`) let the LWC layer stitch client-side operations into a trace hierarchy that carries through to Apex. Limit info is not captured for component logs.

### Related Objects

> 🔗 **Record Context**\
> The system supports linking logs to Salesforce records:

{% code lineNumbers="true" %}

```json
{
  "relatedObjects": ["recordId1", "recordId2"],
  "validationRules": "15 or 18 character IDs",
  "behavior": "Invalid IDs are filtered"
}
```

{% endcode %}

## Automatic Behaviors

> ⚡ **Smart Processing**\
> The system provides intelligent handling of log data:

1. **Transaction Management**
   * Resumes the transaction id cached for the user (within the Cache TTL) when there is one; otherwise adopts the id the component sent, or starts a new one
   * Maintains transaction context across components
   * Correlates related logs
2. **Context Enrichment**
   * Captures component hierarchy
   * Records runtime metrics
   * Preserves error context
3. **Data Validation**
   * Validates all incoming fields
   * Provides sensible defaults
   * Maintains data integrity

## Validation Rules

### Required Field Validation

| Field    | Validation Rule                                                                                                        | Default Behavior                                                         |
| -------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| Category | Must be a `TritonTypes.Category` value                                                                                 | Falls back to `LWC`, with a note in Details                              |
| Type     | Any string                                                                                                             | Blank uses the error's type, then `Frontend`                             |
| Area     | Any string; a known area in any spelling (`'LEAD_CONVERSION'`, `'leadconversion'`) maps to its `TritonTypes.Area` name | Blank lands as `LWC`, with no note                                       |
| Level    | Must be a `TritonTypes.Level` value                                                                                    | Blank uses `INFO` with no note; an invalid value uses `INFO` with a note |

The silent blank-level default applies to LWC logs only: the Flow **Log** action still appends `Unable to locate log level: null` to Details for a blank level. An `ERROR` log from a component opens a Pharos issue.

### ID Validation

📝 **Record ID Processing**\
The system validates record IDs by:

1. Checking ID format (15 or 18 chars)
2. Filtering invalid IDs
3. Maintaining valid relationships

### Error Handling

> 🛡️ **Validation Strategy**\
> When validation issues occur:

* Invalid values get appropriate defaults
* Validation messages are added to details
* Processing continues uninterrupted: a log that fails to build is dropped without costing the others, and `saveComponentLogs` never throws back to the component — failures are written to the Apex debug log

## Runtime Information

The system captures comprehensive runtime context:

| Metric Type | Examples                           |
| ----------- | ---------------------------------- |
| Performance | Page load, DOM events, Paint times |
| Environment | User agent, Platform, Language     |
| Network     | Connection type, Speed, RTT        |
| Memory      | Heap usage, Limits                 |
| Device      | Form factor, Screen dimensions     |

## Related Classes

The TritonLwc class works with several wrapper classes:

* [ComponentLog](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonlwc/componentlog) - Main wrapper for LWC log data
* [Component](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonlwc/component) - Component context information
* [Error](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonlwc/error) - Error details structure
* [RuntimeInfo](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonlwc/runtimeinfo) - Runtime metrics and context


# ComponentLog

Documentation for the ComponentLog wrapper class used to structure and transmit log data from Lightning Web Components.

Wrapper class for passing log data from LWC components.

**Properties:**

{% code lineNumbers="true" %}

```apex
@AuraEnabled public String level              // Log level (defaults to INFO)
@AuraEnabled public String category           // Log category (defaults to LWC)
@AuraEnabled public String type               // Log type
@AuraEnabled public String area               // Functional area
@AuraEnabled public String summary            // Log summary
@AuraEnabled public String details            // Log details
@AuraEnabled public String transactionId      // Transaction identifier
@AuraEnabled public Component componentInfo    // Component context information
@AuraEnabled public Decimal duration          // Operation duration
@AuraEnabled public String action             // Action name (perf mark / call / interaction)
@AuraEnabled public Decimal createdTimestamp  // Log creation timestamp
@AuraEnabled public Error error               // Error information
@AuraEnabled public String stack              // Stack trace
@AuraEnabled public String userId             // User identifier
@AuraEnabled public RuntimeInfo runtimeInfo   // Runtime context information
@AuraEnabled public List<String> relatedObjectIds  // Related record IDs
@AuraEnabled public String spanId             // Span identifier
@AuraEnabled public String parentSpanId       // Parent span identifier
```

{% endcode %}


# Component

Documentation for the Component wrapper class used to capture LWC component context information.

Wrapper class for component context information.

**Properties:**

{% code lineNumbers="true" %}

```apex
@AuraEnabled public String category   // Component category
@AuraEnabled public String name       // Component name
@AuraEnabled public String function   // Controller function name
```

{% endcode %}


# Error

Documentation for the Error wrapper class used to capture and structure error information from Lightning Web Components.

Wrapper class for error information.

**Properties:**

{% code lineNumbers="true" %}

```apex
@AuraEnabled public String message    // Error message
@AuraEnabled public String stack      // Error stack trace
@AuraEnabled public String type       // Error type
```

{% endcode %}


# RuntimeInfo

Documentation for the RuntimeInfo wrapper class used to capture detailed runtime context and performance metrics from Lightning Web Components.

Wrapper class for capturing detailed runtime context information.

**Properties:**

Environment Information:

{% code lineNumbers="true" %}

```apex
@AuraEnabled public String userAgent        // Browser user agent
@AuraEnabled public String platform         // Operating system platform
@AuraEnabled public String language         // User language
@AuraEnabled public Boolean mobile          // Mobile device indicator
@AuraEnabled public List<Object> brands     // Browser brand information
@AuraEnabled public String theme            // UI theme
```

{% endcode %}

Performance Metrics:

{% code lineNumbers="true" %}

```apex
@AuraEnabled public Double pageLoadTime           // Total page load time
@AuraEnabled public Double domInteractive         // Time to interactive
@AuraEnabled public Double domContentLoaded       // DOM content loaded time
@AuraEnabled public Double firstByte             // Time to first byte
@AuraEnabled public Double serverTime            // Server processing time
@AuraEnabled public Double firstPaint            // First paint timing
@AuraEnabled public Double firstContentfulPaint   // First contentful paint
```

{% endcode %}

Memory Statistics:

{% code lineNumbers="true" %}

```apex
@AuraEnabled public Double memoryUsage     // Current memory usage
@AuraEnabled public Double memoryLimit     // Memory limit
```

{% endcode %}

Network Information:

{% code lineNumbers="true" %}

```apex
@AuraEnabled public String connectionType    // Network connection type
@AuraEnabled public Double connectionSpeed   // Connection speed in Mbps
@AuraEnabled public Double connectionRtt     // Round-trip time
@AuraEnabled public Boolean saveData        // Data saver mode
@AuraEnabled public Boolean isOnline        // Online status
```

{% endcode %}

Device and Display:

{% code lineNumbers="true" %}

```apex
@AuraEnabled public String formFactor       // Device form factor
@AuraEnabled public Integer screenWidth     // Screen width
@AuraEnabled public Integer screenHeight    // Screen height
@AuraEnabled public String orientation      // Screen orientation
@AuraEnabled public Integer viewportWidth   // Viewport width
@AuraEnabled public Integer viewportHeight  // Viewport height
```

{% endcode %}

Navigation Context:

{% code lineNumbers="true" %}

```apex
@AuraEnabled public String pathname         // Current path
@AuraEnabled public String hostname         // Host name
```

{% endcode %}


# TritonFlow

Documentation for the TritonFlow Apex class that provides core logging functionality for Flow Builder and Process Builder.

## Overview

The TritonFlow class provides the server-side implementation for Flow and Process Builder logging. It handles automatic transaction management, Flow context capture, and validation of logging parameters.

## Flow Logging Methods

### log

{% code lineNumbers="true" %}

```apex
@InvocableMethod(Category='TritonLogging' 
                Label='Log' 
                Description='Creates a log for a flow or process builder')
public static List<FlowLogOutput> log(List<FlowLog> flowLogs)
```

{% endcode %}

Creates logs from Flow or Process Builder. This method will:

* Create logs with default INFO level if not specified
* Handle automatic transaction management (create new or resume existing)
* Capture Flow context (Interview GUID, Flow API Name)
* Process custom field mapping through JSON
* Validate category and log level enums
* Return stacktrace information for error handling

**Returns:**

* List containing stacktrace information for each log

## Field Mapping Reference

### Core Fields

| Builder Method | Flow Source       | Required | Default                                                                |
| -------------- | ----------------- | -------- | ---------------------------------------------------------------------- |
| `category()`   | flowLog.category  | No       | Flow [(see Categories)](https://triton.pharos.ai/core-concepts/enums)  |
| `type()`       | flowLog.type      | No       | - [(see Types)](https://triton.pharos.ai/core-concepts/enums)          |
| `area()`       | flowLog.area      | Yes      | - [(see Areas)](https://triton.pharos.ai/core-concepts/enums)          |
| `level()`      | flowLog.level     | No       | INFO [(see Levels)](https://triton.pharos.ai/core-concepts/log-levels) |
| `summary()`    | flowLog.summary   | Yes      | -                                                                      |
| `details()`    | flowLog.details   | No       | -                                                                      |
| `operation()`  | flowLog.operation | No       | -                                                                      |

For complete builder method documentation, see [TritonBuilder Reference](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder).

### Context Fields

> 🔍 **Flow Context**\
> The system automatically captures and sets critical Flow execution context:
>
> * Interview GUID for tracking specific Flow runs
> * Flow API Name for identifying the Flow definition
> * Transaction ID for cross-context correlation

{% code lineNumbers="true" %}

```json
{
  "interviewGuid": "required - from flowLog.interviewGUID",
  "flowApiName": "optional - from flowLog.flowApiName",
  "flowVersion": "optional - from flowLog.flowVersion",
  "transactionId": "auto-generated if not exists"
}
```

{% endcode %}

### Additional Fields

Custom fields can be passed through the `additionalFields` JSON string:

{% code lineNumbers="true" %}

```json
{
  "customField1": "value1",
  "customField2": "value2"
}
```

{% endcode %}

## Automatic Behaviors

> ⚡ **Smart Defaults**\
> The system provides intelligent default behaviors to ensure robust logging:

1. **Transaction Management**
   * Creates new transaction if none exists
   * Maintains transaction context across Flow elements
2. **Issue Creation**
   * Automatically creates issues for ERROR level logs
3. **Post-processing**
   * At every level, requests six post-processing controls: stack trace, user info, related objects, installed packages, pending jobs, and total active sessions
4. **Deferred Publishing**
   * Buffers logs and hands them off with [`Triton.drain()`](https://triton.pharos.ai/methods-reference/apex-methods-reference/triton#drain)
   * Publishes them on a short delay via [`TritonFlowFlushBatch`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflowflushbatch) to minimize platform event consumption
   * With **Disable Flow Flush Batch** set, publishes them in the Flow's own transaction instead
5. **Never Fails the Flow**
   * A log that can't be built is dropped without costing the others. If the publish fails, that publish's logs are dropped. Either way the failure is noted in the Apex debug log.
   * Always returns one output per input, so the Flow's output mapping holds

## Validation Rules

### Required Fields

* `area` - Functional area identifier
* `summary` - Log message summary
* `interviewGUID` - Flow interview identifier

### Enum Validation

The system validates and provides fallbacks for:

| Field     | Invalid Value Behavior        |
| --------- | ----------------------------- |
| Log Level | Defaults to INFO with warning |
| Category  | Defaults to Flow with warning |

### Error Handling

📝 **Validation Messages**\
When validation issues occur, the system:

1. Applies appropriate defaults
2. Appends warning messages to the details field
3. Continues processing without interruption

## Related Classes

The TritonFlow class works with:

* [FlowLog](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflow/flowlog) - Main wrapper for Flow log data (and the `FlowLogOutput` return wrapper)
* [TritonFlowFlushBatch](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflowflushbatch) - Deferred publishing of Flow logs
* [TritonBuilder](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder) - Core log building functionality
* [TritonTypes](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritontypes) - Enums and constants

### Transaction Management

The system provides two modes of transaction handling:

1. **Auto-Create**: If no transaction exists and no ID is provided, creates new
2. **Resume**: If transaction ID is provided, resumes existing transaction

This enables correlation of logs across different Flow elements and contexts.

### Stacktrace Handling

This functionality is facilitated by the X-Ray machine only. If logging manually, disregard these values.

1. **Current Trace**: Captured in `stacktrace` field
2. **Full Trace**: Combines previous traces with current in `fullStacktrace`
3. **Automatic Chaining**: Each FlowLogOutput contains the combined trace

This is used by the X-Ray machine for tracking error propagation through multiple Flow elements.


# FlowLog

Documentation for the FlowLog wrapper class used to structure and transmit log data from Flow Builder and Process Builder.

The FlowLog class provides a wrapper for passing log data from Flow or Process Builder.

## Properties

{% code lineNumbers="true" %}

```apex
@InvocableVariable(Required=false Label='Category')
global String category;               // Log category (defaults to Flow)

@InvocableVariable(Required=false Label='Type')
global String type;                   // Log type

@InvocableVariable(Required=true Label='Area')
global String area;                   // Functional area

@InvocableVariable(Required=false Label='Operation')
global String operation;              // Operation name

@InvocableVariable(Required=true Label='Summary')
global String summary;                // Log summary

@InvocableVariable(Required=false Label='Details')
global String details;                // Log details

@InvocableVariable(Required=true Label='Interview GUID')
global String interviewGUID;          // Flow interview identifier

@InvocableVariable(Required=false Label='Flow API Name')
global String flowApiName;            // Flow API name

@InvocableVariable(Required=false Label='Flow Version')
global String flowVersion;            // Flow version number, as text

@InvocableVariable(Required=false Label='Level')
global String level;                  // Log level (defaults to INFO)

@InvocableVariable(Required=false Label='Transaction ID')
global String transactionId;          // Transaction identifier for log grouping

@InvocableVariable(Required=false Label='Additional Fields')
global String additionalFields;       // JSON string of additional custom fields

@InvocableVariable(Required=false Label='Stacktrace')
global String stacktrace;             // Current stacktrace

@InvocableVariable(Required=false Label='Full Stacktrace')
global String fullStacktrace;         // Complete stacktrace including previous traces
```

{% endcode %}

## Field Reference

### Core Fields

| Field            | Required | Default | Description                                                                                                               |
| ---------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------- |
| category         | No       | Flow    | Category classification for the log                                                                                       |
| type             | No       | -       | Technical classification of the log entry                                                                                 |
| area             | Yes      | -       | Functional area the log relates to                                                                                        |
| summary          | Yes      | -       | Brief description of the log entry                                                                                        |
| details          | No       | -       | Detailed information about the log entry                                                                                  |
| interviewGUID    | Yes      | -       | Flow interview identifier ($Flow\.InterviewGuid)                                                                          |
| flowApiName      | No       | -       | **Plain** API name of the Flow — no version suffix ([why](https://triton.pharos.ai/flows#flow-api-name-and-flow-version)) |
| flowVersion      | No       | -       | Version number of the Flow, passed as text. An unparsable value adds a note to Details instead of failing the log         |
| level            | No       | INFO    | Log level for the entry                                                                                                   |
| operation        | No       | -       | Name of the operation being performed                                                                                     |
| additionalFields | No       | -       | JSON string of additional custom fields                                                                                   |
| transactionId    | No       | -       | Transaction identifier for grouping related logs                                                                          |
| stacktrace       | No       | -       | Current stacktrace information                                                                                            |
| fullStacktrace   | No       | -       | Complete stacktrace including previous traces                                                                             |

### Additional Fields Format

The additionalFields property accepts a JSON string mapping field API names to values:

{% code lineNumbers="true" %}

```json
{
    "pharos__Summary__c": "Custom summary",
    "pharos__Details__c": "Custom details"
}
```

{% endcode %}

Note: If the JSON string fails to parse, an error message will be added to the log details.

## FlowLogOutput

The [`log`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflow#log) invocable returns a `List<FlowLogOutput>` — one per input `FlowLog` — carrying stacktrace information back to the Flow for chained error tracking.

{% code lineNumbers="true" %}

```apex
@InvocableVariable(Required=false Label='Stacktrace')
global String stacktrace;             // Not populated: always null

@InvocableVariable(Required=false Label='Full Stacktrace')
global String fullStacktrace;         // Combined stacktrace including previous traces
```

{% endcode %}

Only **Full Stacktrace** is populated; **Stacktrace** is always null. To chain context, store **Full Stacktrace** in a variable and pass it to the **Full Stacktrace** input of a later **Log** action.


# TritonFlowFlushBatch

Singleton batch that defers and consolidates Flow log publishing to minimize platform event consumption.

## Overview

`TritonFlowFlushBatch` is a singleton `Database.Batchable` that publishes Flow logs on a short delay instead of immediately. [`TritonFlow`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflow) drains buffered logs with [`Triton.drain()`](https://triton.pharos.ai/methods-reference/apex-methods-reference/triton#drain) and hands them to this batch, which buffers them in Org Cache (keyed by transaction ID) across invocable calls and concurrent transactions, then publishes everything in a single `pharos.Logger.flush()`.

Before scheduling, a check against `AsyncApexJob` skips scheduling when a flush batch is already queued or running, so concurrent Flows normally share one batch. If two Flows race past that check, a second batch can be scheduled; that's harmless, because each batch publishes only the logs it took from the cache.

Nothing here throws into the Flow. If the cache write fails, the logs are published immediately. If the batch can't be scheduled, the logs it already took from the cache are published immediately. If a publish fails, those logs are dropped and the failure is written to the Apex debug log. Logs still cached when the **Cache TTL** expires are never published, so keep the batch delay below the TTL.

You do not schedule this batch yourself — `TritonFlow` invokes it via `addLogs()`.

## Methods

#### addLogs(List\<pharos\_\_Log\_\_c> logs, String transactionId)

{% code lineNumbers="true" %}

```apex
public static void addLogs(List<pharos__Log__c> logs, String transactionId)
```

{% endcode %}

Buffers logs for deferred flush. Adds the logs to the per-transaction buffer and writes them to Org Cache under `transactionId`. If the cache write fails (size exceeded or cache unavailable), the pending logs are published immediately and the transaction's cache entry is removed, so no later batch publishes them again. Otherwise a flush batch is scheduled if one is not already active; the logs that batch takes from the cache are no longer held by this transaction, so none is published twice. Never throws.

**Parameters:**

* `logs` -- the log records to buffer
* `transactionId` -- the current transaction ID, used as the cache key

## Batchable Lifecycle

The batch implements `Database.Batchable<SObject>`:

* **Constructor** — reads all pending flow-log cache entries (one per transaction), removing each key after reading to prevent double-processing. It runs when the batch is scheduled, so logs cached after that wait for the next batch.
* **`start`** — returns the collected logs as the batch scope.
* **`execute`** — publishes the scope in a single flush through [`TritonHelper.publishLogs`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonhelper#publishlogs); a failed publish drops those logs and is written to the debug log.
* **`finish`** — if new logs arrived in cache since the batch was scheduled, schedules another batch for them, publishing them immediately if that schedule fails.

{% hint style="info" %}
The batch runs after a short delay — **Flow Flush Batch Delay**, 1 minute by default. Its constructor collects the cached logs when the batch is scheduled, so logs added during the delay are picked up by the next batch, which `finish` schedules. Keep the delay below the **Cache TTL** (5 minutes by default): logs still cached when the TTL expires are never published.
{% endhint %}


# TritonHelper

The TritonHelper class provides utility methods and builder classes for the Triton logging framework.

This class is mostly for internal use. It holds the single publish path, the runtime configuration (`TritonHelper.Config`), the cache helpers, UUID generation, HTTP request/response serialization, mark naming, and message formatting.

### Publishing

#### publishLogs

{% code lineNumbers="true" %}

```apex
public static Boolean publishLogs(List<pharos__Log__c> records)
```

{% endcode %}

The one place Triton hands log records to Pharos: `Triton.flush()`, `flushTop()`, `logNow()`, and the Flow flush batch all publish through it. Never throws. If the publish fails, the records are dropped rather than retried — the Pharos logger's own buffer is then in an unknown state, so a retry could publish duplicates — and the failure goes to [`recordFailure`](#recordfailure).

**Returns:**

* `true` when published, or when there was nothing to publish
* `false` when publishing failed and the records were dropped

#### recordFailure

{% code lineNumbers="true" %}

```apex
public static void recordFailure(String operation, Exception e, Integer droppedLogs)
```

{% endcode %}

Records a failure Triton swallowed so that it never reaches your code. Writes one line to the Apex debug log at `ERROR`: `Triton <operation> failed, <n> log(s) dropped: <ExceptionType>: <message>`. Pharos can't be asked to log a failure that may be its own, so the debug log is where these surface.

### Runtime Configuration (`TritonHelper.Config`)

`TritonHelper.Config` is a lazily created `TritonHelper.TritonConfig` instance holding the org's `TritonSettings__c` switches and the parsed `Log_Level__mdt` rules. Every read is fail-safe: if a setting can't be read, the getter returns the default rather than throwing.

{% code lineNumbers="true" %}

```apex
if (!TritonHelper.Config.isLoggingDisabled()) {
    // build an expensive payload only when logging is on
}
```

{% endcode %}

#### isLoggingDisabled

{% code lineNumbers="true" %}

```apex
public Boolean isLoggingDisabled()
```

{% endcode %}

`true` when **Disable Logging** is set; every Triton entry point checks it first. Resolves to `false` (logging on) if the setting can't be read.

#### isFlowFlushBatchDisabled

{% code lineNumbers="true" %}

```apex
public Boolean isFlowFlushBatchDisabled()
```

{% endcode %}

`true` when **Disable Flow Flush Batch** is set, so Flow logs publish in the Flow's own transaction instead of through [`TritonFlowFlushBatch`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflowflushbatch). Resolves to `false` if the setting can't be read.

#### getCacheTtlSeconds

{% code lineNumbers="true" %}

```apex
public Integer getCacheTtlSeconds()
```

{% endcode %}

The lifetime of Triton's Org cache entries — the transaction id and buffered Flow logs — in seconds: **Cache TTL (minutes)** × 60, or 300 when the field is blank or negative.

#### getFlowFlushBatchDelayMinutes

{% code lineNumbers="true" %}

```apex
public Integer getFlowFlushBatchDelayMinutes()
```

{% endcode %}

How many minutes the deferred Flow flush batch waits before it runs: **Flow Flush Batch Delay (minutes)**, or 1 when the field is blank or negative.

#### isLogAllowed

{% code lineNumbers="true" %}

```apex
public Boolean isLogAllowed(pharos__Log__c log)
```

{% endcode %}

`true` when the log passes the `Log_Level__mdt` rules that target it. The most specific matching rule decides (User > Component > Area > Type > Category), and equally specific rules resolve to the most restrictive level. A log that no rule targets, a log with no level, and a log whose level can't be parsed are all allowed. `Triton.log()` calls this before buffering. See [Log Levels](https://triton.pharos.ai/core-concepts/log-levels).

#### hasComponentScopedLevels

{% code lineNumbers="true" %}

```apex
public Boolean hasComponentScopedLevels()
```

{% endcode %}

`true` when at least one rule sets **Component Name**. Triton then derives an Apex log's class from the stack trace before the level check, so component rules can match; orgs without such a rule skip that cost.

### Transaction Cache Methods

#### cacheTransactionId

{% code lineNumbers="true" %}

```apex
public static void cacheTransactionId(String transactionId)
```

{% endcode %}

Saves transaction ID to platform cache with user-specific key. Silently handles cache failures.

**Parameters:**

* `transactionId` - Transaction ID to cache

#### getCachedTransactionId

{% code lineNumbers="true" %}

```apex
public static String getCachedTransactionId()
```

{% endcode %}

Retrieves transaction ID from platform cache using user-specific key.

**Returns:**

* Cached transaction ID or null if not found

#### clearCachedTransactionId

{% code lineNumbers="true" %}

```apex
public static void clearCachedTransactionId()
```

{% endcode %}

Clears transaction ID from platform cache.

### Flow Log Cache Methods

These back the deferred Flow-log publishing pipeline (see [TritonFlowFlushBatch](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflowflushbatch)). Logs are stored as SObjects directly in Org Cache — no JSON serialization.

#### cacheFlowLogs

{% code lineNumbers="true" %}

```apex
public static Boolean cacheFlowLogs(String transactionId, List<pharos__Log__c> logs)
```

{% endcode %}

Saves Flow logs to Org Cache keyed by transaction ID (last write wins). Returns `true` on success, `false` if the write fails (e.g. size exceeded or cache unavailable).

#### getCachedFlowLogs

{% code lineNumbers="true" %}

```apex
public static List<pharos__Log__c> getCachedFlowLogs(String key)
```

{% endcode %}

Retrieves cached Flow logs for a key, or an empty list on failure.

#### getFlowLogCacheKeys

{% code lineNumbers="true" %}

```apex
public static Set<String> getFlowLogCacheKeys()
```

{% endcode %}

Returns all Org Cache keys matching the Flow-log prefix — used by the flush batch to discover pending logs across transactions.

#### removeFlowLogCacheKey

{% code lineNumbers="true" %}

```apex
public static void removeFlowLogCacheKey(String key)
```

{% endcode %}

Removes a Flow-log cache entry after processing.

#### removeFlowLogs

{% code lineNumbers="true" %}

```apex
public static void removeFlowLogs(String transactionId)
```

{% endcode %}

Removes one transaction's Flow-log cache entry. Null-safe. Used when Flow logs are published immediately, so that no later flush batch publishes them a second time.

### Stack Trace Methods

#### getCurrentStackTrace

{% code lineNumbers="true" %}

```apex
public static String getCurrentStackTrace()
```

{% endcode %}

Returns the current stack trace as a string, excluding any Triton-related entries.

**Returns:**

* Filtered stack trace with lines joined by newline characters

#### getOperation

{% code lineNumbers="true" %}

```apex
public static String getOperation(String stackTrace)
```

{% endcode %}

Extracts the operation (Class.Method) from a stack trace string, taking the topmost non-Triton entry.

**Parameters:**

* `stackTrace` - The stack trace string to parse

**Returns:**

* String in format "ClassName.MethodName"

#### formatExecutionContext

{% code lineNumbers="true" %}

```apex
public static String formatExecutionContext()
```

{% endcode %}

Detects and formats the current Salesforce execution context. For triggers: operation type, sObject name, and record count. For async contexts (batch, queueable, scheduled, future): the execution type. Returns an empty string for standard synchronous execution.

**Returns:**

* Formatted execution-context string, or empty string

#### formatDMLError

{% code lineNumbers="true" %}

```apex
public static String formatDMLError(Database.Error err, Id recordId)
```

{% endcode %}

Formats a DML error message including status code, record ID, and field-level information. Used by [`TritonBuilder.dmlResults()`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder#dmlresults-list-object-dmlresults).

**Parameters:**

* `err` - the `Database.Error` instance
* `recordId` - the ID of the record that caused the error

**Returns:**

* Formatted error message string

### Runtime Info Formatting

#### formatLwcRuntimeInfo

{% code lineNumbers="true" %}

```apex
public static String formatLwcRuntimeInfo(TritonLwc.RuntimeInfo runtime)
```

{% endcode %}

Formats runtime information from LWC into a readable string, including environment, performance, memory, network, and device details.

**Parameters:**

* `runtime` - The runtime info object to format

**Returns:**

* Formatted string with all runtime details

### Utility Methods

#### compareLevel

{% code lineNumbers="true" %}

```apex
public static Boolean compareLevel(TritonTypes.Level value, TritonTypes.Level toCompare)
```

{% endcode %}

Compares two log levels to determine if logging should proceed.

**Parameters:**

* `value` - The level to compare against (from settings)
* `toCompare` - The level being compared (from log)

**Returns:**

* `true` if value is greater than or equal to toCompare
* `false` if value is lower than toCompare

#### generateUUID4

{% code lineNumbers="true" %}

```apex
public static String generateUUID4()
```

{% endcode %}

Generates a UUID (Universal Unique Identifier) version 4. Used to create transaction IDs.

**Returns:**

* String containing a UUID4 formatted identifier

#### toJson (HTTP)

{% code lineNumbers="true" %}

```apex
public static String toJson(HttpRequest request, HttpResponse response)
```

{% endcode %}

Serializes HTTP request and response objects to JSON format for integration logging.

**Parameters:**

* `request` - HttpRequest instance
* `response` - HttpResponse instance

**Returns:**

* JSON string containing formatted request and response data

#### toJson (REST)

{% code lineNumbers="true" %}

```apex
public static String toJson(RestRequest request, RestResponse response)
```

{% endcode %}

Serializes REST request and response objects to JSON format for integration logging.

**Parameters:**

* `request` - RestRequest instance
* `response` - RestResponse instance

**Returns:**

* JSON string containing formatted request and response data

#### formatMessage (Single Parameter)

{% code lineNumbers="true" %}

```apex
public static String formatMessage(String template, String param)
```

{% endcode %}

Formats a message by replacing {0} placeholder with the provided parameter.

**Parameters:**

* `template` - Message template containing {0} placeholder
* `param` - Parameter to replace the placeholder

**Returns:**

* Formatted message string

#### formatMessage (Multiple Parameters)

{% code lineNumbers="true" %}

```apex
public static String formatMessage(String template, List<String> params)
```

{% endcode %}

Formats a message by replacing {0}, {1}, etc. placeholders with the provided parameters.

**Parameters:**

* `template` - Message template containing numbered placeholders
* `params` - List of parameters to replace the placeholders

**Returns:**

* Formatted message string

### Performance Mark Helpers

#### deriveMarkName

{% code lineNumbers="true" %}

```apex
public static String deriveMarkName(String stackTrace)
```

{% endcode %}

Derives a mark name (`<Class>.<method>`) from the topmost application frame of a stack trace — the name `Triton.startMark()` uses. Falls back to `AnonymousMark` plus a counter when no name can be derived, so it never returns blank.

#### requestId

{% code lineNumbers="true" %}

```apex
public static String requestId()
```

{% endcode %}

The current request id. It is the root of the span stack, and the span id of an Apex log emitted outside any mark.

#### Mark record constants

| Constant                                        | Value                     | Used for                           |
| ----------------------------------------------- | ------------------------- | ---------------------------------- |
| `MARK_STARTED_PREFIX`                           | `'Performance started: '` | Summary of a mark's opening record |
| `MARK_COMPLETED_PREFIX`                         | `'Performance: '`         | Summary of its completion record   |
| `MARK_DURATION_PREFIX` / `MARK_DURATION_SUFFIX` | `'Duration: '` / `'ms'`   | Details of the completion record   |

### Builder Class

#### PostProcessingControlsBuilder

Builder class for constructing Pharos post-processing settings. Controls various aspects of log enhancement after creation. You can find a more [detailed method reference here](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonhelper/postprocessingcontrolsbuilder).

**Methods**

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder auditTrail(Boolean value)
public PostProcessingControlsBuilder deployResult(Boolean value)
public PostProcessingControlsBuilder installedPackages(Boolean value)
public PostProcessingControlsBuilder area(Boolean value)
public PostProcessingControlsBuilder pendingJobs(Boolean value)
public PostProcessingControlsBuilder relatedObjects(Boolean value)
public PostProcessingControlsBuilder stackTrace(Boolean value)
public PostProcessingControlsBuilder userInfo(Boolean value)
public PostProcessingControlsBuilder totalActiveSession(Boolean value)
public PostProcessingControlsBuilder setAll(Boolean value)
```

{% endcode %}

Each method controls a specific aspect of post-processing:

* `auditTrail` - Controls fetching of recent audit trail
* `deployResult` - Controls fetching of recent deployments
* `installedPackages` - Controls fetching of installed package count
* `area` - Controls automatic functional area setting
* `pendingJobs` - Controls fetching of pending jobs in flow queue
* `relatedObjects` - Controls fetching of related object names
* `stackTrace` - Controls stack trace enhancement (Apex logs; also drives the payload viewer when request/response payloads are attached)
* `userInfo` - Controls fetching of User name
* `totalActiveSession` - Controls fetching of current logged-in user count
* `setAll` - Sets all flags to the provided value

**Build Method:**

{% code lineNumbers="true" %}

```apex
public String build()
```

{% endcode %}

Returns a JSON string representation of the post-processing controls.

**Example:**

{% code lineNumbers="true" %}

```apex
String controls = new TritonHelper.PostProcessingControlsBuilder()
    .stackTrace(true)
    .userInfo(true)
    .relatedObjects(true)
    .build();
```

{% endcode %}

#### IntegrationWrapper

Wrapper class for integration logs used to create the JSON structure that combines HTTP objects.

**Properties:**

* `request` - Map\<String, Object> containing request details
* `response` - Map\<String, Object> containing response details

This class is primarily used internally by the toJson methods to structure integration log data.

### Runtime Information Components

#### [`RuntimeInfo` (in TritonLwc)](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonlwc/runtimeinfo)

Captures detailed runtime information from Lightning Web Components:

* Environment details (user agent, platform, language)
* Performance metrics (page load time, DOM events, paint times)
* Memory usage statistics
* Network information (connection type, speed, RTT)
* Device characteristics (form factor, screen dimensions)
* Navigation context (pathname, hostname)


# PostProcessingControlsBuilder

A builder in TritonHelper.cls for setting the post-processing flags that control what Pharos does with a log after it is saved.

### setAll(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder setAll(Boolean value)
```

{% endcode %}

Sets all flags according to the Boolean value provided.

`value` -- Boolean value to set all flags to

### stackTrace(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder stackTrace(Boolean value)
```

{% endcode %}

Sets the stack trace post processing control. This is only applicable to Apex logs. When this value is set for an Apex log, Pharos will fetch a context-enriched stack trace and render a view showing several lines around each of the stack trace entries. When the log also carries request/response payloads (attached via `.integrationPayload(...)`), Pharos will render a Postman-like view of those payloads on the log record.

`value` -- Boolean value to set

### userInfo(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder userInfo(Boolean value)
```

{% endcode %}

Sets the user info post-processing control. If set to true, Pharos will automatically fetch the first and last name of the user based on user Id value from a log record. This will be used to show a link to the user record from the log detail page.

`value` -- boolean value to set

### area(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder area(Boolean value)
```

{% endcode %}

Sets the functional-area post processing control. If set to true, Pharos will automatically determine and set the functional area for the log record.

`value` -- Boolean value to set

### relatedObjects(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder relatedObjects(Boolean value)
```

{% endcode %}

Sets the related objects post processing control. If set to true Pharos will automatically fetch all labels of related object records based on related object Ids value from a log record.

`value` -- boolean value to set

### deployResult(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder deployResult(Boolean value)
```

{% endcode %}

Sets the deploy result post processing control. If set to true Pharos will automatically fetch the 10 most recent deployments that took place in your org.

`value` -- Boolean value to set

### auditTrail(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder auditTrail(Boolean value)
```

{% endcode %}

Sets the audit trail post processing control. If set to true Pharos will automatically fetch the org audit trail for the last 48 hours (if available).

`value` -- Boolean value to set

### pendingJobs(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder pendingJobs(Boolean value)
```

{% endcode %}

Sets the pending jobs post processing control. If set to true Pharos will automatically fetch all pending jobs currently in the flex queue.

`value` -- Boolean value to set

### totalActiveSession(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder totalActiveSession(Boolean value)
```

{% endcode %}

Sets the active sessions post processing control. If set to true Pharos will automatically fetch the total number of logged in users (active sessions).

`value` -- Boolean value to set

### installedPackages(Boolean value)

{% code lineNumbers="true" %}

```apex
public PostProcessingControlsBuilder installedPackages(Boolean value)
```

{% endcode %}

Sets the installed packages post processing control. If set to true Pharos will automatically fetch the names of all installed managed and unmanaged packages.

`value` -- Boolean value to set

### build()

{% code lineNumbers="true" %}

```apex
public String build()
```

{% endcode %}

Returns an instance of the post processing controls in JSON format. Pass the output of this method to the *postProcessing()* method in the *TritonBuilder* class as described [here](https://triton.pharos.ai/pages/ihlzZHBRL7drvUoMgiDI#postprocessing-tritonhelper.postprocessingcontrolsbuilder-postprocessingbuilder).


# TritonCacheManager

Centralizes Triton's Salesforce Platform Cache (Org cache) operations, with a test-friendly mock backend.

## Overview

`TritonCacheManager` wraps all of Triton's Platform Cache access. In production it delegates to `Cache.Org`; in test context it uses an in-memory map (because platform cache `put()` can succeed silently while `get()` returns null under test). It backs transaction-ID caching (via [`TritonHelper`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonhelper) and [`Triton.withCache()`](https://triton.pharos.ai/methods-reference/apex-methods-reference/triton#withcache)) and the deferred Flow-log buffer used by [`TritonFlowFlushBatch`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflowflushbatch).

This is an internal utility — you rarely call it directly.

## Org Cache Methods

#### put(String key, Object value, Integer ttl)

{% code lineNumbers="true" %}

```apex
public static void put(String key, Object value, Integer ttl)
```

{% endcode %}

Stores a value in Org cache under `key` with a time-to-live of `ttl` seconds.

#### get(String key)

{% code lineNumbers="true" %}

```apex
public static Object get(String key)
```

{% endcode %}

Retrieves a value from Org cache. Returns `null` when the key is absent.

#### getKeys()

{% code lineNumbers="true" %}

```apex
public static Set<String> getKeys()
```

{% endcode %}

Returns all keys currently in Org cache.

#### remove(String key)

{% code lineNumbers="true" %}

```apex
public static void remove(String key)
```

{% endcode %}

Removes a key from Org cache.

## Availability

#### available()

{% code lineNumbers="true" %}

```apex
public static Boolean available()
```

{% endcode %}

Returns `true` when Org cache is usable. `Triton.withCache()` uses this to decide whether to enable cache-backed transaction management.

**Returns:**

* `true` if Org cache is available (always `true` in test context), otherwise `false`


# TritonTestFactory

Shared @IsTest helper for setting up, building, flushing, and asserting Triton logs in your own test classes.

## Overview

`TritonTestFactory` is an `@IsTest` utility that consolidates the setup, record-creation, flush, query, and assertion helpers used across Triton's own tests. You can reuse it in your test classes to reduce boilerplate when exercising Triton logging.

## Setup & State

#### initTestSetup()

{% code lineNumbers="true" %}

```apex
public static void initTestSetup()
```

{% endcode %}

Standard test setup — initializes Pharos test settings and clears the `Log_Level__mdt` cache. Call from your `@TestSetup`.

#### resetFlowState()

{% code lineNumbers="true" %}

```apex
public static void resetFlowState()
```

{% endcode %}

Resets Flow-related static state: the [`TritonFlowFlushBatch`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflowflushbatch) pending buffer and the [`TritonCacheManager`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritoncachemanager) mock cache.

## Fault Injection

#### failPublishing()

{% code lineNumbers="true" %}

```apex
public static void failPublishing()
```

{% endcode %}

Makes every Triton publish in the current test fail, at the single path all publishing goes through. Use it to prove your code survives a publish that Pharos refuses: the logging calls still return normally, and nothing is persisted.

{% code lineNumbers="true" %}

```apex
@IsTest
static void saveSurvivesAFailedPublish() {
    TritonTestFactory.failPublishing();
    Test.startTest();
    insert new Account(Name = 'Acme');   // the instrumented trigger logs and flushes
    Test.stopTest();
    System.assertEquals(1, [SELECT COUNT() FROM Account]);
    TritonTestFactory.assertNoLogs();
}
```

{% endcode %}

#### restrictLevel(TritonTypes.Level l)

{% code lineNumbers="true" %}

```apex
public static void restrictLevel(TritonTypes.Level l)
```

{% endcode %}

Installs a single global `Log_Level__mdt` rule at level `l`, so every log more verbose than it is filtered out. Tests start with no `Log_Level__mdt` rules (the org's own are never loaded), so this one rule is the only filter for the rest of the test.

## Record Creation

#### makeFlowLog(String summary)

{% code lineNumbers="true" %}

```apex
public static TritonFlow.FlowLog makeFlowLog(String summary)
```

{% endcode %}

Creates a [`TritonFlow.FlowLog`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonflow/flowlog) with standard test defaults (category `Flow`, type `type`, area `area`).

#### makeLogRecord(String summary)

{% code lineNumbers="true" %}

```apex
public static pharos__Log__c makeLogRecord(String summary)
```

{% endcode %}

Creates a `pharos__Log__c` record with standard test defaults.

## Flush

#### flushCachedFlowLogs()

{% code lineNumbers="true" %}

```apex
public static void flushCachedFlowLogs()
```

{% endcode %}

Manually drains cached Flow logs by constructing a `TritonFlowFlushBatch` and executing it — needed because a delayed `System.scheduleBatch` does not run during `Test.stopTest()`.

## Assertions

#### assertNoLogs()

{% code lineNumbers="true" %}

```apex
public static void assertNoLogs()
```

{% endcode %}

Asserts that no `pharos__Log__c` records exist.

#### assertLogCount(Integer expected)

{% code lineNumbers="true" %}

```apex
public static void assertLogCount(Integer expected)
```

{% endcode %}

Asserts that exactly `expected` log records exist.

#### assertSingleLog(TritonTypes.Category expectedCategory)

{% code lineNumbers="true" %}

```apex
public static pharos__Log__c assertSingleLog(TritonTypes.Category expectedCategory)
```

{% endcode %}

Asserts exactly one log exists with a populated hash and returns it.

## Query Helpers

#### queryLogs()

{% code lineNumbers="true" %}

```apex
public static List<pharos__Log__c> queryLogs()
```

{% endcode %}

Returns all `pharos__Log__c` records with the commonly queried fields, ordered by creation date.

#### countFlowFlushBatchJobs()

{% code lineNumbers="true" %}

```apex
public static Integer countFlowFlushBatchJobs()
```

{% endcode %}

Returns the count of `TritonFlowFlushBatch` async apex jobs.

#### countActiveFlowFlushBatchJobs()

{% code lineNumbers="true" %}

```apex
public static Integer countActiveFlowFlushBatchJobs()
```

{% endcode %}

Returns the count of active (queued/processing) `TritonFlowFlushBatch` jobs.


# LogBuilder

Triton utilizes the builder design pattern to enable a quick and easy-to-read log creation routine.

## pharos.LogBuilder

This is a global managed class provided with the Pharos managed package. These methods aren't accessible for editing locally. For an overview of the builder class please refer to [this section](https://triton.pharos.ai/core-concepts/builder-and-templates).

{% hint style="info" %}
This class is used by [TritonBuilder](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder) that provides an abstraction layer over this managed class. The documentation here is provided mostly just for reference. For all practical purposes you can skip this class go straight to [TritonBuilder](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonbuilder).
{% endhint %}

### getInstance()

{% code lineNumbers="true" %}

```apex
global static LogBuilder getInstance()
```

{% endcode %}

This is a static method to create a new instance of the builder. Note that this is the only option to instantiate the builder class as the constructor is private.

### type(String value)

{% code lineNumbers="true" %}

```apex
global LogBuilder type(String value)
```

{% endcode %}

This method sets the type value on the log record (see [Type enum](https://triton.pharos.ai/core-concepts/enums)).

### summary(String value)

{% code lineNumbers="true" %}

```apex
global LogBuilder summary(String value)
```

{% endcode %}

This method sets the summary value on the log record. Summary will be truncated automatically to 255 characters as necessary.

### details(String value)

{% code lineNumbers="true" %}

```apex
global LogBuilder details(String value)
```

{% endcode %}

This method sets the details value on the log record.

### category(String value)

{% code lineNumbers="true" %}

```apex
global LogBuilder category(String value)
```

{% endcode %}

This method sets the category value on the log record (see [Category enum](https://triton.pharos.ai/core-concepts/enums)).

### stackTrace(String value)

{% code lineNumbers="true" %}

```apex
global LogBuilder stackTrace(String value)
```

{% endcode %}

This method sets the stack trace on the log record. Pharos will use this value to render a graphical stack trace for Apex code. For everything else, a text representation of the stack trace will be provided.

### area(String value)

{% code lineNumbers="true" %}

```apex
global LogBuilder area(String value)
```

{% endcode %}

This method sets the area (functional area) value on the log record (see [Area enum](https://triton.pharos.ai/core-concepts/enums)).

### postProcessing(String settingsJSON)

{% code lineNumbers="true" %}

```apex
global LogBuilder postProcessing(String settingsJSON)
```

{% endcode %}

This method sets the post processing controls that signal to Pharos the types of post processing to perform on a log record. Use the [*PostProcessingControlsBuilder*](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritonhelper/postprocessingcontrolsbuilder) to build the settings and serialize them to JSON.

### transactionId(String value)

{% code lineNumbers="true" %}

```apex
global LogBuilder transactionId(String value)
```

{% endcode %}

This method sets the transaction Id on a log record.

### createIssue()

{% code lineNumbers="true" %}

```apex
global LogBuilder createIssue()
```

{% endcode %}

Calling this method will signal to Pharos to create an Issue from this log record. By default, no Issue records are created for custom logs.

### attribute(String field, Object value)

<pre class="language-apex"><code class="lang-apex"><strong>global LogBuilder attribute(String field, Object value)
</strong></code></pre>

This methods set any field on a log record to the specified value. Please refer to [this section](https://triton.pharos.ai/core-concepts/builder-and-templates#custom-attributes) for more details.

### build()

{% code lineNumbers="true" %}

```apex
global pharos__Log__c build()
```

{% endcode %}

This methods will return the final log record. Call this method once you've set all the attributes. The output of this method can be provided to the [logging methods](https://triton.pharos.ai/methods-reference/apex-methods-reference).


# LWC

## File Index

#### [`triton.js`](https://github.com/Pharos-AI/triton-docs/tree/release/2.0/methods-reference/triton.md)

The main JavaScript class that provides core logging functionality for Lightning Web Components:

* Implements singleton pattern for logging instance management
* Manages log buffering and auto-flush mechanisms
* Handles transaction context and span hierarchy across the component lifecycle
* Provides methods for different logging levels (ERROR, WARNING, DEBUG, INFO)
* Includes performance profiling APIs (marks, backend calls, user interactions, lifecycle/render tracking)

#### [`tritonBuilder.js`](https://github.com/Pharos-AI/triton-docs/tree/release/2.0/methods-reference/tritonbuilder.md)

A builder class that provides a fluent interface for creating structured log entries:

* Implements builder pattern for constructing log objects
* Handles setting of various log attributes (level, category, type, area)
* Manages component context and runtime information
* Supports error handling and stack trace processing

#### [`tritonUtils.js`](https://github.com/Pharos-AI/triton-docs/tree/release/2.0/methods-reference/tritonutils.md)

Provides utility functions for the logging framework:

* Stack trace analysis and component identification
* Transaction ID generation (UUID v4)
* Runtime information capture
* Component context extraction
* Error stack processing


# Triton

## Overview

The `Triton` class is a singleton logger for Lightning Web Components (and Aura). It manages log buffering, transaction context, span hierarchy, component-scoped templates, and performance profiling. Import the default export and construct it — the same instance is returned every time.

{% code lineNumbers="true" %}

```javascript
import Triton from 'c/triton';

const triton = new Triton();
```

{% endcode %}

## Constructor

### Triton()

* **Description**: Creates or returns the singleton Triton instance. Initializes transaction management, span context, and the performance tracker.
* **Returns**: `{Triton}` The singleton instance

## Component Binding

### bindToComponent(componentId)

* **Description**: Returns a component-scoped logger (a Proxy) that tags logs with the component, isolates its template, and enables performance tracking. Call once per component (typically in `connectedCallback`) and use the returned instance for all logging in that component.
* **Parameters**:
  * `componentId`: `{string}` Unique component identifier
* **Returns**: `{Proxy}` Scoped logger instance
* **Example**:

{% code lineNumbers="true" %}

```javascript
this.logger = new Triton().bindToComponent('myComponent');
```

{% endcode %}

{% hint style="info" %}
Performance tracking methods (`startPerformanceMark`, `trackComponentRender`, etc.) require a component-bound instance from `bindToComponent()`.
{% endhint %}

## Transaction Methods

### startTransaction()

* **Description**: Generates and stores a new transaction ID, resets the span context to the new root, clears performance marks, and starts the auto-flush monitor.
* **Returns**: `{string}` The generated transaction ID

### resumeTransaction(transactionId)

* **Description**: Resumes an existing transaction and resets the span context to it.
* **Parameters**:
  * `transactionId`: `{string}` Existing transaction ID to resume

### stopTransaction()

* **Description**: Stops the current transaction and auto-flush monitor, flushes remaining logs, and clears the span context.
* **Returns**: `{Promise}` Settles once the final flush has been attempted; never rejects

## Span Context

### enterStep(stepSpanId)

* **Description**: Enters a new logical step (e.g. a wizard step), resetting the span stack to the transaction root and pushing a new span for the step.
* **Parameters**:
  * `stepSpanId`: `{string}` *(optional)* Custom span ID (auto-generated if omitted)
* **Returns**: `{string}` The span ID for this step

### enableSpanPersistence()

* **Description**: Enables `sessionStorage` persistence for the span context stack, so the span hierarchy survives navigation in multi-page flows.

## Logging Methods

Each of these returns a [`TritonBuilder`](https://triton.pharos.ai/methods-reference/lwc/tritonbuilder) pre-populated with runtime info, transaction ID, timestamp, and span context. Chain additional attributes, then pass it to `log()` / `logNow()`.

### makeBuilder()

* **Description**: Creates a new builder with default settings (user ID, category, runtime info, transaction ID, timestamp, and span context applied).
* **Returns**: `{TritonBuilder}` New builder instance

### exception(error)

* **Description**: Creates an `ERROR`-level builder from a JavaScript `Error` (or an Apex error with a `body`). The server opens a Pharos issue for it.
* **Parameters**:
  * `error`: `{Error}` Error object to log
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### error(type, area)

* **Description**: Creates an error-level builder.
* **Parameters**:
  * `type`: `{string}` Log type from `TYPE`
  * `area`: `{string}` An `AREA` constant or any custom area string
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### warning(type, area)

* **Description**: Creates a warning-level builder.
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### debug(type, area)

* **Description**: Creates a debug-level builder.
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### info(type, area)

* **Description**: Creates an info-level builder.
* **Returns**: `{TritonBuilder}` Builder instance for chaining

## Template Methods

Templates are scoped to the bound component.

### setTemplate(builder)

* **Description**: Stores a builder as the reusable template for the calling component.
* **Parameters**:
  * `builder`: `{TritonBuilder}` Builder to use as template

### fromTemplate()

* **Description**: Creates a new builder from the component's saved template (or a default builder if none was set), refreshed with current runtime/transaction/span context.
* **Returns**: `{TritonBuilder}` New builder instance

## Buffer Management

### log(builder)

* **Description**: Adds a log builder to the buffer (capturing component details from the current stack).
* **Parameters**:
  * `builder`: `{TritonBuilder}` Builder instance to log
* **Returns**: `{TritonBuilder}` The builder instance

### logNow(builder)

* **Description**: Immediately sends a single log builder to the server; the rest of the buffer stays buffered. Never rejects: if the server can't take the log, it stays in the buffer for later flushes (see [`flush()`](#flush)).
* **Parameters**:
  * `builder`: `{TritonBuilder}` Builder instance to log
* **Returns**: `{Promise}` Resolves with the server response, or `undefined` if the flush failed or the argument wasn't a builder

### flush()

* **Description**: Sends all buffered logs to the server and clears the buffer. Never rejects. On failure the logs go back into the buffer for the next flush; after the third failure in a row they're dropped. After a failed flush, the buffer is trimmed to the newest 500 logs (`Triton.MAX_BUFFERED_LOGS`).
* **Returns**: `{Promise}` Resolves with the server response, or `undefined` when there was nothing to flush or the flush failed

## Performance & Profiling

These methods require a component-bound instance (see [`bindToComponent`](#bindtocomponent-componentid)). For end-to-end guides, see [Profiling](https://triton.pharos.ai/beyond-apex/profiling). Profiling records start from the component's template, so they inherit its Area.

### startPerformanceMark(markName)

* **Description**: Starts a performance mark for timing an operation, pushes a span for it, and logs the opening `Performance` record at `FINE`.
* **Parameters**:
  * `markName`: `{string}` Name of the mark
* **Returns**: `{string}` The mark name (or `null` if not component-bound)

### endPerformanceMark(markName)

* **Description**: Ends a performance mark and logs a `Performance` entry at `FINE` with the measured duration.
* **Parameters**:
  * `markName`: `{string}` Mark name used in `startPerformanceMark`

### timeBackendCall(methodName, apexCall)

* **Description**: Times an Apex call, logging start, completion (with duration), and any error as `BackendCall` entries — start and completion at `FINE`, a failure at `ERROR`.
* **Parameters**:
  * `methodName`: `{string}` Name of the method being called
  * `apexCall`: `{Function}` Function returning the Apex call promise
* **Returns**: `{PerformanceCallBuilder}` Builder — call `.execute()` to run
* **Example**:

{% code lineNumbers="true" %}

```javascript
const accounts = await this.logger
    .timeBackendCall('getAccounts', () => getAccounts({ ids }))
    .execute();
```

{% endcode %}

### timeUserInteraction(interactionName, interaction)

* **Description**: Times a user interaction, logging it as a `UserInteraction` entry at `FINE` (a failure at `ERROR`).
* **Parameters**:
  * `interactionName`: `{string}` Name of the interaction
  * `interaction`: `{Function}` Function to execute and time
* **Returns**: `{PerformanceCallBuilder}` Builder — call `.execute()` to run

### trackComponentLifecycle(lifecycleEvent)

* **Description**: Logs a `ComponentLifecycle` entry at `FINER` for the given event (e.g. `connected`, `disconnected`, `rendered`).
* **Parameters**:
  * `lifecycleEvent`: `{string}` Lifecycle event name

### trackComponentRender()

* **Description**: Logs a `ComponentRender` entry at `FINEST` and increments the component's render count.

### PerformanceCallBuilder

Returned by `timeBackendCall` and `timeUserInteraction`. Configure error handling, then run with `execute()`.

* `withoutRethrow()` — do not rethrow errors after handling. Returns the builder.
* `withCustomErrorHandler(errorHandler)` — supply a custom error handler `(error, context) => {}`. Returns the builder.
* `execute()` — runs the call with the configured handling. Returns a `{Promise}` of the result.

## Enums

### AREA

The values are the Apex `TritonTypes.Area` names, so LWC logs group with the Apex and Flow logs of the same feature. `.area(...)` also accepts any other string as a custom area.

{% code lineNumbers="true" %}

```javascript
{
    ACCOUNTS: 'Accounts',
    COMMUNITY: 'Community',
    LEAD_CONVERSION: 'LeadConversion',
    OPPORTUNITY_MANAGEMENT: 'OpportunityManagement',
    REST_API: 'RestAPI'
}
```

{% endcode %}

### CATEGORY

{% code lineNumbers="true" %}

```javascript
{
    LWC: 'LWC',
    AURA: 'Aura'
}
```

{% endcode %}

### LEVEL

{% code lineNumbers="true" %}

```javascript
{
    ERROR: 'ERROR',
    WARNING: 'WARNING',
    INFO: 'INFO',
    DEBUG: 'DEBUG',
    FINE: 'FINE',
    FINER: 'FINER',
    FINEST: 'FINEST'
}
```

{% endcode %}

### TYPE

{% code lineNumbers="true" %}

```javascript
{
    BACKEND: 'Backend',
    FRONTEND: 'Frontend',
    BACKEND_CALL: 'BackendCall',
    COMPONENT_LIFECYCLE: 'ComponentLifecycle',
    COMPONENT_RENDER: 'ComponentRender',
    USER_INTERACTION: 'UserInteraction',
    PERFORMANCE: 'Performance'
}
```

{% endcode %}


# TritonBuilder

## Overview

The `TritonBuilder` class implements a builder pattern for creating structured log entries in LWC and Aura components. It provides a fluent interface for setting log attributes and metadata. Obtain one from [`triton.makeBuilder()`](https://triton.pharos.ai/methods-reference/lwc/triton#makebuilder) or a level method, then chain attributes and pass it to `log()` / `logNow()`.

## Classification Methods

### level(level)

* **Description**: Sets the log level.
* **Parameters**:
  * `level`: `{string}` Log level from `LEVEL`
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### category(category)

* **Description**: Sets the log category.
* **Parameters**:
  * `category`: `{string}` Log category from `CATEGORY`
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### type(type)

* **Description**: Sets the log type.
* **Parameters**:
  * `type`: `{string}` Log type from `TYPE`
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### area(area)

* **Description**: Sets the functional area. Pass an `AREA` constant or any string — reuse the area your Apex code uses, so the feature's logs group together. A custom string is kept as sent; leave the area unset and the log lands under `LWC`.
* **Parameters**:
  * `area`: `{string}` An `AREA` constant or a custom area
* **Returns**: `{TritonBuilder}` Builder instance for chaining

## Content Methods

### summary(summary)

* **Description**: Sets the log summary message.
* **Parameters**:
  * `summary`: `{string}` Brief description of the log entry
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### details(details)

* **Description**: Sets detailed log information.
* **Parameters**:
  * `details`: `{string}` Detailed description or additional context
* **Returns**: `{TritonBuilder}` Builder instance for chaining

## Error Handling

### exception(error)

* **Description**: Sets the level to `ERROR` — so the server opens a Pharos issue, as Apex's `.exception(e)` does — and populates error message, stack, and type from a JavaScript `Error` (or an Apex error with a `body`), deriving component details from the stack. A `.level(...)` chained after it wins. A missing error (a promise rejected with no reason) only sets the level.
* **Parameters**:
  * `error`: `{Error|Object}` Error object to process
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### componentDetails(stack)

* **Description**: Extracts the calling function name and cleaned stack trace from a stack string.
* **Parameters**:
  * `stack`: `{string}` Stack trace to process
* **Returns**: `{TritonBuilder}` Builder instance for chaining

## Metadata Methods

### transactionId(transactionId)

* **Description**: Sets the transaction ID for log correlation.
* **Parameters**:
  * `transactionId`: `{string}` Transaction identifier
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### duration(duration)

* **Description**: Sets execution duration in milliseconds.
* **Parameters**:
  * `duration`: `{number}` Duration in milliseconds
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### action(action)

* **Description**: Sets the action name — e.g. a performance mark, backend call, or user-interaction name.
* **Parameters**:
  * `action`: `{string}` Action name
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### spanId(spanId)

* **Description**: Sets the span ID identifying this log's unit of work.
* **Parameters**:
  * `spanId`: `{string}` Span identifier
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### parentSpanId(parentSpanId)

* **Description**: Sets the parent span ID, linking this log into a trace hierarchy.
* **Parameters**:
  * `parentSpanId`: `{string}` Parent span identifier
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### timestamp(timestamp)

* **Description**: Sets the log creation timestamp.
* **Parameters**:
  * `timestamp`: `{number}` Unix timestamp (e.g. `Date.now()`)
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### userId(userId)

* **Description**: Sets the user ID associated with the log.
* **Parameters**:
  * `userId`: `{string}` Salesforce user ID
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### relatedObjects(objectIds)

* **Description**: Sets related object IDs. Accepts a single ID or an array; null/empty values are filtered out.
* **Parameters**:
  * `objectIds`: `{string|string[]}` One or more Salesforce record IDs
* **Returns**: `{TritonBuilder}` Builder instance for chaining

### runtimeInfo(info)

* **Description**: Sets runtime environment information (usually captured automatically via `captureRuntimeInfo()`).
* **Parameters**:
  * `info`: `{Object}` Runtime environment details
* **Returns**: `{TritonBuilder}` Builder instance for chaining

## Utility

### clone()

* **Description**: Creates a deep copy of the builder (used for component templates).
* **Returns**: `{TritonBuilder}` New builder instance with copied properties

### build()

* **Description**: Constructs the final log object from all set properties, ready to send to the server.
* **Returns**: `{Object}` Complete log object
* **Example**:

{% code lineNumbers="true" %}

```javascript
const logEntry = triton.makeBuilder()
    .level(LEVEL.INFO)
    .type(TYPE.FRONTEND)
    .summary('User action completed')
    .build();
```

{% endcode %}


# TritonUtils

## Overview

The `tritonUtils` module provides utility functions for stack-trace analysis, transaction ID generation, and runtime information capture. Import the named exports you need:

{% code lineNumbers="true" %}

```javascript
import { isNotTriton, generateTransactionId, captureRuntimeInfo, getFunctionName } from 'c/tritonUtils';
```

{% endcode %}

## Stack Trace Analysis

### isNotTriton(stackTraceLine)

* **Description**: Checks whether a stack-trace line is **not** from an internal Triton file or method — used to filter Triton frames out of captured stacks.
* **Parameters**:
  * `stackTraceLine`: `{string}` Line from a stack trace
* **Returns**: `{boolean}` `true` if the line is not from Triton internals
* **Example**:

{% code lineNumbers="true" %}

```javascript
const isUserCode = isNotTriton('at MyComponent.handleClick (/modules/c/myComponent.js:15:10)');
```

{% endcode %}

### getFunctionName(stackTraceLine)

* **Description**: Extracts the function name from a stack-trace line.
* **Parameters**:
  * `stackTraceLine`: `{string}` Line from a stack trace
* **Returns**: `{string}` The function name, or an empty string if none is found
* **Example**:

{% code lineNumbers="true" %}

```javascript
const fn = getFunctionName('at MyComponent.handleClick (/modules/c/myComponent.js:15:10)');
// Returns: "MyComponent.handleClick"
```

{% endcode %}

## Transaction Management

### generateTransactionId()

* **Description**: Generates a UUID v4 (random UUID). Used for transaction and span IDs.
* **Returns**: `{string}` A UUID in the format `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`
* **Example**:

{% code lineNumbers="true" %}

```javascript
const transactionId = generateTransactionId(); // e.g. "550e8400-e29b-41d4-a716-446655440000"
```

{% endcode %}

## Runtime Information

### captureRuntimeInfo()

* **Description**: Captures comprehensive runtime information about the current environment. Each capture group is wrapped in try/catch so a failure in one area never blocks the others.
* **Returns**: `{Object}` Object containing environment, viewport, theme, performance, memory, network, and device details
* **Example**:

{% code lineNumbers="true" %}

```javascript
const runtimeInfo = captureRuntimeInfo();
console.log(runtimeInfo.viewportWidth); // e.g. 1920
console.log(runtimeInfo.platform);      // e.g. "Windows"
```

{% endcode %}

The returned object includes:

{% code lineNumbers="true" %}

```javascript
{
    // Environment
    userAgent, language, platform, mobile, brands, theme,
    viewportWidth, viewportHeight,
    // Performance
    pageLoadTime, domInteractive, domContentLoaded, firstByte, serverTime,
    firstPaint, firstContentfulPaint,
    // Memory
    memoryUsage, memoryLimit,
    // Network
    connectionType, connectionSpeed, connectionRtt, saveData,
    pathname, hostname, isOnline,
    // Device
    formFactor, screenWidth, screenHeight, orientation
}
```

{% endcode %}


# 2.0

Release notes for Pharos Triton 2.0 — a breaking release with a static, builder-first API, distributed tracing with spans, and Apex performance marks.

> **Status:** Released — version 2.0.0, November 5, 2026

{% hint style="info" %}
**Requirements.** Pharos Triton 2.0.0 requires the Pharos package at version **2.284.5 or later**. Upgrade Pharos first, then install or deploy Triton.
{% endhint %}

{% hint style="danger" %}
**2.0 is a major release with breaking API changes.** Four changes require edits to existing code — three of them fail to compile:

* **The singleton entry point is gone.** `Triton.instance` has been replaced by a static, builder-first API; every `Triton.instance.*` call must be rewritten.
* **`TritonTypes.Category.Integration` is removed.** Callout and integration logging keeps the default `Apex` category — an integration log is identified by `.integrationPayload(request, response)` plus a call type such as `TritonTypes.Type.BackendCall`, not by a category of its own.
* **`TritonTypes.Category.Warning`, `.Event`, and `.Debug` are removed.** The enum is now exactly `Apex` · `Flow` · `LWC` · `Aura`. Category answers "what technology produced this log"; severity lives in the log **Level**.
* **The LWC `CATEGORY` export lost `WARNING`, `DEBUG`, and `EVENT`.** `import { CATEGORY } from 'c/triton'` now yields only `LWC` and `AURA`. JavaScript isn't compiled, so a removed key silently evaluates to `undefined` rather than erroring — the log still lands, re-categorized, with a note in Details.

`Log_Level__mdt` rules keyed on a removed category stop matching. See [Category is now origin-only](#category-is-now-origin-only) and [Upgrade notes](#upgrade-notes).
{% endhint %}

## Highlights

* **New static, builder-first API.** `Triton` is now called statically — no more `Triton.instance`. Logs are composed with a builder and passed to level methods: `Triton.info(...)`, `Triton.error(...)`, `Triton.logNow(...)`. A `Triton.t` shorthand builds from the active template. See [The new logging API](#the-new-logging-api).
* **Logging never fails your code.** `Triton.log(...)`, the level methods, `logNow`, `flush`, `flushTop`, and the mark methods catch their own failures, as do the Flow **Log** action and the LWC logger's server call. A log that can't be published is dropped and noted in the Apex debug log; your transaction carries on. See [Logging never fails your code](#logging-never-fails-your-code).
* **Distributed tracing with spans.** New `spanId()` / `parentSpanId()` builder methods and `Span_Id__c` / `Parent_Span_Id__c` fields let you correlate work across transactions and services, alongside the existing `traceable()` / `tracePoint()` traceability controls.
* **Performance marks in Apex.** New `Triton.startMark()` / `Triton.endMark()` time a stretch of Apex, emit a paired set of `Performance` records, and parent every log created inside the mark to it — with the mark name derived from the stack trace, so call sites carry no hand-typed strings. `startTriggerMark()` adds the trigger context a stack trace can't supply. See [Performance marks in Apex](#performance-marks-in-apex).
* **Platform-cache transaction management.** A new `TritonCacheManager` centralizes Org cache operations, and `Triton.withCache()` ties a transaction id across LWC / Apex / Flow hops using the platform cache.
* **Deferred flushing to conserve platform events.** New `Triton.drain()` and `Triton.flushTop()`, plus a `TritonFlowFlushBatch`, let Flow and high-volume logging hand work off for batched publishing instead of consuming platform-event allocations inline.
* **Org-level runtime configuration.** A new `TritonSettings__c` custom setting adds a master **Disable Logging** kill switch, a **Disable Flow Flush Batch** switch, and **Cache TTL** / **Flow Flush Batch Delay** knobs, while `Log_Level__mdt` gains **Component** and **User** matching with most-specific-rule-wins resolution — all editable from Pharos Admin. See [Runtime configuration & admin controls](#runtime-configuration--admin-controls).
* **Level and convenience builder methods.** `TritonBuilder` gains `.error()`, `.warning()`, `.info()`, `.debug()`, `.fine()`, `.finer()`, `.finest()` (with optional summary overloads), plus `.exception(e)`, `.dmlResults(...)`, `.apexExecutionContext()`, and `.operation(...)`.
* **Flow version capture.** The Flow **Log** action gains a **Flow Version** input and `TritonBuilder` gains `.flowVersion(Decimal)`, writing `pharos__Flow_Version__c` — so a Flow log carries the plain API name and its version separately, the way native Flow error logs do. See [Flow version capture](#flow-version-capture).
* **Log-level rule evaluation fixed.** User-scoped rules now match for Apex logs, blank rule fields are true wildcards, and a malformed rule or an unparsable level can no longer break a transaction or drop a log. See [Log-level rule fixes](#log-level-rule-fixes) — one of these changes can also widen rules you already have, so read the [Upgrade notes](#upgrade-notes) too.
* **Overhauled test infrastructure.** A new `TritonTestFactory`, an expanded `TritonTest`, and a new `TritonFlowTest` bring comprehensive coverage of the static API, caching, and tracing.
* **Instrumentation skills + OpenTelemetry readiness.** Eight agent-agnostic instrumentation skills take a codebase from audit → migrate → instrument → guard: read-only coverage reports, 1.x → 2.0 conversion, per-technology instrumentation for Apex, LWC, and Flows, org-wide orchestration in reviewed batches, CI guardrails, and a persona that runs the whole catalog — each with a human-in-the-loop diff review and an optional deploy. Combined with the new spans/tracing model, this makes your org **OTEL-ready**: Triton's trace/span/parent-span concepts map cleanly onto OpenTelemetry. See [Instrumentation skills (companion tooling)](#instrumentation-skills-companion-tooling) and [OpenTelemetry readiness](#opentelemetry-readiness).

## The new logging API

The most significant change in 2.0 is the move from a singleton instance to a **static, builder-first** API.

**Before (1.42 and earlier):**

```apex
try {
    // ...
} catch (Exception e) {
    Triton.instance.error(TritonTypes.Area.OpportunityManagement, e);
}
```

**After (2.0):**

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

### Static log methods

`Triton` exposes buffered and immediate log methods, all of which accept a `TritonBuilder`:

| Method                                                        | Behavior                         | Level                              |
| ------------------------------------------------------------- | -------------------------------- | ---------------------------------- |
| `Triton.log(builder)`                                         | Buffer the log                   | uses builder's level               |
| `Triton.error(builder)`                                       | Buffer the log                   | overrides to ERROR                 |
| `Triton.warning(builder)`                                     | Buffer the log                   | overrides to WARNING               |
| `Triton.info(builder)`                                        | Buffer the log                   | overrides to INFO                  |
| `Triton.debug(builder)`                                       | Buffer the log                   | overrides to DEBUG                 |
| `Triton.fine(builder)` / `finer(builder)` / `finest(builder)` | Buffer the log                   | overrides to FINE / FINER / FINEST |
| `Triton.logNow(builder)`                                      | Buffer **and** flush immediately | uses builder's level               |

Buffered logs are persisted when you call `Triton.flush()` (all logs), `Triton.flushTop()` (only the most recent), or `Triton.drain()` (hand the buffer off without publishing).

### Templates and the `Triton.t` shorthand

Set a reusable template once, then start each log from it. `Triton.t` is shorthand for `Triton.fromTemplate()` and automatically carries the active transaction id:

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

Triton.info(Triton.t.summary('Fetching items').details('...'));
Triton.error(Triton.t.summary('Failed').exception(e));
Triton.logNow(Triton.t.summary('Critical').error().exception(e));
```

### Convenience builder methods

`TritonBuilder` now carries the level and common configuration itself:

* **Level methods** — `.error()`, `.warning()`, `.info()`, `.debug()`, `.fine()`, `.finer()`, `.finest()`, each with an optional `(String summary)` overload.
* **`.exception(Exception e)`** — one call sets the type (from the exception type, or `Backend`), ERROR level, summary, details, stack trace, and flags issue creation. The issue follows the final level: downgrade the log below ERROR — `Triton.warning(Triton.t.exception(e))`, say — and the issue is withdrawn. An explicit `.createIssue()` always keeps it.
* **`.dmlResults(List<Object>)`** — formats `Database.SaveResult`/`DeleteResult`/`UpsertResult`/`UndeleteResult`/`MergeResult` collections. When any row failed, the log becomes a `DMLResult` at ERROR with the failed ids, the error messages, and an issue. When every row succeeded — or the list is null or empty — nothing is emitted, whichever method you pass the builder to, so no `if` is needed around it. `isSuppressed()` reports that state.
* **`.apexExecutionContext()` / `.operation(String)`** — capture the current execution context and label the operation.

## Logging never fails your code

A logging call should never be the reason a transaction fails. In 2.0, `Triton.log(...)`, the level methods (`Triton.error(...)` through `Triton.finest(...)`), `Triton.logNow(...)`, `Triton.flush()`, `Triton.flushTop()`, and the performance-mark methods catch their own failures. So do the Flow **Log** action, the deferred Flow flush batch, and the server call behind the LWC logger. When Pharos can't accept a publish — because the running user lacks a license or a permission, for example — the affected logs are dropped and one `ERROR` line is written to the Apex debug log. The business work goes ahead.

Three limits remain:

* **Builder arguments run in your code.** The builder expression — `Triton.t.relatedObjects(Trigger.newMap.keySet())`, say — is evaluated before Triton is called, so Triton can't catch what throws there. Keep builder arguments null-safe.
* **`System.LimitException` can't be caught** by any Apex. In bulk code, buffer with `Triton.log(...)`, flush once at a boundary, and keep per-log details lean.
* **`Triton.stopTransaction()` can still throw when `withCache()` is enabled**, if clearing the cached transaction id fails.

See [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing#when-publishing-fails) and, for trigger handlers, [Instrument Apex](https://triton.pharos.ai/instrumentation-skills/instrument-apex#trigger-handlers-logging-never-fails-the-write).

## Category is now origin-only

`TritonTypes.Category` answers exactly one question — **what technology produced this log** — and the enum is now exactly:

`Apex` · `Flow` · `LWC` · `Aura`

`Integration`, `Warning`, `Event`, and `Debug` are gone. `Warning`, `Event`, and `Debug` described *severity*, which is what the log **Level** is for. `Integration` described a *kind of work*, which is what the Type and the attached payload are for.

**Logging a callout.** Keep the default `Apex` category and identify the log by its call type and payload:

```apex
HttpResponse response = new Http().send(request);

Triton.info(Triton.t
    .type(TritonTypes.Type.BackendCall)
    .integrationPayload(request, response)
    .summary('Loan application pushed'));
```

An integration log is an ordinary Apex log with the HTTP exchange attached — see [Integration Logs](https://triton.pharos.ai/common-apex-usage-patters/integration-logs).

**Deployed Flows and LWCs keep logging.** A Flow **Log** action or an LWC that still passes a removed category string is not dropped. The entry is re-categorized to `Flow` or `LWC`, and a diagnostic note is appended to **Details**. The two tiers word it differently, so search for both:

| Source | Note appended to Details                                                      |
| ------ | ----------------------------------------------------------------------------- |
| Flow   | `Unable to locate category: Integration. Default Flow category will be used.` |
| LWC    | `Invalid Log Category: Integration. Default LWC category will be used.`       |

Treat those notes as a to-do list: they name precisely which Flows and components still pass a category that no longer exists.

**Apex gets no such grace.** Apex referencing a removed enum member no longer compiles against 2.0.

**Historical logs are untouched.** Category is stored as a string on the log record, so logs written before the upgrade keep whatever they were written with.

**`Log_Level__mdt` rules need re-keying.** A rule keyed on `Integration`, `Warning`, `Event`, or `Debug` does **not** error — the Category field is free text, so the rule simply stops matching anything and that slice of logs falls back to whatever broader rule applies. Re-key those rules to a real origin category, or to a Level. See [Upgrade notes](#upgrade-notes).

## Distributed tracing with spans

2.0 adds span-based tracing on top of Triton's existing transaction id and traceability:

* **`spanId(String)`** — set the current span identifier (stored on `Span_Id__c`).
* **`parentSpanId(String)`** — link to a parent span (stored on `Parent_Span_Id__c`).
* **`traceable(Boolean)`** — mark a builder as traceable (also flags issue creation, which stands at any level).
* **`tracePoint()`** — emit a trace point when the builder is traceable.

The corresponding LWC layer (`TritonLwc` / `triton.js`) was updated to carry span and parent-span identifiers so front-end interactions can participate in the same trace. This aligns Triton's model with distributed-tracing conventions — see the [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing) guide for how these map to spans and traces.

## Performance marks in Apex

Apex reaches parity with the LWC performance marks. A **mark** times a stretch of code, emits a paired set of records, and builds a span tree as it goes:

```apex
Triton.startMark();          // name derived from the stack trace
try {
    recalculateForecast();
} finally {
    Triton.endMark();
}
```

| Method                      | Behavior                                                                              |
| --------------------------- | ------------------------------------------------------------------------------------- |
| `Triton.startMark()`        | Open a mark named `<Class>.<method>`, derived from the stack trace. Returns the name. |
| `Triton.startMark(String)`  | Open a mark with an explicit name, for names that aren't method names.                |
| `Triton.endMark()`          | Close the innermost open mark.                                                        |
| `Triton.endMark(String)`    | Close the newest mark with that name, for out-of-order completion.                    |
| `Triton.clearMarks()`       | Discard all open marks and reset to the request root.                                 |
| `Triton.startTriggerMark()` | Open a mark named `<Handler>.<Trigger.operationType>`. Zero arguments.                |

* **Paired records.** A mark publishes `Performance started: <mark>` when it opens and `Performance: <mark>` with `Duration: <n>ms` when it closes, both on the same span — the same prefixes the LWC marks use, so both tiers render identically.
* **Ambient parenting.** Marks nest LIFO, and an ordinary log emitted inside a mark becomes a child of it instead of a flat sibling. The outermost mark parents to the transaction span. Ids you set with `.spanId(...)` / `.parentSpanId(...)` are never overwritten.
* **Starting a transaction no longer destroys an open mark.** `Triton.startTransaction()` resets the span hierarchy only when no mark is open. An LWC log save or a Flow **Log** action firing inside an open Apex mark used to discard that mark along with its unwritten completion record; now the mark survives and closes normally. `Triton.clearMarks()` remains the explicit way to reset.
* **Suppression is transparent.** If a `Log_Level__mdt` rule filters out a mark's opening record, its children re-parent to the nearest surviving ancestor rather than being orphaned.
* **Buffered, always `FINE`.** No mark method flushes, and there is no `level` argument — verbosity stays an admin's `Log_Level__mdt` decision rather than a constant baked into a call site.
* **Batch and async need no new API.** `Triton.resumeTransaction(carriedId)` (if you carry one) followed by `Triton.startMark()` is the whole idiom; each chunk begins as its own subtree under the shared transaction.

{% hint style="warning" %}
**Marks are opt-in, and they reshape span fields once used.** Code that never calls `startMark` produces exactly the span fields it does today. Inside an open mark, `Span_Id__c` on an ordinary log becomes a fresh UUID rather than the request id — move any query, report, or dashboard that used `Span_Id__c == requestId` to mean "belongs to request X" onto **`pharos__Request_Id_External__c`**, which is where that fact actually lives. `Parent_Span_Id__c` also goes from always-null to populated, and each mark adds two records to the log volume. A mark filtered out by log levels is still an *open* mark, so it still reshapes the logs around it.
{% endhint %}

Full guide: [Performance Marks in Apex](https://triton.pharos.ai/common-apex-usage-patters/performance-marks).

## Flow version capture

Flow logs now record the flow's version in a field of its own instead of folding it into the name — the same split native Flow error logs use:

* **Flow → Log action:** a new optional **Flow Version** input (`flowVersion`), alongside the existing **Flow API Name**. Flow passes it as a string.
* **Apex:** `TritonBuilder.flowVersion(Decimal)`, written to `pharos__Flow_Version__c`. The managed field is Text, so the number is stored in its canonical string form.

A value Triton can't parse never fails the log: it appends `Unable to parse flow version: <value>. Flow Version will not be set.` to **Details** and saves the log without the version.

{% hint style="warning" %}
**Manual step for already-instrumented Flows: `flowApiName` must be the plain API name.** Component-scoped `Log_Level__mdt` rules match the Flow API Name **verbatim**, so a version-suffixed value like `My_Flow-4` will not match a rule naming `My_Flow`. Put the plain name in **Flow API Name** and the number in **Flow Version**. See [Upgrade notes](#upgrade-notes).
{% endhint %}

## LWC logging changes

The LWC logger changed in ways that mostly need no code edits but can change what you see:

* **`AREA` values are now the Apex area names.** `AREA.ACCOUNTS` is `'Accounts'`, `AREA.LEAD_CONVERSION` is `'LeadConversion'`, and so on, so LWC logs group with the Apex and Flow logs of the same feature. The server also maps the old spellings (`'LEAD_CONVERSION'`, in any casing) to the same names, so a page loaded before the upgrade still groups correctly.
* **Custom areas are kept.** `.area('OrderEntry')` from LWC now lands as `OrderEntry`, exactly as it does from Apex and Flow. Previously any value outside the enum was recorded as `LWC`, with a note.
* **Blank means "not set".** An LWC log with no area lands under `LWC`, and one with no level lands at `INFO`, with no note in Details. This applies to LWC only: the Flow **Log** action still appends `Unable to locate log level: null` for a blank level. A non-blank, invalid level still gets its note.
* **`exception(error)` sets `ERROR`** on any builder, as in Apex, so the log opens an issue. A `.level(...)` chained after it still wins.
* **Profiling records have levels.** Backend-call, user-interaction, and performance-mark records log at `FINE`; a failed backend call or interaction at `ERROR`, with an issue; lifecycle tracking at `FINER`; render tracking at `FINEST`. They start from the component's template, so they carry its Area. See [Profiling](https://triton.pharos.ai/beyond-apex/profiling#levels-and-area).
* **`flush()` and `logNow()` never reject.** A failed flush keeps its logs for the next one and drops them after the third failure in a row. After a failed flush, the buffer is trimmed to the newest 500 logs (`Triton.MAX_BUFFERED_LOGS`). `stopTransaction()` returns a promise that settles once its final flush has been attempted.

## OpenTelemetry readiness

The tracing model above isn't just useful inside Pharos — it's what makes a 2.0 org **OpenTelemetry-ready**. Triton's three correlation primitives line up directly with OTel's tracing vocabulary:

| OpenTelemetry concept | Triton 2.0 equivalent                                                                                            |
| --------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **Trace**             | The transaction id (`Triton.TRANSACTION_ID` / `this.triton.transactionId`) correlating one end-to-end operation. |
| **Span**              | `Span_Id__c`, set via `.spanId(...)`.                                                                            |
| **Parent span**       | `Parent_Span_Id__c`, set via `.parentSpanId(...)`.                                                               |

Because the concepts map cleanly, instrumented Triton logs carry the structure an observability stack expects, and they're a solid foundation for a future OpenTelemetry integration.

{% hint style="warning" %}
**Readiness, not a shipped exporter.** Triton 2.0 is **not** an OpenTelemetry SDK and does **not** emit OTLP — there is no OTEL exporter in the package. "OTEL-ready" means the data model aligns with OpenTelemetry's, giving you a clean path toward one. Treat trace / span / parent span as an accurate mental model, not a drop-in pipeline. Full mapping: [Spans & Distributed Tracing → How this maps to OpenTelemetry](https://triton.pharos.ai/end-to-end/spans-and-tracing#how-this-maps-to-opentelemetry).
{% endhint %}

## Instrumentation skills (companion tooling)

2.0 is accompanied by a set of **agent-agnostic instrumentation skills** — portable playbooks surfaced as `/pharos:` slash commands in agents that support them (and runnable from any coding agent) — that automate adding Triton instrumentation to existing code, following the 2.0 static API and Triton best practices:

**Instrument one technology:**

* **`/pharos:instrument-apex`** — instruments Apex classes and triggers: structure-aware resume-first transactions, `logNow` + rethrow in catches, `.dmlResults(...)` on partial DML, callout `integrationPayload`, `System.debug` → `Triton.debug`, and flush at the right boundaries. Trigger handlers get write-safe logging (null-safe builder arguments, one flush, a restricted-user test), and batch classes take the caller's transaction id rather than starting their own.
* **`/pharos:instrument-lwc`** — adds the `c/triton` logger, `bindToComponent`, and `timeBackendCall` (which carries span context), plus transaction stitching to Apex. It reuses the paired Apex area string and scales profiling with `--perf essential|standard|deep`.
* **`/pharos:instrument-flows`** — inserts `TritonFlow` "Log" actions with individual named inputs, instrumenting flow entry and every fault path.

**Work across a codebase:**

* **`/pharos:audit-logging`** — a read-only scan that reports logging gaps and a prioritized instrumentation plan. Writes no source files; run it first for the map. It also flags publishes inside triggers on managed-package objects for review.
* **`/pharos:migrate-to-2.0`** — converts 1.x `Triton.instance` code to the 2.0 static API, stopping to ask on every call where a rename would silently change immediate-vs-buffered publishing. It covers every 1.x overload, checks that the target library skips successful DML results, and verifies that no 1.x member or removed enum value survives. It rewrites Apex only.
* **`/pharos:instrument-org`** — orchestrates the three per-technology skills across a whole project: consistent Areas per feature, transaction stitching across LWC → Apex → Flow, and a review checkpoint every batch.
* **`/pharos:setup-standards`** — scaffolds the guardrails that keep an instrumented codebase instrumented: CI checks for `System.debug` and `Triton.instance`, a PR review checklist, and `Log_Level__mdt` defaults.
* **`/pharos:instrumentation-agent`** — the persona that ties the catalog together and runs the full audit → migrate → instrument → guard sequence end to end, pausing for you between stages.

Each skill runs a **human-in-the-loop** loop — prerequisites check → analyze → apply → **diff review (yes / modify / skip)** → write → optional `--deploy` via the Salesforce CLI — so nothing is written until you approve it. Run them repeatedly (or loop an agent) across a backlog to roll out consistent instrumentation quickly.

{% hint style="info" %}
**Companion tooling — ships alongside 2.0, not inside the package.** The skills live in the Triton repository's `agent-skills/` directory on the 2.0 line. They are **not** part of the Triton package and are never deployed into an org — they're developer tooling you run from your coding agent against your local project, and the code they generate targets Triton 2.0. See the [Instrumentation Skills](https://triton.pharos.ai/instrumentation-skills) section for full usage.
{% endhint %}

## Platform-cache transaction management

A new **`TritonCacheManager`** centralizes platform cache access (Org cache). Transaction handling is now cache-aware:

* **`Triton.withCache()`** — enable platform cache for transaction management; resumes an existing cached transaction id if present, otherwise starts a new one. Falls back gracefully when cache is unavailable.
* **`Triton.startTransaction()` / `resumeTransaction(id)` / `stopTransaction()`** — now cache the transaction id (and extend its TTL) when caching is enabled, making it easier to correlate logs across LWC / Apex / Flow transitions.

## Deferred flushing & Flow batching

To reduce platform-event (PE) consumption under load, 2.0 introduces deferred flushing:

* **`Triton.drain()`** — returns all buffered logs and clears the buffer without publishing, so a caller (such as Flow) can hand them off for batched processing.
* **`Triton.flushTop()`** — publishes only the most recent buffered log immediately.
* **`TritonFlowFlushBatch`** — a batch class that flushes Flow-originated logs, integrating with the cache manager so Flow logging consumes fewer PE allocations.

If a flush batch can't be scheduled, the Flow logs it has already collected are published straight away, so a scheduling failure never strands them, and no Flow log is published twice. Keep the **Flow Flush Batch Delay** below the **Cache TTL**: Flow logs still waiting in the cache when the TTL expires are never published.

## Runtime configuration & admin controls

2.0 moves logging behavior under org-level runtime configuration — a new `TritonSettings__c` custom setting plus richer `Log_Level__mdt` matching — all editable from the **Triton** area of Pharos Admin (Configuration → **Settings** / **Log Levels**) without a code change or redeploy.

**Global switches (`TritonSettings__c`):**

* **Disable Logging** — a master kill switch. When set, all Triton logging (Apex, Flow, LWC) is short-circuited before logs are built or persisted.
* **Disable Flow Flush Batch** — when set, Flow logs flush immediately (synchronously, in-transaction) instead of via the delayed `TritonFlowFlushBatch`. Either way, logging never fails the Flow.

**Operational knobs (`TritonSettings__c`):**

* **Cache TTL (minutes)** — lifetime of Triton's Org-cache entries (the transaction id and buffered Flow logs). Blank uses the packaged default (5 minutes).
* **Flow Flush Batch Delay (minutes)** — how long the flush batch waits before it runs. Blank uses the packaged default (1 minute).

**Log-level matching (`Log_Level__mdt`):**

* Rules now match on **Component** and **User** in addition to Category / Type / Area, so you can scope verbosity down to a single class, LWC, Flow, or user.
* When several rules target a log, the **most specific** one wins and overrides the others in *both* directions — a narrow rule can raise *or* lower verbosity for its slice. Specificity is ranked User > Component > Area > Type > Category. See [Log Levels](https://triton.pharos.ai/core-concepts/log-levels).
* A **Log Level page layout** now ships with the rule fields — Level, Category, Type, Area, Component Name, and User Id — so rules can be created and edited from Setup as well as from Pharos Admin.
* The **Component Name** help text now matches the behavior: an Apex log matches by class name whether its operation was set explicitly or derived from the stack trace.

**Transaction-id cache moved to Org cache.** Transaction correlation now uses Salesforce **Org** cache instead of Session cache, so a cached transaction id survives across asynchronous and session-less contexts (Batch, Queueable, Scheduled, `@future`). See [Transactions & Platform Cache](https://triton.pharos.ai/end-to-end/transactions-and-cache).

### Log-level rule fixes

Four fixes to how `Log_Level__mdt` rules are evaluated. All four make rules behave the way the field labels already promised:

* **User-scoped rules now actually match.** `build()` stamps `pharos__User_Id__c` with `UserInfo.getUserId()` when nothing else set it, so a **User** rule is evaluated against a real user id at filter time. Previously a User rule was inert for Apex logs: the id was filled in at flush time, after filtering had already run.
* **Blank rule fields are true wildcards.** A field holding `''` or whitespace now behaves exactly like an empty one. Previously only a genuine `null` was a wildcard, so a rule saved with a blank-looking field could silently match nothing.
* **Matching on Category, Type, Area, and Component is case-insensitive.** These are free-text fields typed by hand, so `apex` and `Apex` now mean the same thing. **User Id stays case-sensitive**, compared on its 15-character form — Salesforce Ids are case-sensitive base-62, and folding their case would collide distinct users. This change can widen rules you already have; see [Upgrade notes](#upgrade-notes).
* **A bad rule can no longer break a transaction.** A malformed `Log_Level__mdt` row — one with a blank **Level**, for instance — is skipped instead of throwing into the host transaction, and a log whose own level is unparsable is kept rather than dropped. Filtering fails open: when Triton can't decide, the log survives.

See [Log Levels](https://triton.pharos.ai/core-concepts/log-levels) for how rules are scoped and resolved.

## Governor-limit tracking

Limit tracking is now **automatic**. 1.42 captured limits only when you asked for them; in 2.0 every Apex and Flow log captures the essential set at log time — SOQL queries and rows, DML statements and rows, CPU time, heap size, and callouts — each alongside its governor ceiling. Call `withFullLimitInfo()` on the builder to add the extended set (aggregate queries, SOSL queries, `@future` calls, queueable jobs, email invocations, push notifications, async (batch) calls, and immediate-publish DML), or `withoutLimitInfo()` to skip limits for that log. LWC logs carry no limit data.

{% hint style="warning" %}
**Four limit fields ship unpopulated.** `Callout_Time__c`, `SOQL_Rows_Retrieved__c`, `Scheduled_Jobs__c`, and `Script_Statements__c` exist on `pharos__Log__c`, but **nothing writes them in 2.0** — no builder method populates them, and the Log Limits component neither reads nor renders them. They also have no companion `_Limit__c` field, so there is no ceiling to measure them against. Expect them to be blank on every log, and don't build reports, dashboards, or alerts on them.
{% endhint %}

## Permission set updates

`Triton_Read` and `Triton_Write` were updated to include the new span fields — `Span_Id__c` and `Parent_Span_Id__c`. Both sets also grant Apex class access to `LogLimitsController`, which the Log Limits component on the Log record page needs.

After deploying 2.0, **re-assign the permission sets** (or refresh them through your deployment pipeline) so users pick up the new field-level access — and if you deploy the sets separately from the rest of 2.0, deploy them **after** the span fields, never before. Both steps are load-bearing: see [Upgrade notes](#upgrade-notes) for what breaks if you skip either, and [Configure Permissions](https://triton.pharos.ai/installing-pharos-triton#configure-permissions) for what each set grants.

## Test suite

The Apex test infrastructure was substantially reworked:

* **`TritonTestFactory`** — a new factory for constructing test logs and builders against the static API.
* **`TritonTest`** — significantly expanded to cover static access, caching, spans, and deferred flushing.
* **`TritonFlowTest`** — a new test class covering Flow logging and the flush batch.

## Upgrade notes

* **Install Pharos 2.284.5 or later first.** Triton 2.0 depends on it.
* **Installing over 1.x code?** Salesforce refuses the whole install while any Apex class or trigger still calls 1.x, and lists only the first few compile errors. [Upgrading an Org from 1.x](https://triton.pharos.ai/migration/upgrading-an-org) shows how to find every dependent and land your migrated code together with 2.0.
* **Breaking: the singleton is gone.** Replace all `Triton.instance.<method>(...)` calls with the static, builder-first equivalents. For example, `Triton.instance.error(area, e)` — which published immediately — becomes `Triton.logNow(Triton.t.area(area).exception(e))`, and the buffered `Triton.instance.addError(area, e)` becomes `Triton.error(Triton.t.area(area).exception(e))`. See [Migrating from 1.x](https://triton.pharos.ai/migration).
* **Breaking: categories are origin-only.** `TritonTypes.Category` is now exactly `Apex` · `Flow` · `LWC` · `Aura`; `Integration`, `Warning`, `Event`, and `Debug` are removed, and Apex referencing them won't compile. Also **re-key any `Log_Level__mdt` rule that named a removed category** — and note that a stale rule gives you no warning: the Category field is plain text, not a picklist, so the rule doesn't error, it just silently stops matching and that slice of logs reverts to whatever broader rule applies. Deployed Flows and LWCs keep logging with a diagnostic note in Details; historical logs keep their stored category strings. Full detail: [Category is now origin-only](#category-is-now-origin-only).
* **Fix up `flowApiName` on already-instrumented Flows.** Component-scoped log levels match the Flow API Name verbatim, so a version-suffixed value such as `My_Flow-4` will not match a rule naming `My_Flow`. Move the version into the new **Flow Version** input and leave the plain API name behind. See [Flow version capture](#flow-version-capture).
* **Case-insensitive rule matching can widen rules you already have.** Category / Type / Area / Component now match case-insensitively, so a rule field typed `apex` — which previously matched nothing, because the log's category is `Apex` — now matches every Apex log. Review your existing `Log_Level__mdt` rows for values whose case doesn't match what they were meant to target: a rule that had quietly never fired may start firing after the upgrade.
* **Buffered vs immediate naming changed.** The old `add*` (buffer) / bare (instant) method pairs are replaced by `Triton.log(...)` / level methods (buffer) and `Triton.logNow(...)` (immediate). Audit any code that relied on the instantaneous default methods to ensure logs are still flushed when expected.
* **Upgrade Triton&#x20;*****before*****&#x20;you deploy the Triton permission sets.** `Triton_Read` and `Triton_Write` grant `Span_Id__c` and `Parent_Span_Id__c` — fields Triton adds to `pharos__Log__c` itself — so deploying the sets into an org still on an older Triton fails with an invalid-field error. This error depends on your Triton version, not your Pharos package version. Upgrade Triton first, then deploy the permission sets, then re-assign them; a single deploy of the whole 2.0 source works too, because the fields and the sets land together. If you've already hit the error, finish the Triton upgrade and deploy again — nothing needs undoing.
* **Re-assign the permission sets — and know what a missing `Triton_Write` costs.** Re-assignment isn't cosmetic. Triton publishes a platform event, and a separate subscriber process performs the `pharos__Log__c` insert; if that subscriber's running user lacks `Triton_Write`, **logs still land — silently missing their limit and span data, with no error raised anywhere.** So **empty essential limit fields (SOQL, DML, CPU, heap, callouts) on new Apex or Flow logs are a permission-set symptom first**: check the subscriber's permission sets before you go looking at governor limits. The extended limit fields stay blank unless a log asked for `withFullLimitInfo()`, and LWC logs carry no limit data at all. See [Configure Permissions](https://triton.pharos.ai/installing-pharos-triton#configure-permissions).
* **Platform cache is opt-in.** Call `Triton.withCache()` to enable cache-backed transaction management; without it, behavior falls back to the standard transaction id handling.
* **Tracing is additive.** `spanId()`, `parentSpanId()`, `traceable()`, and `tracePoint()` are optional; existing logs continue to work without them.
* **Marks are opt-in, but they reshape span fields once used** — including `Span_Id__c` on ordinary logs inside a mark. See [Performance marks in Apex](#performance-marks-in-apex) before adopting them.
* **Re-check LWC `Log_Level__mdt` rules.** LWC profiling records now log at `FINE` and below (failures at `ERROR`), so a rule at `INFO` or stricter for LWC logs now drops the backend-call, interaction, and mark spans it used to keep. Set that rule — or a `Type`-scoped one — to `FINE` where you want those spans in production. See [LWC logging changes](#lwc-logging-changes).
* **LWC code that compared area strings, or relied on `logNow()` rejecting.** Area values are now `'Accounts'`-style, and `flush()` / `logNow()` resolve even when the server can't take the logs, so a `.catch(...)` on them no longer runs.
* **Deploying the source yourself?** The Triton repository's `.forceignore` excludes `**/__tests__/**` and `**/__mocks__/**`, but a `.forceignore` only governs its own project. Once you vendor `force-app`, add both lines to your project's `.forceignore`, or a deploy can reject the LWC Jest tests.


# 1.42

Release notes for Pharos Triton 1.42 — LWC performance tracking, Apex governor-limit tracking, full Jest coverage, and Log\_\_c metadata fixes.

> **Source commit:** [adaa303](https://github.com/Pharos-AI/triton/commit/adaa303e9a40bb7afe52036163fee5c89a3f38a7)
>
> **Released:** 2026-05-26

## Highlights

* **LWC performance tracking is now a first-class feature.** A reworked `triton.js`, `tritonBuilder.js`, and `tritonUtils.js` introduce `timeBackendCall`, `timeUserInteraction`, `trackComponentLifecycle`, `trackComponentRender`, and `startPerformanceMark`/`endPerformanceMark` — all per-instance isolated and Locker Service-safe. See [Profiling](https://triton.pharos.ai/beyond-apex/profiling).
* **Apex governor-limit tracking on `TritonBuilder`.** New `limitInfo()`, `limitInfoLite()`, `withFullLimitInfo()`, and `withoutLimitInfo()` methods capture transaction usage and limits from `System.Limits`, plus a new `Action__c` field and `action(String)` builder method.
* **Full Jest test coverage** for `triton`, `tritonBuilder`, and `tritonUtils`, with a new `TESTING.md`, `jest.config.js`, and `jest.setup.js` at the repo root.
* **`pharos__Log__c` metadata fixes.** Missing XML attributes restored on all limit fields, plus permission set updates so the new fields are immediately readable/writable.

## LWC performance tracking

The LWC module gains a complete performance-tracking surface that piggy-backs on the existing logger:

| API                                                       | Purpose                                                                                                                                                                                              | Log type                   |
| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
| `bindToComponent(name)`                                   | Required anchor for all profiling APIs. Generates a per-instance UUID so multiple instances on a page stay isolated.                                                                                 | n/a                        |
| `timeBackendCall(name, () => apexCall)`                   | Wrap Apex calls; emits start/complete/failure logs with duration. Returns a `PerformanceCallBuilder` with four error-handling scenarios (default, `withoutRethrow`, `withCustomErrorHandler`, both). | `TYPE.BACKEND_CALL`        |
| `timeUserInteraction(name, async fn)`                     | Wrap a higher-level user flow that may contain nested backend calls. Same builder/error-handling model.                                                                                              | `TYPE.USER_INTERACTION`    |
| `trackComponentLifecycle('connected'\|'disconnected')`    | Log mount/unmount events per instance.                                                                                                                                                               | `TYPE.COMPONENT_LIFECYCLE` |
| `trackComponentRender()`                                  | Increment a per-instance render counter and log it.                                                                                                                                                  | `TYPE.COMPONENT_RENDER`    |
| `startPerformanceMark(name)` / `endPerformanceMark(name)` | Browser-style timing for arbitrary regions, isolated per component instance.                                                                                                                         | `TYPE.PERFORMANCE`         |

The `TYPE` enum has expanded accordingly:

{% code lineNumbers="true" %}

```javascript
export const TYPE = {
    BACKEND: 'Backend',
    FRONTEND: 'Frontend',
    BACKEND_CALL: 'BackendCall',
    COMPONENT_LIFECYCLE: 'ComponentLifecycle',
    COMPONENT_RENDER: 'ComponentRender',
    USER_INTERACTION: 'UserInteraction',
    PERFORMANCE: 'Performance'
};
```

{% endcode %}

Time measurement uses a Locker Service-safe helper that prefers `performance.now()` and falls back to `Date.now()` when the Performance API is restricted. Per-instance state (marks, render counts, lifecycle events) is keyed by `componentName-uuid`, so two instances of the same component on a page never collide.

Full walkthrough: [Profiling](https://triton.pharos.ai/beyond-apex/profiling).

## Apex governor-limit tracking on TritonBuilder

`TritonBuilder` (Apex) now captures transaction usage from `System.Limits` directly onto the log record. There are two modes, controlled by builder methods that compose with the rest of the fluent API.

* `limitInfoLite()` — populates the essential set: SOQL queries/rows, DML statements/rows, CPU time, heap size, callouts (and their corresponding `*_Limit__c` companion fields).
* `limitInfo()` — calls `limitInfoLite()` and, if `withFullLimitInfo()` has been chained earlier, also captures the extended set: aggregate queries, SOSL queries, future calls, queueable jobs, email invocations, push notifications, batch (async) calls, publish-immediate DML — and their limits.
* `withFullLimitInfo()` — opt in to the extended set on the next `limitInfo()` call.
* `withoutLimitInfo()` — opt out entirely; `limitInfo()` becomes a no-op for this builder.

In addition, `TritonBuilder` exposes a new `action(String)` method that writes to the new **`Action__c`** field on `pharos__Log__c`. The field is used by the LWC performance-tracking layer to record method names, interaction names, and mark names, and is also available to Apex callers that want to tag logs with an action label.

## `pharos__Log__c` field metadata fixes

All limit-related fields on `pharos__Log__c` had missing XML attributes that prevented some attributes from being recognized correctly. The affected fields:

* `Batch_Jobs__c`, `Batch_Jobs_Limit__c`
* `CPU_Time__c`, `CPU_Time_Limit__c`
* `Callouts__c`, `Callouts_Limit__c`
* `DML_Rows__c`, `DML_Rows_Limit__c`
* `DML_Statements__c`, `DML_Statements_Limit__c`
* `Email_Invocations__c`, `Email_Invocations_Limit__c`
* `Future_Calls__c`, `Future_Calls_Limit__c`
* `Heap_Size__c`, `Heap_Size_Limit__c`
* `Publish_Immediate_DML__c`, `Publish_Immediate_DML_Limit__c`
* `Push_Notifications__c`, `Push_Notifications_Limit__c`
* `Queueable_Jobs__c`, `Queueable_Jobs_Limit__c`
* `SOQL_Aggregates__c`, `SOQL_Aggregates_Limit__c`
* `SOQL_Queries__c`, `SOQL_Queries_Limit__c`
* `SOQL_Rows__c`, `SOQL_Rows_Limit__c`
* `SOSL_Queries__c`, `SOSL_Queries_Limit__c`

The new `Action__c` field was added under the same object.

## Permission set updates

Both `Triton_Read` and `Triton_Write` permission sets were updated to include the new `Action__c` field and ensure consistent access to the fixed limit fields. After deploying 1.42, re-assign the permission sets (or refresh them via your deployment pipeline) so users pick up the new field-level access.

## Test suite

A complete Jest test suite has been added under `force-app/main/default/lwc/*/__tests__/`:

* `lwc/triton/__tests__/triton.test.js` — full coverage of the core class, including `PerformanceCallBuilder`.
* `lwc/tritonBuilder/__tests__/tritonBuilder.test.js` — full coverage of the builder.
* `lwc/tritonUtils/__tests__/tritonUtils.test.js` — full coverage of utility helpers.

The repo now ships with `babel.config.js`, `jest.config.js`, `jest.setup.js`, and Jest-mock stubs under `jest-mocks/` so contributors can run `npm test` out of the box. See `TESTING.md` in the Triton repo for the full developer workflow.

## Upgrade notes

* **No breaking API changes.** All new LWC profiling methods and Apex builder methods are additive. Existing Apex and LWC callers continue to work unchanged.
* **Permission sets must be re-assigned (or re-deployed) after upgrade** so the new `Action__c` field and the fixed limit fields are visible to users.
* **LWC profiling APIs require `bindToComponent()` first.** If you call `timeBackendCall`, `trackComponentLifecycle`, etc. on an unbound instance, Triton emits a console warning and skips the call — nothing throws. Existing components that already bind for logging purposes get profiling support for free.
* **Limit info is opt-in.** Calling `limitInfo()` from Apex requires explicit invocation; existing builders won't suddenly start writing limit data unless you call it. Use `withFullLimitInfo()` to opt into the extended set.


# Help and Support

Instructions for getting support on Pharos or Triton.

If you find yourself stuck with Pharos Triton or Pharos, for that matter, don't worry! We're here to help. There are several ways to get in touch:

## Troubleshooting heuristic: is this a permissions problem?

A permission gap fails **every** log, loudly, with a class-access or DML/field-level-security error. If logs are only sometimes missing, or disappearing without any error surfacing anywhere, it is not a permissions problem — look at governor limits, log levels (see [Log Levels](https://triton.pharos.ai/core-concepts/log-levels)), or platform event allocation instead. See [Configure Permissions](https://triton.pharos.ai/installing-pharos-triton#configure-permissions) for what each permission set actually grants.

* Email us at <support@pharos.ai> and mention *Triton* in the subject.
* Use the chat in Pharos Admin (part of the Pharos app in Salesforce). See instructions below:

{% embed url="<https://app.arcade.software/share/UDzDCXlHBWwIRBmbezgA>" %}
*Support Chat Instructions*
{% endembed %}

* If you find an issue with Triton specifically, or have a feature request in mind, feel free to file a [GitHub issue here](https://github.com/Pharos-AI/triton/issues/new/choose).
* If you have some general feedback or thoughts that you'd like to share, [create a Discussion here](https://github.com/Pharos-AI/triton/issues/new?assignees=\&labels=\&projects=\&template=general.md\&title=).


# About Pharos Triton

Just as the mighty Triton delivered important messages from the deep, Pharos Triton sends you crucial insights from the depths of your Salesforce automation.

{% embed url="<https://app.arcade.software/share/QwpFqaCj9KfWB26kQe4z>" %}
*Pharos Triton Intro*
{% endembed %}

***

## Ready to Dive In?

{% content-ref url="/pages/uv1BtXe1otT4BF6Xs9s4" %}
[Installing Pharos Triton](https://triton.pharos.ai/1-42/installing-pharos-triton)
{% endcontent-ref %}

## Why Logging?

If you've spent any time on the Salesforce platform, you probably know that, by default, Salesforce does not generate any logs in its standard setup. You probably also know that exception emails and debug logs don't quite cut it if you’re trying to manage and troubleshoot an org. The former is simply unmanageable and the latter is extremely limited. With all its complexity the platform offers no solution to a common engineering problem: what went wrong, when, and how. Troubleshooting even a slightly complex automation can quickly take a turn for the worst. It's akin to stumbling around a dark room in hopes that you'll trip over a problem and then magically identify a solution. This exercise can be time consuming, frustrating and downright hazardous to one's mental state.

For all these reasons, many engineers have taken matters into their own hands and embarked on a logging journey. If Salesforce doesn't save logs for us, then we will!

Thus the idea of logging frameworks was born. Throughout the years these frameworks have evolved to the point that nowadays thousands of developers and admins all over the ecosystem are forever grateful to the source that is omniscient and wise: the Log.

## Pharos vs Pharos Triton

You might be wondering what's the deal with Pharos? Is it the same as Pharos Triton or completely different? Are they related? If it's all Greek to you, please allow us to elaborate.

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FsDnQTGGNL9WwCYbK2Cfm%2Fimage%20(20).png?alt=media&amp;token=89e97479-7f6b-4d36-a5dc-634fa4b32ab4" alt=""><figcaption><p><em>The Mighty Triton - Messenger From the Depths Of the Sea</em></p></figcaption></figure>

### Pharos

Pharos is a Salesforce native observability platform. It is composed of several layers: tracking, awareness, action, collaboration, and resolution.

As an observability platform Pharos does much more than create logs. It provides an entire suite of functionality that relies on log data, such as notifications, analytics, grouping, monitoring, issue tracking, and so forth. Pharos is able to automatically create log records from certain system events that the Salesforce platform makes available. There's quite a bit of data in those system events.

However, that is not the only log ingestion method available. This is where Triton comes in.

### Pharos Triton

Pharos Triton is a component of the larger observability platform that is Pharos. It is responsible for ingesting log data from your automation, custom rest APIs, even emails. The diagram below outlines the various components of Pharos. Note the section on the bottom right in blue. This is Pharos Triton.

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FxSMHfTKTOV3863uGu4z9%2FPharos%20Observability%20Platform.png?alt=media&amp;token=bc780b31-01f7-4cfd-aa58-c93f6fe19240" alt=""><figcaption><p><em>Components of the Pharos Observability Platform and Pharos Triton</em></p></figcaption></figure>

## What Exactly Does Pharos Triton Do?

Simply put, Pharos Triton is a logging framework for all things Salesforce. It allows creating logs from your automation whether it's code or declarative. A log record can contain any number of useful data points: debug info, warnings or even integration payloads. But really, you can log anything you need.

Pharos Triton provides a set of convenient interfaces for building logs and saving them to your Salesforce org. Sounds simple, right? Well, it is! And that's the whole premise behind this particular framework. We've crafted a number of helper classes for most of today's Salesforce logging needs. The best part is, if we missed something, you can extend and customize Pharos Triton's capabilities as you see fit.

Pharos Triton can also serve as a connector between Salesforce and other external systems, such as Mulesoft. By utilizing Triton's logging capabilities you can ingest any data from anywhere and transform into a log record that then feeds into the larger functionality of the Pharos platform.

## How Does Pharos Triton Compare to Other Logging Frameworks?

When it comes to features and functionality, Pharos Triton is a top-tier logging framework. If you're familiar with Nebula logger library, you'll find Pharos Triton is just as powerful and is easier to navigate and extend. Pharos Triton utilizes platform events for persisting logs, and offers some pre-canned interfaces for you to use in Apex, LWC and flows.

What really sets Pharos Triton apart from something like Nebula is that it's not just a log util. You get a lot more functions to work with, including automated error capture, fingerprinting and categorization, issue tracking and lots of pre-canned dashboards to view and analyze log data. And let's not forget Slack and Teams notifications! Also, unlike Nebula, Pharos is a commercial solution, so you can rely on getting support for any issues you might encounter—even with the free tier.

## Is Pharos Triton Free?

The short answer is yes. The Pharos platform [is offered in multiple editions](https://pharos.ai/pricing), including a free tier. The Pharos Triton component can be used with any Pharos edition. It's just a matter of selecting how much observability functionality you want to utilize and which edition of the Pharos platform best meets your needs. You can absolutely use Triton with a free tier of Pharos without any loss of logging functionality.

## Logging Use Cases

The world of logging is vast and diverse. In theory, what you could achieve with logging is only limited by your imagination. That said, here are several common directions you could take on your logging journey.

### Troubleshooting

Troubleshooting typically refers to identifying a root cause of a problem that's known to happen. In other words, we know something isn't working properly but we don't know where the problem originates. The term is a bit vague, because the range of "troubles" one could "shoot" is extensive, from user errors to automation failures. The idea here is that data in the logs will help us understand why the execution went the way it did.

#### Primary beneficiaries: developers, admins, and ultimately end users

### Profiling

In some cases there may not be a failure as such. Rather we might be seeing a performance degradation on, say, an LWC page, a Flow, or an Apex trigger. Another possibility is that we either might be getting dangerously close to—or even hitting—the governor limits. In these instances it would be valuable to know the breakdown of precious resource consumption by each step of the execution. These resources might be: number of SOQL queries, CPU utilization, or simply execution time.

#### Primary beneficiaries: developers, admins, end users

### Tracing

Getting into more advanced territory, we might find ourselves navigating complex multi-step transactions. For example, a screen flow that is performing a DML operation could start an Apex trigger, followed by an autolaunched flow. In these scenarios we'd like to see every step of execution recorded so we can determine if the order of operations is as we expect. Indeed, these complex bits of automation don't even need to span multiple technologies. There are plenty of use cases where everything happens in Apex but it's still complex enough that it poses a challenge.

#### Primary beneficiaries: developers, admins

### Auditing

Some organizations have strict compliance requirements around certain key areas that require auditing. For example, a financial institution might be interested in tracking every step of a complex financial exchange.

Even if your company is not bound by compliance requirements it's still great to know that what you *expect* to happen does, in fact, happen. For example, let's say a closed opportunity needs to kick off a provisioning flow in an external system, followed by order creation and some outbound communication. Having an audit trail for every step of that process is invaluable for ensuring data completeness and correctness. It also prevents disconnects between parts of the business processes that can lead to disasters.

#### Primary beneficiaries: business, operations, legal

### User Experience

This area is mainly concerned with user adoption. Want to know if your end users are getting to end-of-the-screen flows? How about locating time-consuming steps in a complicated custom LWC interface that are part of users' day to day? Want to know where in the application process your users are dropping off?

Analyzing log trails of users' interactions with your custom interfaces can provide all these answers and give you insights that are either unavailable otherwise or extremely hard to obtain through UX studies.

#### Primary beneficiaries: UX designers, admins, end users


# Installing Pharos Triton

Your journey into logging starts here! This article details how to set up the Pharos Triton tools so you can incorporate logging into your own code base.

## 1. Installing and Configuring Pharos <a href="#h_01hswdbmj3y683vqpc8npwc2f2" id="h_01hswdbmj3y683vqpc8npwc2f2"></a>

First, install the Pharos managed package, which includes the observability platform. There are several options:

* Signup for Pharos Free edition [from our website](https://pharos.ai/pricing/102).
* Sign up for a paid edition trial by visiting our [AppExchange listing here](https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3A00000FMhhvUAD).

Next, complete the basic configuration steps. Please refer to [the Pharos guide here](https://support.pharos.ai/hc/en-us/articles/22352477522715-Installing-and-Configuring-Pharos). The entire process shouldn't take more than 10 minutes of your time, depending on how quickly the package installs in your org.

{% hint style="info" %}
Pharos Free Edition is indeed **free.** Completely. Now and forever. No hidden fees. This is our contribution to the Salesforce community and we will stand by it.
{% endhint %}

## 2. Deploy Pharos Triton <a href="#id-01hswedx82r2bk16vnnmd9vnjv" id="id-01hswedx82r2bk16vnnmd9vnjv"></a>

There are 2 delivery methods. We recommend option A for its simplicity.

* **Option A:** Deploy via an unlocked managed package
  * [Sandbox install link](https://resources.pharos.ai/pharos-triton-sandbox)
  * [Production (non-sandbox) install link](https://resources.pharos.ai/pharos-triton-prod)\\
* **Option B:** Visit us at [this Github repo](https://resources.pharos.ai/pharos-triton-github). The code is available and free for all to use and modify as necessary. Feel free to utilize your favorite IDE or deployment tool to release the logger code in all environments as necessary. We recommend that the log util is deployed to production once it has been vetted through your development process. As your sandboxes are refreshed the log util will become available there as well.

{% hint style="info" %}
If you've evaluated Pharos in the past and installed the Error Generator package, you may notice there is a Log.cls file included. This is actually a condensed version of Pharos Triton with some slight modifications. We recommend you use the official Triton version, however.
{% endhint %}

## 3. Platform Event Setup <a href="#h_01hswdbmj3y683vqpc8npwc2f2" id="h_01hswdbmj3y683vqpc8npwc2f2"></a>

Pharos Triton is based on platform events. In other words, every time logs are flushed, a platform event gets fired off.

In this section we will configure Pharos to raise platform events, thus enabling the use of the log util.

Let's get started by navigating to Pharos Admin → Advanced → Triton. Follow the steps in this quick tutorial to complete the configuration, and you're done!

{% embed url="<https://app.arcade.software/share/rk1d50LwD0F3ccO5JAqf>" %}

Feel free to run a test at the end as well. You can come back to the results in the Logs tab in case the test takes a little while.

{% hint style="info" %}

### Why Platform Events? <a href="#h_01ht0gsafztervtjm33sb0emd7" id="h_01ht0gsafztervtjm33sb0emd7"></a>

Platform events are a great way to ensure reliable logging that will not get rolled back no matter what happens to the original transaction. Platform event operations also don't not count against DML limits, which is important in high volume processing situations. It is the de facto standard for logging on the Salesforce platform and is utilized by many other open source logging frameworks. For more information about platform events please refer to [Salesforce developer documentation](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_intro.htm).
{% endhint %}

## 4. Platform Cache Setup <a href="#platform-cache-setup" id="platform-cache-setup"></a>

Triton requires a platform cache partition to be configured. Even if you don't plan to use Triton's cache-based transaction management features, this setup is necessary for Triton's Apex tests to pass.

### Creating a Cache Partition

1. Navigate to **Setup → Platform Cache**
2. Click **New Platform Cache Partition**
3. Configure the partition with the following settings:
   * **Label**: `Default` (or your preferred name)
   * **Name**: `Default`
   * **Default Partition**: ✅ **Check this box** — This is critical! Triton requires a default partition to function properly with cache-based transaction management.

### Allocating Session Cache Memory

{% hint style="warning" %}
You must allocate memory to the **Session Cache Allocation** section for Triton's caching to work. Without session cache allocation, Triton will not be able to store transaction IDs.
{% endhint %}

4. In the **Session Cache Allocation** section, set the **Organization** value to at least `1` MB
5. Click **Save**

The image below shows the correct configuration with the Default Partition checkbox and Session Cache Allocation highlighted:

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2Fgit-blob-648394d12b0079697496c6e6e6b612e5742af531%2Fcache_partition.png?alt=media" alt="Platform Cache partition configuration showing Default Partition checkbox and Session Cache Allocation settings"><figcaption><p>Suggested cache partition configuration</p></figcaption></figure>

{% hint style="info" %}
For more detailed information on platform cache configuration, see [Set Up Platform Cache](https://help.salesforce.com/s/articleView?id=sf.data_platform_cache_setup.htm\&type=5) in the Salesforce documentation.

To learn how to use platform cache with Triton for LWC and Apex integration, see [Platform Cache for Transactions](https://triton.pharos.ai/1-42/beyond-apex/lwc-and-apex-cache).
{% endhint %}

## 5. Configure Permissions

Pharos Triton comes with three permission sets to help manage access:

### Triton End User

* **Purpose**: For users who will be running automation that uses Triton logging
* **Access**: Provides ability to execute processes that create logs
* **Includes**: Access to Triton Apex classes needed for automation execution
* **When to use**: Assign to:
  * Experience Cloud (Community) users
  * Users who run screen flows
  * End users executing automated processes

### Triton Read

* **Purpose**: For users who need to view and analyze logs
* **Access**: Read-only access to log records and metadata
* **Includes**:
  * Read access to Log Level custom metadata
  * Read access to all log fields (CPU time, heap size, SOQL queries, etc.)
* **When to use**: Assign to developers, support staff, and business analysts who need to monitor and troubleshoot using logs

### Triton Write

* **Purpose**: For Triton and Pharos administrators
* **Access**: Complete read/write access to all Triton and Pharos components
* **Includes**:
  * Full CRUD access to log records
  * Ability to modify Log Level metadata
  * Complete administrative control
* **When to use**: Assign to Triton administrators and Pharos platform administrators

{% hint style="info" %}
Best Practice: Start with the most restrictive permission set (Triton End User for those running automation, Triton Read for those monitoring logs) and escalate to Triton Write only for dedicated administrators.
{% endhint %}

## 6. Start Logging! <a href="#id-01hswedx82r2bk16vnnmd9vnjv" id="id-01hswedx82r2bk16vnnmd9vnjv"></a>

This is where the fun begins. We recommend you identify [which use cases](https://triton.pharos.ai/1-42#logging-use-cases) you'd like to tackle first such as troubleshooting, tracing or profiling, or anything else. Once you have an idea of what you'd like to start with, head on over to [Apex Logging Basics](https://triton.pharos.ai/1-42/apex-logging-basics) to get started.


# Apex Logging Basics

This articles explains the structure and some of the basic principles behind Pharos Triton.

Now that we've completed all the preliminary work, let's get going! We'll cover the basics of what's included in the logging tools and look at some examples.

## Instantiating a Logger

Pharos Triton utilizes a Singleton pattern for accessing its capabilities. This is a handy way of ensuring that the state is preserved throughout the entire transaction. It also cuts down on the verbosity of creating a new class from scratch by referencing a static instance instead. We think that you will like this approach. However, if you don't, you can remove the Singleton implementation and switch over to the standard usage pattern.

Below is an example of how logging methods can be invoked.

```apex
try {
....
} catch (Exception e) {
    Triton.instance.error(TritonTypes.Area.Opportunities, e);
}
```

{% hint style="info" %}
If you decide to remove the singleton usage, take care to observe the use cases around bulk logging.
{% endhint %}

## Default Logging Methods

Pharos Triton provides a variety of logging methods to give you plenty of options for how you pass data to your log records. All of these reside inside *Triton.cls.* Below are a few examples:

```apex
public void error(Area area, Exception e)
public void addError(Area area, Exception e)

public void debug(Type type, Area area, String summary, String details)
public void addDebug(Type type, Area area, String summary, String details)

public void event(Level level, Type type, Area area, String summary, String details)
public void addEvent(Type type, Area area, String summary, String details)

.....
```

Many methods are overloaded to accept varying sets of parameters. You can log as much as you want or as little as you want.

### Instantaneous vs Buffered

The logging methods are divided into two major categories: **instantaneous** and **buffered**.

The first category immediately persists the logs. In other words, the methods in this category will build the log record, buffer it, and publish the platform event.

The second category of methods simply stashes the logs into a buffer until the *flush()* method is called. All methods in this second category are prefixed with "*add".*

For example this method will instantly publish an error log event:

```apex
public void error(TritonTypes.Area area, Exception e)
```

This method will buffer an error log record without publishing:

```apex
public void addError(TritonTypes.Area area, Exception e)
```

You'll notice that most methods have a corresponding *add\** version. In fact, the instantaneous methods will utilize their *add* counterpart, followed by a *flush()*. Here's an example of an instantaneous error method:

```apex
public void error(TritonTypes.Area area, Exception e) {
    addError(area, e);
    flush();
}
```

### Saving a Log

In order to save a log there are three steps involved:

1. Build the log, using Pharos *builder.*
2. Append the log to the buffer.
3. *flush()* when ready.

The last step will publish the platform event. Using the default methods [mentioned above](#default-logging-methods) will take care of all these steps for you. It's good practice to follow this pattern for your own logging methods as well.

Let's examine more closely what happens inside one of the default methods. The following method will create an error log and add it to the log buffer:

```apex
public void addError(TritonTypes.Area area, Exception e) {
    add(                
         makeBuilder()
         .category(TritonTypes.Category.Apex)
         //use exception type, Backend if blank
         .type(String.isBlank(e.getTypeName()) ? TritonTypes.Type.Backend.name() : e.getTypeName())
         .area(area)
         .summary(e.getMessage())
         .stackTrace(e.getStackTraceString())
         .details(String.valueOf(e) + SPACE_SEP + e.getStackTraceString())
         .transactionId(TRANSACTION_ID)
         .relatedObjects(relatedObjectIds)
         .level(TritonTypes.Level.ERROR)
         .createIssue()
         .build());
}
```

Few things to note here:

* The use of the Category, Type and Area enums within the TritonTypes class. These indicate that this log is to be presented as an error with a specific type and functional area. This is covered in more detail in the [enums section](#important-enums).
* The use of the *makeBuilder()* method and the builder pattern for constructing logs. This is covered in [more detail here](#id-01hswfnenxm0yhrnat382sq96g).
* The use of the *.attribute()* method that allows setting of standard and custom fields on Log records. This is addressed further in [this section](#h_01hsz0123tet1q4avq0hjzy4wp).
* The use of the *add()* method to buffer the log.

You'll find all of the default logging methods adhering to the same pattern to various degrees. We encourage you to explore this approach and adapt it for your own needs.

[This article](https://triton.pharos.ai/1-42/methods-reference/apex-methods-reference) details the full list of logging methods.

### Bulk Logging

As you know, the name of the game on the Salesforce platform is "bulkification." Wherever possible, all operations are performed in bulk. There are multiple reasons for the platform to require bulk processing. When it comes to logging, though, there's one main reason: platform event (PE) allocations. In other words, there is a limit on how many platform events can be emitted. For more details on platform event limits, please refer to the [Salesforce documentation here.](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_event_limits.htm)

If your org is consuming a large number of PE allocations, the added logging will impact this limit as well. Therefore, it is more important to log in bulk by buffering as many logs as possible before calling the *flush()* method. In general, the same best practices apply here as for DML operations. There is a finer balance to strike here, however. If all logs are buffered, in the event of an error or exception the stashed logs may never get created. The code between logging statements will need to be carefully examined for exception possibilities. If there is a risk of an exception, it's best to *flush()* logs before moving on.

## Important Enums

There are three default enums that come with Pharos Triton. They can be found inside the *TritonTypes.cls*. The purpose of these is to provide a consistent list of values for three key fields: Category, Type and Functional Area.

Why Enums? Technically, any string value can be written into the three fields mentioned above. However, for clarity purposes, it's a good idea to keep these values explicit. When new values are introduced, they should be added to the enums accordingly. This will help you with code maintenance and readability.

{% hint style="info" %}
We highly encourage you to **add your own** enum values, especially for the Area enum. These values are meant to represent accurate functional areas in the context of *your* org. There is simply no one-size-fits-all here so feel free to expand your enums value sets.
{% endhint %}

### Category <a href="#h_01hsyh27q519ca5zkjbdp2javx" id="h_01hsyh27q519ca5zkjbdp2javx"></a>

This value represents a broad category of a log or issue. These values are predefined by Pharos and it's a good idea to stick to the value set that comes out of the box. The full list is as follows:

* Apex
* Integration
* LWC
* Aura
* Bulk API
* Flow
* Process Builder
* Debug
* Error
* Event
* Warning
* Email-to-Case
* Web-to-Lead

Many methods within Pharos Triton will automatically set a category for you.

The main reason to stick with these predefined values is to ensure that Log and Issue detail pages are rendered with the appropriate lightning page layout and debug views. While Pharos Triton allows for lots of flexibility when it comes to populating your custom logs with data, mislabeling a Category on a log record can result in a different view being displayed. For example, if you label an Apex log with a Flow category, the resulting log record will still contain all the appropriate data, but the detail page will not show the Apex stack trace.

The general guideline is to stick to the specific technology where logging is performed. If you are logging from Apex, set the category as Apex. If you are logging in Flows, leave the default Flow category and so on.

The following values are always set automatically as part of Pharos' automated error capture:

* Bulk API
* Flow
* Process Builder
* Email-to-Case
* Web-to-Lead

It's best to stick to these category values for your custom logging needs as well. This will ensure that the correct view is presented and the relevant fields are visible

* Apex
* Flow
* LWC
* Aura
* Integration
* Error
* Event
* Warning
* Debug

### Type <a href="#h_01ht0g8b2jq5s214ya8nw8x9za" id="h_01ht0g8b2jq5s214ya8nw8x9za"></a>

Type provides a more specific technical classification. This value will be written to the Type field. For your custom logs, utilize this value as you see fit. This value assumes more freedom when it comes to the possible values and doesn't influence the view of a log record. Types are set by default during Pharos' automated error capture. For example, the default behavior of Pharos apex logs is to set the *Type* to the corresponding Exception type, such as DmlException. For flows, Type is set according the particular kind of flow that is utilized (e.g, Screen Flow or Autolaunched Flow).\
The default values included in Triton are:

* Backend
* Frontend

### Area <a href="#h_01hsyh0nmy90sa21hdbktchavj" id="h_01hsyh0nmy90sa21hdbktchavj"></a>

Area represents *Functional Area* at the Log and Issue level. This goal of this value is to convey a business or data centric description of functionality. For example, let's say there's an Account trigger that you would like to add logging to. In this case it would be appropriate to introduce an Area of Accounts. Alternatively, if there's a more specific operation that is performed in the Account trigger, such as data enrichment or an integration that pushes new Accounts into an external system, you could consider utilizing a Functional Area such as *AccountEnrichment* or *AccountSync.*

### Level <a href="#h_01hsyh0nmy90sa21hdbktchavj" id="h_01hsyh0nmy90sa21hdbktchavj"></a>

This enum represents log levels. These are typically used by *\*event()* and *\*debug()* logging methods to indicate a custom log level. Use this enum to control the verbosity of your logging output. Values are listed from the least verbose to the most verbose. For example if org logging level is set to INFO, any logs created with ERROR, WARNING or INFO levels will get saved and all others will not.

* ERROR
* WARNING
* INFO
* DEBUG
* FINE
* FINER
* FINEST

## LogBuilder <a href="#id-01hswfnenxm0yhrnat382sq96g" id="id-01hswfnenxm0yhrnat382sq96g"></a>

Pharos Triton makes use of the Builder design pattern. There's lots of information out there about this approach. [Here is as an example.](https://refactoring.guru/design-patterns/builder)

In short, the builder paradigm allows for an easy-to-understand, self-documenting approach to passing data to your log files. Here is an example of what Pharos Triton does to create a log record:

```apex
makeBuilder()
    .category(TritonTypes.Category.Debug)
    .type(type)
    .area(area)
    .summary(summary)
    .details(details)
.build());
```

Invoking the build function at the end returns a *pharos\_\_Log\_\_c* object with all the relevant fields populated. At this point the log is ready to either be buffered for later or persisted right away via the platform event.

One thing to note is the usage of the *makeBuilder()* method. This is simply a shorthand way of creating an instance of the Pharos builder class. It serves no other purpose than to cut down on the verbosity of creating a builder directly by referencing the *pharos* namespace.

```apex
public static TritonBuilder makeBuilder()
```

Please refer to [this section](https://triton.pharos.ai/1-42/methods-reference/apex-methods-reference/tritonbuilder) for the full API reference.

### Passing Custom Attributes to Logs <a href="#h_01hsz0123tet1q4avq0hjzy4wp" id="h_01hsz0123tet1q4avq0hjzy4wp"></a>

In the event you have a need to track additional custom attributes on the Log record, the *builder* offers a simple way of passing these values. In the example below, consider a custom field *My\_Custom\_Attribute\_\_c* on the Log record.

```apex
makeBuilder()
    .attribute('My_Custom_Attribute__c', customValue)
```

If you've already examined *TritonBuilder.cls* you might have noticed several static final constants declared at the very top, such as:

<pre class="language-apex"><code class="lang-apex"><strong>public static final String APEX_NAME = 'pharos__Apex_Name__c';
</strong>public static final String CREATED_TIMESTAMP = 'pharos__Created_Timestamp__c';
public static final String DURATION = 'pharos__Duration__c';
public static final String INTERVIEW_GUID = 'pharos__Interview_GUID_External__c';
......
</code></pre>

These are used by various default logging methods to set custom log attributes. It's a good idea to follow this practice for your own custom attributes as well.

First declare a static final constant, and then reference it:

```apex
public static final String MY_CUSTOM_ATTRIBUTE = 'My_Custom_Attribute__c';
....
makeBuilder()
    .attribute(MY_CUSTOM_ATTRIBUTE, customValue)
....
```

It's a good practice to keep things organized and keep a list of Log field dependencies all in one place.

#### Creating Custom Methods in TritonBuilder

While using `.attribute()` is functional, a better approach is to add custom methods directly to the `TritonBuilder` class. This provides a cleaner, more readable API and ensures type safety for your custom attributes.

For example, instead of using:

```apex
makeBuilder()
    .attribute(MY_CUSTOM_ATTRIBUTE, customValue)
```

You can add a custom method to `TritonBuilder`:

```apex
/**
 * Set custom attribute for tracking specific business logic
 * @param value -- String value for the custom attribute
 * @return this builder instance
 */
public TritonBuilder myCustomAttribute(String value) {
    this.builder.attribute(MY_CUSTOM_ATTRIBUTE, value);
    return this;
}
```

Then use it in your logging code:

```apex
makeBuilder()
    .category(TritonTypes.Category.Apex)
    .type(TritonTypes.Type.Backend)
    .area(TritonTypes.Area.Accounts)
    .myCustomAttribute('Custom Value')
    .summary('Operation completed')
    .build()
```

This approach offers several benefits:

* **Type Safety**: You can enforce the correct data type for the attribute
* **Documentation**: JSDoc comments provide clear documentation for the method's purpose
* **Readability**: The method name clearly indicates what attribute is being set
* **IDE Support**: Better autocomplete and IntelliSense support
* **Consistency**: Follows the same fluent interface pattern as other builder methods

When adding custom methods to `TritonBuilder`, follow the established patterns:

* Return `this` to maintain the fluent interface
* Use descriptive method names that clearly indicate the attribute being set
* Include JSDoc documentation explaining the parameter and return value
* Consider adding overloaded methods for different parameter types if needed


# Common Apex Usage Patters

This articles details of some of the more common logging patterns.

## Basic Apex Logging

Now that you're familiar with the [basic philosophy of Pharos Triton](https://triton.pharos.ai/1-42/apex-logging-basics), let's take a look at an example of apex logging. There are a number of ways to do logging ranging, from straightforward to very complex. We'll start with the basics and gradually move on to more advanced patterns and use cases.

In this scenario we'll take a look at a simple code snippet that performs a DML statement. The DML statement is wrapped into a try/catch block, where any potential exceptions can be handled. This scenario can take place anywhere: triggers, LWC Apex controllers, or even custom rest methods.

{% code lineNumbers="true" fullWidth="false" %}

```apex
public void basicApexLogging() {
        Triton.instance.startTransaction();
	Triton.instance.debug(TritonTypes.Type.Backend,//type
			TritonTypes.Area.Accounts,//functional area
			'Apex logging example Pre-dml',//summary
			'Pre dml update. Processing account records'); //details 
	try {
		List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
		if (!accounts.isEmpty()) {
			Triton.instance.debug(TritonTypes.Type.Backend, 
					TritonTypes.Area.Accounts,   
					'Account records found!',
					'Pre dml update. Processing account records');		
			accounts[0].Name = 'Logging rules!';
			update accounts;
		}
	} catch (Exception e) {
		//uh-oh... we have an Exception on our hands. Let's log that!
		Triton.instance.error(TritonTypes.Area.Accounts, e);
	} finally {
		Triton.instance.stopTransaction();
	}
}

```

{% endcode %}

Let's take a closer look at this snippet. There are a few take aways in the code above:

* The use of *start/stopTransaction().* This initiates a new transaction context within Pharos and ensures that all subsequent logs are grouped under a single umbrella—more specifically, under the first log generated in the sequence. See the log structure [detailed below](#parent-and-child-logs).

{% hint style="info" %}
If you have more logging to perform that you wish to group under the same umbrella, you can pass around the transaction Id (obtained from the *Triton.instance.TRANSACTION\_ID* property). This would allow you to span across Salesforce transactions to trace a complex process.
{% endhint %}

* Note the use of Type and Area values. You can check out the [general guidelines here](https://triton.pharos.ai/1-42/apex-logging-basics#enums).
* The use of *debug()* and *error()* methods. These simply provide a shorthand for creating log records with different categories, and different log levels. Note that different parameters are provided to *debug()* and *error()* methods.
* The use of a *finally{}* construct. This ensures that *stopTransaction()* is the last method that executes in any event.

{% hint style="info" %}
If you exceed a **governor limit** somewhere in your transaction, there's no guarantee that the finally{} block will execute, and with it the *stopTransaction().*

If *stopTransaction()* is not called, Pharos Triton simply stops logging under the parent log. In the example above, that poses no problem as there is no further logging after the *flush()*.
{% endhint %}

### Parent and Child Logs

Let's now assume that there is an exception raised during the DML operation. This will result in the following log records created:

* **A parent debug log generated on line (3)**
  1. A child debug log generated on line (10)
  2. A child Apex error log generated on line (19)
     * **An issue record** will also automatically get created for this log. Issues, by default, are only created for error logs. Debug and other log categories such as Event or Warning do not generate issues by default. This behavior is customizable in the [logging methods detailed here.](https://triton.pharos.ai/1-42/methods-reference/apex-methods-reference)

{% hint style="info" %}
If no *startTransaction()* call is made Pharos Triton will simply create the logs without associating them together under a common parent. This would result in the log structure below.

* A parent debug log generated on line (3)
* A parent debug log generated on line (10)
* A parent Apex error log generated on line (19)
  * An issue record will also automatically get created for this log. Similar to the example above. Issue creation behavior is not impacted by transactional logging.
    {% endhint %}


# Batch Logging

This article demonstrates some common approaches to batch logging.

Batch jobs are great for processing large amounts of data in the background. They can be scheduled, executed by hand on demand, or via some sort of trigger. The common pain point with these is that there's little visibility when it comes to failures. Hence, many developers turn to logging. There are a number of use cases to cover here: basic error handling, trace logging, and profiling.

## Basic Error Handling

Proper error handling is essential to weed out those pesky errors in batch jobs. Often Salesforce will mask failures or provide a one-liner error message with no stack trace. This is where we can make a huge difference by taking matters into our own hands. Below is a code snippet that incorporates error logging in the most troublesome *execute()* method.

<pre class="language-apex" data-title="Basic Batch Logging" data-line-numbers><code class="lang-apex"><strong>public class LeadsBatch implements Database.Batchable&#x3C;sObject>, Database.Stateful {
</strong>    private String query ='';
    private Triton logger = Triton.instance;
    
    public LeadsBatch(String leadQuery) {
        this.query = leadQuery;
    }
    
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext bc, List&#x3C;Lead> leads) {
        for(Lead l : leads){
            try {
                LeadProcessingResult result = LeadService.getQualificationScore(l);
                if(result.isSuccess) {
                    l.Score__c = result.qualificationScore;
                }
            } catch(Exception e){
                this.logger.addError(TritonTypes.Area.LeadQualification, e);
            }
        }
        
        try {
            update leads;
        } catch(Exception e){
            this.logger.addError(TritonTypes.Area.LeadQualification, e);
        }
    }

    public void finish(Database.BatchableContext bc){
        this.logger.flush();
    }
}
</code></pre>

There is a good chance you might find similar batch jobs in your own org. The pattern is quite typical: query records, process them in a loop, then perform a DML, a callout or some other action. Let's now dive into the details of what's happening here.

* Note the use of the ***Database.Stateful*** interface in the declaration of our *LeadsBatch* clas&#x73;*.* In this example we have made our batch **stateful**, or, in other words, retain its state between the different iterations of the *execute()* method. For more information on this please refer to [Salesforce developer documentation here.](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm) The reason we need state preservation is to be able to accumulate our logs in a buffer within the logger class variable declared on line (3). Static context in our Singleton logger instance will not be preserved between different batch iterations.
* In this batch class we're utilizing another concept called **bulk logging** [introduced in this section](https://triton.pharos.ai/1-42/apex-logging-basics#bulk-logging). You'll notice the use of the *addError()* method instead of the *error()* method as in the [previous example](#basic-apex-logging). The *addError()* method appends to the log buffer that is subsequently flushed in the *finish()* method on line (33).

{% hint style="info" %}
The main motivation behind buffering logs is to **preserve platform event (PE) allocations** by emitting a single platform event containing a collection of logs. Since we're dealing with a batch, it may take hundreds of iterations to complete. Assuming we log something on every iteration, quite a few PE allocations may be consumed.
{% endhint %}

* The use of the *finish()* method on line (33). This method runs when a batch is finished executing, regardless of whether those executions resulted in exceptions. This is good news for us as it ensures that our log buffer is persisted properly.
* Note the use of the *Area* enum on line (21) and (28) in the *catch()* clause. The more accurate you can be with this value, the better your searching and reporting experience will be.

{% hint style="info" %}
It is possible to log within **all** **methods** of the batch class, not just the *execute().* In fact, it is highly recommended you do so when you have logic in those methods. In our example above there is really not much going there, hence no logging needed.
{% endhint %}

## Grouping Logs From Multiple Iterations

Let's now incorporate the idea of uniting logs under a single transaction [illustrated in the very first example](https://triton.pharos.ai/1-42/common-apex-usage-patters#basic-apex-logging) with the concept of bulk logging. We'd like to see all logs for each of the iteration grouped under the same parent, and we are also going to do in a way that is consistent with the platform best practices by emitting only a single platform event. The example below also adds a few *debug()* and *event()* statements to the mix for a more detailed trace of batch execution:

{% code title="Batch + Transaction" lineNumbers="true" %}

```apex
public class LeadsBatch implements Database.Batchable<sObject>, Database.Stateful {
    private String query ='';
    private Log logger = Triton.instance;
    //will need to keep track of the number of iterations
    private Integer iteration = 0;
    
    public LeadsBatch(String leadQuery) {
        this.query = leadQuery;
        logger.startTransaction();
        logger.addDebug(TritonTypes.Type.LeadsBatch, 
                        TritonTypes.Area.LeadQualification,
                        'LeadsBatch initialized',
                        'LeadsBatch initialized with query: ' + query );
    }
    
    public Database.QueryLocator start(Database.BatchableContext bc) {
        logger.addEvent(TritonTypes.Level.FINE,
                    TritonTypes.Type.LeadsBatch, 
                    TritonTypes.Area.LeadQualification,
                    'LeadsBatch starting',
                    'Fetching query locator for query: ' + query );
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext bc, List<Lead> leads) {
        iteration++;
        logger.addEvent(TritonTypes.Level.FINE,
                    TritonTypes.Type.LeadsBatch, 
                    TritonTypes.Area.LeadQualification,
                    'LeadsBatch executing iteration: '+ iteration,
                    'Processing ' + leads.size()) + ' in this iteration';
        for(Lead l : leads) {
            try {
                LeadProcessingResult result = LeadService.getQualificationScore(l);
                if(result.isSuccess) {
                    l.Score__c = result.qualificationScore;
                } else {
                    logger.addEvent(TritonTypes.Level.FINE,
                                    TritonTypes.Type.LeadsBatch, 
                                    TritonTypes.Area.LeadQualification,
                                    'LeadsBatch failed to obtain successful qualification score',
                                    'Result returned for lead id ' + l.Id + 
                                        Triton.SPACE_SEP + 'Result: ' + 
                                        Triton.SPACE_SEP + String.valueOf(result);
                }
            } catch(Exception e){
                logger.addError(TritonTypes.Area.LeadQualification, e);
            }
        }
        
        try {
            update leads;
        } catch(Exception e){
            logger.addError(TritonTypes.Area.LeadQualification, e);
        }
    }

    public void finish(Database.BatchableContext bc){
        logger.addDebug(TritonTypes.Type.LeadsBatch, 
                        TritonTypes.Area.LeadQualification,
                        'LeadsBatch finishing',
                        'Iterations processed: ' + iteration);
        logger.flush();
        logger.stopTransaction();
    }
}
```

{% endcode %}

For the most part this example is similar in spirit to the basic batch logging snippet. A few things to highlight here nonetheless:

* Note the more generous logging statements that are incorporated into every method of this batch class. This will provide more details when analyzing the execution and help examine some key data points such as iteration number and the query that was used to construct a query locator.
* In this example we're making use of the different log levels (see [Level enum](https://triton.pharos.ai/1-42/apex-logging-basics#h_01hsyh0nmy90sa21hdbktchavj-1)). The constructor and the *finish()* methods are utilizing the DEBUG level, whereas the *start()* and *execute()* methods are logging at INFO level.

{% hint style="info" %}
The general rule of thumb with log levels is to log anything that is essential for troubleshooting at DEBUG, WARNING or INFO levels. Everything else that may be helpful should remain at the FINE level or below.

Errors are typically always logged at the highest level of ERROR.
{% endhint %}

* Last but not least is that all these logs that we're generating here will be grouped under a single parent log. This is quite convenient for future troubleshooting needs as there is now an nice easy to navigate structure available.


# Integration Logs

If your Salesforce instance is talking to external services via REST or other types of APIs, Pharos Triton can perform a certain type of logging that helps troubleshoot those integrations.

In this article, we'll look at creating logs with supporting request/response payload information. A typical scenario involves performing an Apex callout. Oftentimes we expect an HTTP 200 response if all goes well. However, the most troublesome scenario is when things *don't* go well. You may receive a non 200 response from your external service and, at that point, the only way to get to the bottom of the problem is to examine the request/response payload.

## Integration Log View

Triton offers a convenient interface for visualizing payloads directly from a log record. Below is an example of such a log record:

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2Fuq5qzPnq3qZC1fn0vl7o%2FScreenshot_2024-06-13_at_10_47_57_AM.png?alt=media&amp;token=a1f0fee7-bc7b-4639-b1ff-c6ec84b181ce" alt=""><figcaption><p>Pharos Triton Integration Log View</p></figcaption></figure>

If you've used Postman before, this view may look familiar. From this interface you have the ability to view the request endpoint, parameters, headers, and body. In a similar fashion, you can examine the response that is returned. There is also a replay capability that allows you to re-send the request (with optional modifications) to your external endpoint. The request will be sent from your org and not just your browser. This is a very powerful way to troubleshoot integrations. Moreover, there is an easy way to create these types of logs view the Pharos Triton Apex interface. Let's take a look at an example.

## Common Callout Example

Regardless of where your integration is kicked off, you'll likely have some Apex code that sets up an HttpRequest and performs a callout to your external service. In the example below, we're going to collect some data from a custom object and use that to create the JSON body of the request and send it off to our external service.

{% code title="Basic HTTP Post " %}

```apex
public static void pushLoanApplication(Id loanApplicationId) {
    //collect the data for our http request
    Loan_Application__c la = [select Id, 
                                    Account__r.Name, 
                                    Primary_Contact__r.FirstName, 
                                    Primary_Contact__r.LastName, 
                                    Primary_Contact__r.Email, 
                                    Primary_Contact__r.Social__c 
                                    from Loan_Application__c 
                                    where Id=:loanApplicationId limit 1]; 

    //put together a map so we can serialize it into JSON
    Map<String, String> requestMap = new Map<String, String>();
    requestMap.put('firstName', la.Primary_Contact__r.FirstName);
    requestMap.put('lastName', la.Primary_Contact__r.LastName);
    requestMap.put('email', la.Primary_Contact__r.Email);        
    requestMap.put('ssn', la.Primary_Contact__r.Social__c);                

    //setup an HttpRequest with all the necessary attributes
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
    request.setMethod('POST');
    request.setHeader('Content-Type', 'application/json;charset=UTF-8');
    request.setBody(JSON.serializePretty(requestMap));      
    
    //perform the POST operation
    HttpResponse response = http.send(request);
}
```

{% endcode %}

Your use case may not be this exact operation, but in all likelihood, the idea is similar: gather data, create a request payload and perform the callout.

One glaring issue with the code snippet above is that it doesn't account for the possibility of failure. If the HttpResponse response returns a 500 status or some other non-200 failure, we will never know. At that point it's next to impossible to connect the dots, especially if the failure is discovered well after the request was performed. To remedy this situation, let's add some logging to help us out.

## Creating an Integration Log

{% code lineNumbers="true" %}

```apex
public static void pushLoanApplication(Id loanApplicationId) {
    //collect the data for our http request
    Loan_Application__c la = [select Id, 
                                    Account__r.Name, 
                                    Primary_Contact__r.FirstName, 
                                    Primary_Contact__r.LastName, 
                                    Primary_Contact__r.Email, 
                                    Primary_Contact__r.Social__c 
                                    from Loan_Application__c 
                                    where Id=:loanApplicationId limit 1]; 

    //put together a map so we can serialize it to JSON
    Map<String, String> requestMap = new Map<String, String>();
    requestMap.put('firstName', la.Primary_Contact__r.FirstName);
    requestMap.put('lastName', la.Primary_Contact__r.LastName);
    requestMap.put('email', la.Primary_Contact__r.Email);        
    requestMap.put('ssn', la.Primary_Contact__r.Social__c);                

    //setup an HttpRequest with all the necessary attributes
    try {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody(JSON.serializePretty(requestMap));      
    
        //perform the POST operation
        HttpResponse response = http.send(request);
        if (response.getStatusCode() != 200) {
            //we didn't get a successful response, so let's log this
            Triton.instance.integrationError(TritonTpes.Type.PushIntegration, /* type */
                                    TritonTpes.Area.LoadApplications, /* area */
                                    'Unable to push an application to the loan service', /* summary */
                                    String.format('Received a {0} status code from the loan service when pushing an application id {1}',
                                        new String[] {String.valueOf(response.getStatusCode()), la.Id]    /* formatted details */ 
                                    request, /* HttpRequest */
                                    response /* HttpResponse */
            ); 
        }
       
    } catch (Exception e) {
        //something else went wrong, let's log this as well
        Triton.instance.error(e);
    }
}
```

{% endcode %}

Executing this code snippet should result in a log similar to the following:

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FN6Rq2Jbl9GrDS2YT6d24%2FScreenshot%202024-06-13%20at%204.08.19%20PM.png?alt=media&amp;token=dbd86d5f-c237-44f7-9b3b-5056a005af4d" alt=""><figcaption><p>Resulting Integration Log</p></figcaption></figure>

Because we also specified a record Id in the details of the log we should also see a related object linked to the log record:

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2F497139jyoobUzBp8JX3A%2FScreenshot%202024-06-13%20at%204.08.31%20PM.png?alt=media&amp;token=e40b291f-bc0d-49a8-8cc4-49c801bc8733" alt=""><figcaption><p>Related Object Automatically Associated</p></figcaption></figure>


# Apex Rest Logging

In the previous article we've taken a look at an outbound scenario where a callout is made from Salesforce to another external system. Now, imagine a reverse use case where Salesforce is receiving a request from an external system via a custom REST endpoint.

A custom REST endpoint is facilitated via an annotated Apex class similar to the one in the snippet below.

For this example, let's assume we're handing a POST request. Regardless of the method the solution below still applies. Our goal is to log the initial request and pass on the generated transaction Id to any other processing that may happen. In addition, if there is an exception during a DML operation or anything else, we'd like to associate this error to the parent REST log.

{% code lineNumbers="true" %}

```apex
@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {

  @HttpPost
    global static String doPost(String name, String phone, String website) {
        String transactionId = Triton.instance.startTransaction();
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        Log.instance.integrationLog(TritonTypes.Type.AccountIntegration, /* type */
                                      TritonTypes.Area.Accounts, /* functional area */
                                      'Initiating new account creation', /* summary */
                                      String.format('POST received with name = {0}, phone = {1}, website = {2}',
                                           new String[]{name, phone, website}), /* formatted details */
                                      req, /* request */
                                      res); /* response */
        try {
            Account account = new Account();
            account.Name = name;
            account.phone = phone;
            account.website = website;

            //(optional) perform some other processing asynchronously, 
            //passing an existing transaction Id 
            AccountProcessing.doAsyncProcessing(account, transactionId);
            
            insert account;
            return account.Id;
        } catch(Exception e) {
            //uh oh, something went wrong, let's log this!
            Triton.instance.error(e);
        }
        return null;
    }
}

```

{% endcode %}

## The Result

Let's assume that we do run into a DML Exception on line 26 and we will also have some logging performed inside *doAsyncProcessing()* on line 24. Given all of the above, the snipped may generate the following log structure:

* Parent Apex Integration Log from line 9
  * Child Apex Error Log from our try/catch block on line 28
  * Any child logs inside the *AccountProcessing.doAsyncProcessing()* routine on line 24.

{% hint style="info" %}
The order of child logs created may vary, depending on how quickly Salesforce schedules AccountProcessing for execution. This depends on what type of processing takes place, Batch or Queueable, and whether or not this execution starts immediately.
{% endhint %}


# Full Control with TritonBuilder

With TritonBuilder, logging is no longer a tedious task but an art form. Embrace the power of structured logging and let TritonBuilder be your guide. Happy logging!

## TritonBuilder: Your Logging Sidekick

Welcome to the world of TritonBuilder, the unsung hero of the Pharos Triton logging framework. Imagine a world where logging is not just a chore but a delightful experience. TritonBuilder is here to make that dream a reality, providing a fluent interface that transforms the mundane task of log creation into a seamless and enjoyable process.

### Builder Perks: Why You'll Love It

#### Fluent Interface: The Art of Chaining

TritonBuilder is like a well-trained butler, allowing you to chain method calls effortlessly. Set your log attributes with the grace of a ballroom dancer, avoiding the confusion of tangled code. It's like having a conversation with your code—clear, concise, and to the point.

#### Customizable Attributes: Your Log, Your Way

Whether you're setting categories, types, areas, or levels, TritonBuilder has you covered. It's like a customizable pizza—choose your toppings (or attributes) and create the perfect log for your needs.

#### Integration with HTTP and REST: The Diplomat

TritonBuilder handles payloads from HTTP and REST requests/responses with the finesse of a seasoned diplomat. It ensures your integration logs are as smooth as a well-brewed cup of coffee.

#### Support for Related Objects: The Matchmaker

Need to associate logs with related Salesforce objects? TritonBuilder is your matchmaker, making connections that matter.

#### Template Support: The Reusable Genius

Create reusable log templates for consistent logging. It's like having a wardrobe of perfectly tailored suits—always ready for any occasion.

### Basic Usage

#### Creating a Simple Log

To create a basic log entry, instantiate a `TritonBuilder` and set the desired attributes:

```apex
TritonBuilder builder = new TritonBuilder();
builder.category(TritonTypes.Category.Apex)
       .type(TritonTypes.Type.Backend)
       .area(TritonTypes.Area.Community)
       .level(TritonTypes.Level.INFO)
       .summary('Sample Log Entry')
       .details('This is a detailed description of the log entry.')
       .build();
```

#### Setting Attributes

The `TritonBuilder` class provides methods to set various attributes:

* **Category**: Represents the high-level classification of the log.

  ```apex
  builder.category(TritonTypes.Category.Apex);
  ```
* **Type**: Provides a more specific classification.

  ```apex
  builder.type(TritonTypes.Type.Backend);
  ```
* **Area**: Represents the functional area from a business perspective.

  ```apex
  builder.area(TritonTypes.Area.Community);
  ```
* **Level**: Defines the severity of the log.

  ```apex
  builder.level(TritonTypes.Level.INFO);
  ```
* **Summary and Details**: Provide a brief and detailed description of the log.

  ```apex
  builder.summary('Log Summary').details('Detailed log information');
  ```

### Advanced Usage

#### Handling HTTP and REST Payloads

`TritonBuilder` can serialize HTTP and REST request/response objects for integration logs. It's like having a translator for your logs, ensuring nothing gets lost in translation.

```apex
HttpRequest request = new HttpRequest();
HttpResponse response = new HttpResponse();
builder.integrationPayload(request, response);
```

#### Associating Related Objects

Logs can be associated with related Salesforce objects using their IDs. TritonBuilder is the bridge that connects your logs to the bigger picture that is your data. You can associate one or many ids (or strings that represent Ids).

```apex
Id relatedObjectId = Id.valueOf('001xx000003DGb2AAG');
builder.relatedObject(relatedObjectId);
```

## Builder Templates

The `setTemplate` and `fromTemplate` methods in `Triton.cls` allow developers to create reusable log templates. This is particularly useful for scenarios where the same logging structure is used repeatedly, ensuring consistency and reducing code duplication. For example, say you're logging in a large class and want to re-use log category, type and functional area for every log you create. This is a perfect time to use a template.

### Using Templates for Repeated Logging

For scenarios where the same logging structure is used repeatedly, `TritonBuilder` supports the creation of templates. It's like having a template for your favorite email—consistent and reliable.

```apex
Triton.instance.setTemplate(Triton.makeBuilder()
                               .category(TritonTypes.Category.Apex)
                               .type(TritonTypes.Type.Backend)
                               .area(TritonTypes.Area.Community)
                               .level(TritonTypes.Level.INFO));

// Use the template for logging
Triton.instance.log(Triton.instance.fromTemplate()
                                 .summary('Template Log')
                                 .details('Details from template log'));
```

### Turn Builder into a Log with the Triton Class

#### `log()` Method

The `log()` method in `Triton.cls` is designed for immediate logging. It adds a log entry and flushes it to the database right away. It's the quick-draw cowboy of logging, ensuring your log is persisted immediately in critical scenarios.

**Usage Example:**

```apex
Triton.instance.log(Triton.makeBuilder()
                    .category(TritonTypes.Category.Apex)
                    .type(TritonTypes.Type.Backend)
                    .area(TritonTypes.Area.Community)
                    .summary('Immediate Log Entry')
                    .details('This log entry is flushed immediately.'));
```

#### `addLog()` Method

The `addLog()` method is used for buffered logging. It adds a log entry to the collection but does not immediately flush it to the database. It's the strategist, allowing you to batch multiple log entries and flush them together, optimizing performance.

**Usage Example:**

```apex
Triton.instance.addLog(Triton.makeBuilder()
                    .category(TritonTypes.Category.Apex)
                    .type(TritonTypes.Type.Backend)
                    .area(TritonTypes.Area.Community)
                    .summary('Buffered Log Entry')
                    .details('This log entry is buffered and not immediately flushed.'));
```

***

### Templates IRL Example

Let's revisit our`LeadsBatch`class from the [previous example](https://triton.pharos.ai/1-42/common-apex-usage-patters/batch-logging#grouping-logs-from-multiple-iterations) and update it to utilize the `setTemplate`and`fromTemplate`methods from the`Triton`class. We'll create a log template with common parameters and reuse it throughout our batch process.

Updated `LeadsBatch` Class:

```apex
public class LeadsBatch implements Database.Batchable<sObject>, Database.Stateful {
    private String query = '';
    private Log logger = Triton.instance;
    private Integer iteration = 0;
    
    public LeadsBatch(String leadQuery) {
        this.query = leadQuery;
        logger.setTemplate(Triton.makeBuilder()
                            .type(TritonTypes.Type.LeadsBatch)
                            .area(TritonTypes.Area.LeadQualification));

        logger.addLog(logger.fromTemplate()
            .summary('LeadsBatch initialized')
            .details('LeadsBatch initialized with query: ' + query));
    }
    
    public Database.QueryLocator start(Database.BatchableContext bc) {
        logger.addLog(logger.fromTemplate()
            .summary('LeadsBatch starting')
            .details('Fetching query locator for query: ' + query));
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext bc, List<Lead> leads) {
        iteration++;
        logger.addLog(logger.fromTemplate()
            .summary('LeadsBatch executing iteration: ' + iteration)
            .details('Processing ' + leads.size() + ' in this iteration'));
        
        for (Lead l : leads) {
            try {
                LeadProcessingResult result = LeadService.getQualificationScore(l);
                if (result.isSuccess) {
                    l.Score__c = result.qualificationScore;
                } else {
                    logger.addLog(logger.fromTemplate()
                        .summary('LeadsBatch failed to obtain successful qualification score')
                        .details('Result returned for lead id ' + l.Id + Triton.SPACE_SEP + 'Result: ' + String.valueOf(result)));
                }
            } catch (Exception e) {
                logger.addError(TritonTypes.Area.LeadQualification, e);
            }
        }
        
        try {
            update leads;
        } catch (Exception e) {
            logger.addError(TritonTypes.Area.LeadQualification, e);
        }
    }

    public void finish(Database.BatchableContext bc) {
        logger.addLog(logger.fromTemplate()
            .summary('LeadsBatch finishing')
            .details('Iterations processed: ' + iteration));
        logger.flush();
        logger.stopTransaction();
    }
}
```

**Benefits of Using Log Templates**

1. **Consistency**: By defining a template, you ensure that all log entries share a consistent structure, making it easier to analyze logs and identify patterns.
2. **Efficiency**: Templates reduce the amount of code needed to create log entries. You only need to specify the unique details for each log, while the common parameters are automatically applied from the template.
3. **Maintainability**: Changes to common log parameters can be made in one place (the template), rather than updating each log entry individually.
4. **Readability**: Code becomes cleaner and more readable, as the repetitive parts of log creation are abstracted away.

**Summary**

1. **To Create a Log Template**: Use the `Triton.makeBuilder()` method to create a log builder with common parameters. Set this builder as a template using `logger.setTemplate()`.

   ```apex
   TritonBuilder logTemplate = Triton.makeBuilder()
       .type(TritonTypes.Type.LeadsBatch)
       .area(TritonTypes.Area.LeadQualification);
   logger.setTemplate(logTemplate);
   ```
2. **Use the Template for Logging**: When creating a log entry, use `logger.fromTemplate()` to start with the template and then add specific details for that log entry.

   ```apex
   logger.addLog(logger.fromTemplate()
       .summary('LeadsBatch initialized')
       .details('LeadsBatch initialized with query: ' + query));
   ```

By adopting this approach, you can enhance the robustness and clarity of your logging strategy, making it easier to manage and analyze logs from your entire code base.

***


# Log Levels

This article explains how log levels work in Triton and how to configure them using custom metadata.

Log levels provide a powerful mechanism to control the verbosity of logging output across your Salesforce org. Triton implements a hierarchical log level system that allows you to filter logs based on their severity, ensuring that only relevant information is captured and stored.

## Understanding Log Levels

Log levels in Triton follow a standard hierarchy from least verbose to most verbose:

* **ERROR** - Critical errors that require immediate attention
* **WARNING** - Issues that may need attention but aren't critical
* **INFO** - General information about application flow
* **DEBUG** - Detailed debugging information
* **FINE** - Fine-grained debugging information
* **FINER** - Very detailed debugging information
* **FINEST** - Most detailed debugging information

The fundamental principle is that if you set a log level, only logs with that level or higher (more critical) will be persisted. For example, if you set the log level to INFO, only ERROR, WARNING, and INFO logs will be saved, while DEBUG, FINE, FINER, and FINEST logs will be filtered out.

## Custom Metadata Configuration

Triton uses the `Log_Level__mdt` custom metadata type to control log levels. This metadata type contains four fields:

* **Category** - The log category (e.g., Apex, Flow, LWC, Integration)
* **Type** - The log type (e.g., Backend, Frontend, DMLResult)
* **Area** - The functional area (e.g., Accounts, Opportunities, LeadConversion)
* **Level** - The minimum log level to capture (ERROR, WARNING, INFO, DEBUG, FINE, FINER, FINEST)

### Org-Wide Log Level

To set a default log level for your entire org, create a metadata record with all three classification fields (Category, Type, Area) left blank. This serves as a catch-all configuration that applies when no more specific rules match.

**Example:**

```
Category: (blank)
Type: (blank)
Area: (blank)
Level: INFO
```

This configuration would ensure that only ERROR, WARNING, and INFO logs are captured across all categories, types, and areas unless overridden by more specific rules.

### Refined Log Level Control

You can create more specific log level rules by populating one or more of the classification fields. The system uses a hierarchical matching approach:

1. **Exact Match** - Category, Type, and Area all match
2. **Partial Matches** - Various combinations of Category, Type, and Area
3. **Fallback** - Org-wide default (all fields blank)

**Example Configurations:**

```
# All Apex logs at DEBUG level
Category: Apex
Type: (blank)
Area: (blank)
Level: DEBUG

# All Flow logs at INFO level
Category: Flow
Type: (blank)
Area: (blank)
Level: INFO

# Account-related Apex logs at FINE level
Category: Apex
Type: (blank)
Area: Accounts
Level: FINE

# Integration errors always captured
Category: Integration
Type: (blank)
Area: (blank)
Level: ERROR
```

## Implementation in TritonBuilder

The `TritonBuilder` class provides the `level()` method to set log levels on individual log entries:

```apex
public TritonBuilder level(TritonTypes.Level l)
```

This method accepts a `TritonTypes.Level` enum value and sets it on the log record. The system then compares this level against the configured metadata rules to determine whether the log should be persisted.

**Example Usage:**

```apex
Triton.instance.addLog(
    Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .type(TritonTypes.Type.Backend)
        .area(TritonTypes.Area.Accounts)
        .summary('Account processing started')
        .details('Processing account: 001xx000003DGb2AAG')
        .level(TritonTypes.Level.DEBUG)
);
```

## Log Level Filtering Logic

When a log is created, Triton performs the following steps to determine if it should be persisted:

1. **Build Matching Keys** - Creates various combinations of Category, Type, and Area
2. **Check Metadata Rules** - Looks for matching rules in the `Log_Level__mdt` metadata
3. **Compare Levels** - Compares the log's level against the configured minimum level
4. **Filter Decision** - Only persists logs that meet or exceed the minimum level

The system checks rules in order of specificity, from most specific (all three fields populated) to least specific (org-wide default).

## Practical Examples

### Environment-Specific Configuration

The logging code remains the same across all environments. What changes is the metadata configuration that controls which logs are actually persisted:

**Development Environment Metadata:**

```
Category: Apex
Type: (blank)
Area: (blank)
Level: DEBUG
```

**Production Environment Metadata:**

```
Category: Apex
Type: (blank)
Area: (blank)
Level: INFO
```

**Same Logging Code:**

```apex
Triton.instance.addLog(
    Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .type(TritonTypes.Type.Backend)
        .area(TritonTypes.Area.Accounts)
        .summary('Account validation started')
        .details('Validating account data: ' + accountData)
        .level(TritonTypes.Level.DEBUG)  // Same level in both environments
);
```

In development, this DEBUG log would be captured. In production, it would be filtered out based on the INFO-level configuration.

### Error Handling

Errors should always be logged at the ERROR level:

```apex
try {
    // Business logic
    processAccount(account);
} catch (Exception e) {
    // Always log errors
    Triton.instance.addError(TritonTypes.Area.Accounts, e);
}
```

## Log Levels are Ubiquitos

The log level concept applies consistently across all Triton logging capabilities:

### Apex Logging

```apex
Triton.instance.addEvent(
    TritonTypes.Level.DEBUG,  // Set log level
    TritonTypes.Type.Backend,
    TritonTypes.Area.Accounts,
    'Account processing',
    'Processing account data'
);
```

### LWC Logging

```javascript
this.tritonLogger.log(
    this.tritonLogger.debug(TYPE.BACKEND, AREA.ACCOUNTS)
        .summary('Account data loaded')
        .details(JSON.stringify(accountData))
        .level(LEVEL.DEBUG)  // Set log level
);
```

### Flow Logging

When using the Triton Flow action, you can set the log level parameter to control verbosity:

```
Level: DEBUG
Summary: Account validation completed
Details: Account {!Account.Id} validated successfully
```

## Best Practices

### 1. Start Conservative

Begin with INFO level in production and adjust based on your monitoring needs. You can always increase verbosity for specific areas when troubleshooting.

### 2. Use Specific Rules

Create targeted log level rules for different functional areas rather than relying solely on org-wide defaults.

### 3. Monitor Log Volume

Keep an eye on log volume and adjust levels accordingly. Too much logging can impact performance and storage costs.

### 4. Error Logging

Always log errors at the ERROR level - these should never be filtered out as they represent actual problems that need attention.

### 5. Development vs Production

Use different log level configurations for development and production environments. Development can use DEBUG or FINE levels, while production should typically use INFO or WARNING levels.

## Real-World Scenarios

### Scenario 1: Account Processing System

```apex
// Metadata Configuration
// Category: Apex, Type: (blank), Area: Accounts, Level: INFO

// In your code
Triton.instance.addLog(
    Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .area(TritonTypes.Area.Accounts)
        .summary('Account validation started')
        .level(TritonTypes.Level.INFO)  // Will be logged
);

Triton.instance.addLog(
    Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .area(TritonTypes.Area.Accounts)
        .summary('Detailed validation step')
        .level(TritonTypes.Level.DEBUG)  // Will be filtered out
);
```

### Scenario 2: Integration Monitoring

```apex
// Metadata Configuration
// Category: Integration, Type: (blank), Area: (blank), Level: ERROR

// In your integration code
Triton.instance.addLog(
    Triton.makeBuilder()
        .category(TritonTypes.Category.Integration)
        .summary('API call successful')
        .level(TritonTypes.Level.INFO)  // Will be filtered out
);

// Only errors will be logged
Triton.instance.addIntegrationError(
    TritonTypes.Area.ExternalAPI,
    apiException,
    httpRequest,
    httpResponse
);
```

### Scenario 3: Flow Debugging

```apex
// Metadata Configuration
// Category: Flow, Type: (blank), Area: (blank), Level: DEBUG

// In Flow, use the Triton action with:
// Level: DEBUG
// Summary: Flow decision point reached
// Details: Decision criteria met: {!decisionResult}
```

## Choosing Appropriate Log Levels

Understanding when to use each log level is crucial for effective logging. Here's guidance on which types of information belong at each level:

### ERROR Level

Use for critical failures that require immediate attention:

* Unhandled exceptions and system errors
* Integration failures that break business processes
* Data corruption or loss scenarios
* Security violations or authentication failures
* System resource exhaustion (CPU, memory, governor limits)

```apex
try {
    processAccount(account);
} catch (Exception e) {
    Triton.instance.addError(TritonTypes.Area.Accounts, e);
}
```

### WARNING Level

Use for issues that may need attention but aren't critical:

* Deprecated feature usage
* Performance degradation indicators
* Business rule violations that don't break the process
* Retry scenarios and temporary failures
* Approaching governor limits

```apex
// Check if we're approaching governor limits
if (System.Limits.getQueries() > System.Limits.getLimitQueries() * 0.8) {
    Triton.instance.addWarning(
        TritonTypes.Type.Backend,
        TritonTypes.Area.Accounts,
        'Approaching SOQL query limit',
        'Used: ' + System.Limits.getQueries() + 
        ', Limit: ' + System.Limits.getLimitQueries() + 
        ', Remaining: ' + (System.Limits.getLimitQueries() - System.Limits.getQueries())
    );
}
```

### INFO Level

Use for important business events and milestones:

* Record creation, updates, and deletions
* Process completion and major workflow steps
* User actions and business transactions
* Integration success and data synchronization
* Scheduled job execution and completion

```apex
Triton.instance.addEvent(
    TritonTypes.Type.Backend,
    TritonTypes.Area.Accounts,
    'Account created successfully',
    'Account ID: ' + newAccount.Id + ', Owner: ' + newAccount.OwnerId
);
```

### DEBUG Level

Use for detailed debugging information:

* Method entry and exit points
* Variable values and state changes
* Decision points in business logic
* Query results and data transformations
* Performance timing information

```apex
Triton.instance.addDebug(
    TritonTypes.Type.Backend,
    TritonTypes.Area.Accounts,
    'Account validation started',
    'Validating account: ' + account.Id + ', Industry: ' + account.Industry
);
```

### FINE Level

Use for fine-grained debugging and code flow tracking:

* Loop iterations and collection processing
* Conditional branch execution
* Detailed parameter values
* Minor state transitions
* Helper method execution

```apex
Triton.instance.addEvent(
    TritonTypes.Level.FINE,
    TritonTypes.Type.Backend,
    TritonTypes.Area.Accounts,
    'Processing account field',
    'Field: Industry, Value: ' + account.Industry + ', Validation: passed'
);
```

### FINER Level

Use for very detailed debugging when troubleshooting complex issues:

* Individual record processing in bulk operations
* Detailed stack trace analysis
* Memory usage and performance metrics
* Network call details and response parsing
* Complex algorithm step-by-step execution

```apex
Triton.instance.addEvent(
    TritonTypes.Level.FINER,
    TritonTypes.Type.Backend,
    TritonTypes.Area.Accounts,
    'Bulk account processing iteration',
    'Processing record ' + (i + 1) + ' of ' + accounts.size() + 
    ', Account: ' + account.Id + ', Status: ' + processingStatus
);
```

### FINEST Level

Use for the most detailed debugging information:

* Individual character processing in string operations
* Bit-level operations and data structure details
* Memory allocation and garbage collection events
* Network packet-level information
* Detailed timing for micro-optimizations

```apex
Triton.instance.addEvent(
    TritonTypes.Level.FINEST,
    TritonTypes.Type.Backend,
    TritonTypes.Area.Accounts,
    'String processing detail',
    'Processing character ' + (j + 1) + ' of ' + fieldValue.length() + 
    ', Character: "' + fieldValue.charAt(j) + '", ASCII: ' + (int)fieldValue.charAt(j)
);
```

## Log Level Guidelines

### General Principles

* **ERROR**: Something is broken and needs immediate attention
* **WARNING**: Something might be wrong, but the system can continue
* **INFO**: Important business events that stakeholders should know about
* **DEBUG**: Detailed information useful for troubleshooting
* **FINE**: Fine-grained debugging for complex issues
* **FINER**: Very detailed debugging for deep troubleshooting
* **FINEST**: Extremely detailed debugging for performance optimization

### Performance Considerations

* Higher log levels (FINE, FINER, FINEST) can impact performance
* String concatenation and object serialization in logs should be minimized
* Consider using conditional logging for expensive operations
* Monitor log volume and adjust levels based on system performance

### Environment-Specific Recommendations

* **Development**: DEBUG or FINE level for comprehensive debugging
* **Staging**: INFO level to simulate production behavior
* **Production**: INFO or WARNING level to focus on business events
* **Troubleshooting**: Temporarily increase to DEBUG or FINE as needed

By understanding and properly configuring log levels, you can maintain comprehensive visibility into your application's behavior while keeping log volumes manageable and focused on the information that matters most for your specific use case.


# Beyond Apex

In this series of articles we'll cover more advanced logging scenarios that extend beyond Apex code.

Oftentimes, we may have more than Apex code running in our environments. Salesforce offers a variety of technologies you might be using. Chances are, your org has a mix of Apex, LWC, and Flows, in varying proportions.

This makes troubleshooting considerably more complicated. What if a trigger kicks off a Flow and that Flow breaks? What if an LWC component kicks off some Apex code that breaks during a DML operation? What if there's a screen flow that invokes some Apex backend that kicks off a Flow? The number of such permutations one can encounter is vast. That's why we've put together some helpful tips to enable logging across any mix of technologies your team might be using.

The biggest problem with using a mix of platform technologies is being able to trace the execution throughout the entire transaction. Luckily, Triton has a way to deal with this and provide you with a unified trace of execution that includes ample details.

Read on for some of the more common examples. If you don't see your exact scenario covered, we'd love to hear from you!

{% hint style="info" %}
We recommend you work through the examples below in the order they are presented.
{% endhint %}

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FE6Amk05Frci0Mcdm3h0q%2FScreenshot%202024-06-13%20at%206.01.14%20PM.png?alt=media&amp;token=54b6e296-28b8-4986-aa56-73ddbf7745ae" alt=""><figcaption></figcaption></figure>


# LWC

In this article we'll take a look at logging in LWC components and familiarize ourselves with Triton's JS interface.

LWC is a powerful UI framework in use today by organizations of all sizes. LWC provides a wealth of capabilities that extend the platform's user interface and allow developers to create rich visual experiences. However, with great power comes complexity.

It's quite common for LWC-based interfaces to become large and complex. At that point, one needs a little something to help manage the expanding functionality without loosing sanity. As you may have guessed, this is yet another area to leverage Pharos Triton. Let's first examine the basics.

## Component Binding

When initializing Triton in an LWC component, it's crucial to use the `bindToComponent()` method. This method creates a component-specific context for logging that enables:

1. **Component Identification**: Each log entry is automatically tagged with the component that generated it
2. **Template Management**: Component-specific log templates are properly scoped and managed
3. **Stack Trace Accuracy**: Error traces and component details are correctly captured

Here's the proper way to bind Triton to your component:

```javascript
this.tritonLogger = new Triton().bindToComponent('myComponentName');
```

The `bindToComponent()` argument should be a unique identifier for your component, typically matching the component's name. This binding ensures that when debugging issues in production, you can easily trace logs back to their source component.

{% hint style="warning" %}
Always use `bindToComponent()` when initializing Triton. Without it, you'll lose important component context in your logs and template functionality won't work correctly.
{% endhint %}

## Creating an LWC Logger

The good news is that getting a hold of the Triton logger in LWC is quite easy. The logger component is called triton. To access its capabilities, simply include it in your controller class. The initialization timing depends on whether your component uses @wire methods:

### Components Without @wire

For components without @wire decorators, initialize Triton in the *connectedCallback()* method. This is safe because connectedCallback is one of the first lifecycle hooks that fires when a component is added to the DOM, and without @wire decorators, there's no risk of missing early data or error events:

{% code title="logDemo.js" lineNumbers="true" %}

```javascript
//Triton logger component
import Triton, { TYPE, AREA, LEVEL } from 'c/triton';

export default class LogDemo extends LightningElement {
    //instance of the logger 
    tritonLogger;
    
    connectedCallback() {
        //create new logger - uses singleton pattern
        this.tritonLogger = new Triton().bindToComponent('logDemo');
    }
    
    //let's utilize our logger
    async handleClick(event) {
        ....
        
        //invoke some action
        someAction({}).then(() => {
            // Buffer the log for later sending
            this.tritonLogger.log(
                this.tritonLogger.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                    .summary('Action completed successfully')
                    .details(JSON.stringify({ someKey: 'value' }))
            );
        }).catch(async (error) => {
            // Immediately send the error log
            await this.tritonLogger.logNow(
                this.tritonLogger.exception(error)
                    .summary('Action failed')
                    .details(JSON.stringify({ eventDetails: event }))
            );
        });
        
        ....
    }    
}    
```

{% endcode %}

### Components With @wire

When using @wire decorators, we need to be more careful about initialization timing. The Lightning Web Component lifecycle follows this sequence:

1. Constructor runs
2. @wire decorators are initialized and begin fetching data
3. connectedCallback executes
4. Component renders

This means that if we initialize Triton in connectedCallback, we might miss important wire-related events that occur between steps 2 and 3. Therefore, for components with @wire decorators, we initialize in the constructor.

```javascript
export default class LogDemoWithWire extends LightningElement {
    tritonLogger;
    
    constructor() {
        super();
        this.tritonLogger = new Triton().bindToComponent('logDemoWithWire');
    }
    
    @wire(getRecord, { /* wire parameters */ })
    wiredRecord({ error, data }) {
        if (error) {
            this.tritonLogger.logNow(
                this.tritonLogger.exception(error)
                    .summary('Failed to load record')
            );
        }
        // ... handle data ...
    }
}
```

{% hint style="info" %}
**Best Practice**: While we've shown both initialization patterns, it's actually perfectly safe and arguably cleaner to always initialize Triton in the constructor, regardless of whether your component uses @wire or not. The constructor initialization will work in all scenarios because:

1. It ensures the logger is available as early as possible in the component lifecycle
2. Triton uses the singleton pattern, so there's no performance penalty
3. It reduces cognitive overhead - you don't need to think about where to initialize based on @wire usage
4. It future-proofs your component if you later add @wire decorators

The only minor consideration is that if your component is never actually connected to the DOM (very rare), you'll have initialized Triton unnecessarily. However, this edge case rarely outweighs the benefits of consistent initialization.
{% endhint %}

## Inside Triton.js

The LWC version of Triton implements a robust logging system with transaction management and automatic log flushing. The logger provides different logging levels (error, warning, info, debug) and uses a builder pattern for constructing logs with rich context.

Each log can include details such as:

* Transaction ID for tracking related logs
* User ID and timestamp
* Component stack traces
* Runtime information (browser, device, performance metrics)
* Summary and detailed information

The logger automatically manages log buffering and flushing to the server, with an auto-flush mechanism that triggers after a period of inactivity.

## TritonBuilder Pattern

Triton uses a builder pattern that allows for fluent, chainable logging statements. Each logging method (error, warning, info, debug) returns a builder instance that you can use to add additional context to your log:

```javascript
this.tritonLogger.log(
    this.tritonLogger.error(TYPE.FRONTEND, AREA.ACCOUNTS)
        .summary('Failed to load account details')
        .details(JSON.stringify({ accountId: '123' }))
        .relatedObjects(['001xx000003DGb2AAG'])
);
```

The builder captures rich contextual information automatically, including:

* Component details and stack traces
* Runtime information (browser, device, etc.)
* Transaction IDs
* Timestamps
* User context

Each builder method is chainable, allowing you to construct logs with as much or as little detail as needed:

```javascript
const startTime = performance.now();
// ... perform operation ...
this.tritonLogger.log(
    this.tritonLogger.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
        .summary('Processing account update')
        .details(JSON.stringify(accountData))
        .duration(performance.now() - startTime)
        .relatedObjects([accountId])
);
```

## Component-Specific Templates

Triton provides a powerful templating system that allows you to define logging templates specific to each component. When you use `bindToComponent()`, Triton ensures that templates are properly scoped to your component through method proxying.

### Setting Up Templates

You can define templates with common properties that you'll reuse across your component:

```javascript
export default class AccountManager extends LightningElement {
    tritonLogger;
    
    connectedCallback() {
        this.tritonLogger = new Triton().bindToComponent('AccountManager');
        
        // Set up a component-specific template
        this.tritonLogger.setTemplate(
            this.tritonLogger.makeBuilder()
                .type(TYPE.FRONTEND)
                .area(AREA.ACCOUNTS)
                .level(LEVEL.INFO)
                .relatedObjects([this.recordId])
        );
    }
}
```

### Using Templates

Once defined, you can use the template as a base for your logs, adding only the specific details that change:

```javascript
async handleAccountUpdate() {
    try {
        await updateAccount(this.accountId);
        
        // Uses the template and adds specific details
        this.tritonLogger.log(
            this.tritonLogger.fromTemplate()
                .summary('Account updated successfully')
                .details(JSON.stringify({ accountId: this.accountId }))
        );
    } catch (error) {
        // Template properties are preserved in error logs too
        this.tritonLogger.logNow(
            this.tritonLogger.fromTemplate()
                .exception(error)
                .summary('Failed to update account')
        );
    }
}
```

{% hint style="info" %}
Templates are automatically scoped to the component that created them thanks to Triton's proxy-based component binding. This means:

* Each component can have its own template
* Templates won't interfere with each other
* Template methods (`setTemplate` and `fromTemplate`) are only available after calling `bindToComponent()`
  {% endhint %}

This templating system is particularly valuable when:

* Your component generates many similar logs
* You want to ensure consistent logging patterns
* You need to maintain common context across all component logs
* You want to reduce repetitive logging code

## Buffered vs Immediate Logging

Triton provides two methods for sending logs to the server:

* `log()`: Buffers the log entry for later sending. Multiple logs will be sent together during periodic flush operations or when explicitly flushed. This is more efficient for high-volume logging.
* `logNow()`: Immediately sends the log entry to the server. This is useful for critical errors or when immediate logging feedback is required. Returns a Promise that resolves when the log is saved.

{% hint style="info" %}
When using `logNow()`, only the specific log entry passed to the method is sent to the server immediately. Any other logs in the buffer remain there until the next flush operation. This selective immediate logging is particularly useful when you need to ensure critical logs are saved without affecting the buffering of less urgent logs.
{% endhint %}

For example:

```javascript
// This log will be buffered
this.triton.log(
    this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
        .summary('Debug info')
);

// This error log will be sent immediately
await this.triton.logNow(
    this.triton.error(TYPE.FRONTEND, AREA.ACCOUNTS)
        .summary('Critical error')
);

// Previously buffered debug log is still in the buffer
```

### Real-World Logging Scenario

Consider a complex account management interface where users can perform multiple operations:

```javascript
async handleAccountOperations() {
    // Buffer debug logs for routine operations
    this.triton.log(
        this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
            .summary('Starting account update sequence')
    );

    try {
        // Perform multiple account operations
        await this.updateAccountDetails();
        
        // Buffer success logs
        this.triton.log(
            this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('Account details updated successfully')
                .details(JSON.stringify({ accountId: this.accountId }))
        );

    } catch (error) {
        // Immediately log critical errors
        await this.triton.logNow(
            this.triton.exception(error)
                .summary('Failed to update account')
                .details(JSON.stringify({ 
                    accountId: this.accountId,
                    operation: 'updateAccountDetails',
                    errorDetails: error.message 
                }))
        );
        
        // Show error to user with support notification
        this.showErrorMessage(
            'Failed to update account. A support team member has been notified and will contact you shortly.'
        );
    }
}
```

In this scenario:

* Debug and success logs are buffered because they're routine and non-critical
* Error logs are sent immediately because:
  1. They need to be available right away for troubleshooting
  2. The error might prevent subsequent operations from completing
  3. Support teams can respond in real-time to mission-critical failures
  4. The error context is preserved even if the component crashes
  5. Time-sensitive operations can trigger immediate support intervention

This immediate logging pattern is particularly valuable in scenarios like financial transactions, healthcare operations, or other mission-critical processes where real-time monitoring and rapid response are essential.

## Advanced Wire Patterns with Logging

When working with wired properties in LWC, there's a powerful pattern that combines programmatic refresh capabilities with logging. This involves wiring the same Apex method to two different properties:

```javascript
export default class OrderManager extends LightningElement {
    @wire(getOrderItems, { orderId: '$recordId' })
    wiredOrderItems;

    @wire(getOrderItems, { orderId: '$recordId' })
    logOrderItemsChange({ error, data }) {
        if (data) {
            this.setOrderItems(data);
            this.triton.log(
                this.triton.fromTemplate()
                    .level(LEVEL.DEBUG)
                    .summary('Order items retrieved successfully')
                    .relatedObjects([this.recordId])
                    .details(`Retrieved ${data.length} order items`)
            );
        } else if (error) {
            this.error = error;
            this.triton.log(
                this.triton.fromTemplate()
                    .level(LEVEL.ERROR)
                    .summary('Error retrieving order items')
                    .relatedObjects([this.recordId])
                    .exception(error)
            );
        }
    }
}
```

This pattern serves two important purposes:

1. **Programmatic Refresh**: The `wiredOrderItems` property provides a reference that can be used to programmatically refresh the data using `refreshApex(this.wiredOrderItems)`.
2. **Automatic Logging**: The second wire decorator with the callback function handles data processing and automatically logs both successful retrievals and errors.

This approach is particularly useful when you need to:

* Track all data loading attempts, both automatic and manual refreshes
* Maintain a detailed audit trail of data operations
* Debug intermittent loading issues
* Monitor performance patterns in data retrieval

{% hint style="info" %}
The dual-wire pattern doesn't cause double network requests - LWC's wire service is smart enough to share a single subscription for identical wire configurations.
{% endhint %}

Now that we've covered some basics, let's have a look at a more interesting example and combine the LWC logger with its Apex counterpart.


# LWC Transaction Management

Learn how Triton manages LWC transactions and logging sessions, including automatic transaction management and best practices.

Transaction management is a crucial aspect of logging in LWC components. Triton provides automated transaction handling that helps correlate logs across different operations and components. Let's explore how this works.

## Automatic Transaction Management

Triton automatically manages transactions through its `TransactionManager` class. When you create a new Triton instance, it automatically:

1. Checks for an existing transaction ID in the session storage
2. Creates a new transaction ID if none exists
3. Starts monitoring for log activity to handle auto-flushing

Here's how this initialization happens behind the scenes:

```javascript
connectedCallback() {
    this.triton = new Triton();
    // Transaction ID is automatically managed
}
```

## Transaction Storage and Caching

Triton uses session storage to maintain transaction continuity across component lifecycles. This is particularly useful when you have multiple components that need to share the same transaction context.

Here's an example showing how to leverage transaction caching:

```javascript
export default class LogDemo extends LightningElement {
    triton;

    async handleOperation() {
        try {
            // Log the start of operation
            this.triton.log(
                this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                    .summary('Operation started')
            );
            
            // Perform some async operation
            await this.performOperation();
            
            // Log successful completion
            this.triton.log(
                this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                    .summary('Operation completed successfully')
            );
        } catch (error) {
            // Log any errors that occur
            this.triton.log(
                this.triton.exception(error)
                    .summary('Operation failed')
            );
        }
    }
}
```

Behind the scenes, here's what happens when these logs are created:

1. Each `log()` call adds the entry to an internal buffer array in the Triton instance
2. The transaction ID (stored in session storage) is automatically attached to each log
3. The TransactionManager monitors the buffer every 10 seconds
4. If any logs in the buffer are older than 1 minute, they are automatically flushed to the server
5. All logs with the same transaction ID will be correlated in the database, allowing you to trace the entire operation

This buffering and auto-flush mechanism helps optimize performance by:

* Reducing the number of server calls by batching logs together
* Ensuring logs aren't lost if a component is destroyed
* Maintaining transaction context across asynchronous operations
* Automatically cleaning up old logs that might be forgotten

## Auto-Flush Mechanism

Triton implements an intelligent auto-flush mechanism that automatically sends logs to the server based on activity patterns:

* Checks for pending logs every 10 seconds
* Automatically flushes logs that are older than 1 minute
* Ensures logs aren't lost when components are destroyed

The auto-flush mechanism is particularly useful for long-running operations where you want to ensure logs are sent periodically:

```javascript
export default class LogDemo extends LightningElement {
    disconnectedCallback() {
        if (this.triton) {
            // Flush any remaining logs before disconnecting
            this.triton.flush();
            this.triton = undefined;
        }
    }
}
```

## Transaction Methods

Triton provides several methods for manual transaction management when needed:

```javascript
// Start a new transaction
this.triton.startTransaction();

// Resume an existing transaction
this.triton.resumeTransaction(existingTransactionId);

// Stop current transaction and flush logs
this.triton.stopTransaction();
```

When you call `startTransaction()`:

1. A new UUID v4 transaction ID is generated
2. The ID is stored in session storage for cross-component access
3. The auto-flush monitor is started (checks every 10 seconds for logs to flush)
4. Any subsequent logs will use this new transaction ID

When you call `resumeTransaction(existingTransactionId)`:

1. The provided transaction ID is stored in session storage
2. The auto-flush monitor is started
3. Any subsequent logs will use this resumed transaction ID
4. This is useful when you need to correlate logs with an existing transaction

When you call `stopTransaction()`:

1. Any pending logs are immediately flushed to the server
2. The auto-flush monitor is stopped
3. The transaction ID is removed from session storage
4. This ensures all logs are properly saved before ending the transaction

These methods give you explicit control over transaction boundaries when needed, though in most cases, letting Triton handle transactions automatically is preferred.

## Best Practices

Here are some recommended practices for transaction management in LWC:

1. **Let Triton Handle It**: In most cases, let Triton manage transactions automatically. The built-in management is sufficient for most use cases.

```javascript
// Good - Let Triton handle transactions
connectedCallback() {
    this.triton = new Triton();
}
```

2. **Manual Transaction Control**: Use manual transaction methods only when you need explicit control over transaction boundaries. Here are some common scenarios where manual transaction control makes sense:

```javascript
// Scenario 1: Multi-step wizard where you want all steps logged under one transaction
async handleWizardNavigation() {
    if (this.isFirstStep) {
        this.triton.startTransaction();  // Start new transaction at wizard beginning
    }
    
    try {
        // Log current step
        this.triton.log(
            this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary(`Wizard Step ${this.currentStep} completed`)
        );
        
        await this.processCurrentStep();
        
        if (this.isLastStep) {
            // On last step, stop transaction and flush all wizard logs
            this.triton.stopTransaction();
        }
    } catch (error) {
        this.triton.stopTransaction();  // Clean up on error
        throw error;
    }
}

// Scenario 2: Batch processing UI where you want to group related operations
async handleBatchProcessing() {
    this.triton.startTransaction();
    try {
        // Process multiple records in UI
        for (const record of this.selectedRecords) {
            this.triton.log(
                this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                    .summary(`Processing record ${record.Id}`)
            );
            await this.processRecord(record);
        }
        
        // All records processed - log summary and stop transaction
        this.triton.log(
            this.triton.info(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary(`Batch processing complete: ${this.selectedRecords.length} records`)
        );
    } finally {
        this.triton.stopTransaction();
    }
}
```

In most other cases, letting Triton automatically manage transactions is the better choice. For example:

* Single API calls or operations
* Form submissions
* Simple user interactions
* Standard CRUD operations

3. **Component Cleanup**: Always clean up in the disconnectedCallback:

```javascript
disconnectedCallback() {
    if (this.triton) {
        this.triton.flush();
        this.triton = undefined;
    }
}
```

4. **Error Handling**: Always include error handling with transaction management:

```javascript
async handleOperation() {
    try {
        // Perform operation
        await this.doSomething();
    } catch (error) {
        // Log error with current transaction
        await this.triton.logNow(
            this.triton.exception(error)
                .summary('Operation failed')
        );
    }
}
```

By following these practices, you can ensure your LWC components maintain proper transaction context while logging, making it easier to trace and debug issues across your application.


# LWC and Apex

In this article we'll describe the process for logging in LWC in conjunction with Apex. We will examine how Triton associates two different types of logs together under a single umbrella.

Logging across LWC and Apex can be very helpful in both troubleshooting and profiling. The most common scenario is to track your component's UI logs and link these together with Apex action calls on the back end. This approach will allow you to see all LWC and Apex logs under the same transaction.

We'll assume that the start of our user flow originates from a button click (an LWC action) and then continues on the back end in Apex. Our goal is to link together the two types of logs. Let's begin with the LWC side.

## LWC Component

Let's place a button in our component that will start the main execution and logging from a click event.

{% code title="logDemo.html" %}

```javascript
<template>
    ....
    
    <lightning-button 
        variant="brand" 
        label="DML Error" 
        title="DML Error" 
        onclick={handleClick} 
        class="slds-m-left_x-small">
    </lightning-button>
    
    ....
</template>

```

{% endcode %}

## LWC Controller

Now, let's take a look at our LWC controller and create our first log.

{% code title="logDemo.js" lineNumbers="true" %}

```javascript
// Our apex action that will perform some logging
import apexActionThatGeneratesDMLError from '@salesforce/apex/LogDemoController.apexActionThatGeneratesDMLError';
// Triton logger component
import Triton, { AREA, TYPE } from 'c/triton';

export default class LogDemo extends LightningElement {
    triton;
    startTime;
    
    connectedCallback() {
        this.triton = new Triton();
    }
    
    handleClick() {
        this.startTime = performance.now();
        this.executeScenario();
    }
    
    async executeScenario() {
        // Log the start of our execution
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('LWC action (from js) - DML Error')
                .details('LWC action (from js) - DML Error - Execution Start')
                .duration(performance.now() - this.startTime)
        );

        try {
            // Invoke our Apex action passing in the transaction Id 
            // for the apex controller to re-use
            await apexActionThatGeneratesDMLError({
                transactionId: this.triton.transactionId
            });
        } catch (error) {
            // Log this exception
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}    
```

{% endcode %}

The `executeScenario()` method above will generate two LWC logs: one debug and one error log (if the Apex action fails). Note that we are passing our generated transaction Id back to the Apex controller to use for back-end logging.

## Apex Controller

Next, let's look at our Apex controller. The action that we're calling from LWC is also doing some debug and error logging with the provided transaction Id.

{% code title="LogDemoController.cls" lineNumbers="true" %}

```apex
public with sharing class LogDemoController {

//this method will use our logger to create a new transaction Id
@AuraEnabled
public static String getTransactionId() {
	return Triton.instance.startTransaction();
}

@AuraEnabled
public static void apexActionThatGeneratesDMLError(String transactionId) {
	//letting our logger know to re-use an existing transaction Id
	Triton.instance.resumeTransaction(transactionId);
	Triton.instance.debug(TritonTypes.Type.Backend, /* type */
			TritonTypes.Area.Community, /* functional area */
			'LWC controller (apex) - DML Error', /* summary */
			'LWC controller (apex) - DML Error - Apex Execution Start' /* details */
	);
	
	try {
		ContentVersion contentVersion = new ContentVersion();
		contentVersion.ContentLocation = 'Apex Error';
		contentVersion.Title = 'Apex Error';
		contentVersion.PathOnClient = 'ApexError.pdf';
		//this insert statement will generate a DMLException
		insert contentVersion;
	} catch (Exception e) {
		//let's log this exception
		Triton.instance.error(TritonTypes.Area.Community, e);
	}
}
....

}
```

{% endcode %}

Similar to our LWC controller, executing this action will result in a debug and an error log created.

## The Result

Altogether, both LWC and Apex executions will generate the following log structure in a single transaction:

* Parent LWC **Debug** Log from `executeScenario()`
  1. Child Apex **Debug** Log from our `apexActionThatGeneratesDMLError()` action
  2. Child Apex **Error** Log from our try/catch block inside the Apex action
  3. Child LWC **Error** Log from the LWC error handler (if an error occurs)

{% hint style="info" %}
All logs within the same transaction are automatically linked together using the transaction ID. The transaction management is handled automatically by the Triton framework, including caching and auto-flushing of logs.
{% endhint %}

While this example demonstrates passing the transaction ID directly through method parameters, there's another powerful approach using Salesforce Platform Cache. This alternative method is particularly useful for complex scenarios involving multiple components or when direct parameter passing isn't practical. We'll explore platform caching in detail in the next article.


# Platform Cache for Transactions

Learn how to use Salesforce Platform Cache with Triton to manage transaction IDs across different contexts without direct parameter passing.

## Understanding Platform Cache

Salesforce Platform Cache is a distributed caching service that stores frequently accessed data in memory. Triton leverages platform cache to store transaction IDs, making them accessible across different execution contexts without requiring direct parameter passing.

{% hint style="info" %}
**Prerequisites**: Before using platform cache with Triton, you must configure a default cache partition with session cache allocation. See [Platform Cache Setup](https://triton.pharos.ai/1-42/installing-pharos-triton#platform-cache-setup) in the installation guide for detailed configuration instructions.
{% endhint %}

## How Triton Uses Platform Cache

Triton uses platform cache to store transaction IDs, making them accessible across different execution contexts. This is particularly useful when:

* Direct parameter passing is impractical
* You're dealing with multiple components or services
* You need to correlate logs across asynchronous operations

When you enable caching using `withCache()`, Triton:

1. Stores the transaction ID in the platform cache
2. Uses the running user's ID as part of the cache key
3. Automatically retrieves the transaction ID when needed

{% hint style="info" %}
Note that Triton automatically checks for platform cache availability and will gracefully fall back to direct parameter passing if caching is unavailable or no partitions are configured.
{% endhint %}

## Using Cache Instead of Direct Parameter Passing

While our previous article [⚡ LWC and Apex](https://triton.pharos.ai/1-42/beyond-apex/lwc-and-apex) demonstrated passing transaction IDs directly through method parameters, here's an example of how to use platform cache with Triton. This example shows a common scenario where an LWC component needs to log actions and errors across both frontend and backend contexts - one of the most common and effective use cases for platform cache:

{% code title="logDemo.js" %}

```javascript
export default class LogDemo extends LightningElement {
    triton;
    
    connectedCallback() {
        // Bind triton to this component
        this.triton = new Triton().bindToComponent('LogDemo');
    }
    
    async executeScenario() {
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('Cache Demo - Start')
                .details('Starting execution with cache enabled')
        );

        try {
            // Note we're not passing transactionId here
            await apexActionThatGeneratesDMLError({
                cacheEnabled: true
            });
        } catch (error) {
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}
```

{% endcode %}

And in your Apex controller:

{% code title="LogDemoController.cls" %}

```apex
public with sharing class LogDemoController {
    @AuraEnabled
    public static void apexActionThatGeneratesDMLError(Boolean cacheEnabled) {
        if (cacheEnabled) {
            // This will automatically retrieve the transaction ID from cache
            Triton.instance.withCache();
        }
        
        Triton.instance.debug(
            TritonTypes.Type.Backend,
            TritonTypes.Area.Community,
            'Cache Demo - Apex',
            'Executing with cached transaction ID'
        );
        
        try {
            ContentVersion contentVersion = new ContentVersion();
            contentVersion.ContentLocation = 'Apex Error';
            contentVersion.Title = 'Apex Error';
            contentVersion.PathOnClient = 'ApexError.pdf';
            insert contentVersion;
        } catch (Exception e) {
            Triton.instance.error(TritonTypes.Area.Community, e);
        }
    }
}
```

{% endcode %}

## How withCache() Works

When you call `withCache()`, Triton follows this logic:

1. First, it checks if platform cache is available and configured
2. If cache is available:
   * It uses the running user's ID to create a unique cache key
   * Looks for an existing transaction ID in the cache
   * If found, resumes that transaction
   * If not found, generates a new transaction ID and stores it in cache
3. If cache is not available:
   * Automatically falls back to starting a new transaction
   * Continues execution without using cache

This automatic fallback behavior means you don't need to explicitly handle transaction management when cache is unavailable - Triton handles this for you.

## Benefits and Considerations

### Benefits

* Simplified parameter passing
* Works across asynchronous boundaries
* Reduces code complexity
* Makes transaction ID management transparent

### Caveats

{% hint style="warning" %}
Since Triton uses the running user's ID as part of the cache key, all operations performed by the same user within the cache timeout period will share the same transaction ID. This can lead to unintended log grouping in scenarios like:

1. If a batch job runs on behalf of the same user who initiated an LWC action
2. When multiple browser tabs are executing similar operations
3. If the cache isn't cleared properly between operations

Consider these scenarios when deciding whether to use cache or direct parameter passing.
{% endhint %}

### Best Practices

1. LWC components and their associated Apex controllers are ideal candidates for platform cache, especially when dealing with multiple server calls or asynchronous operations
2. Use direct parameter passing for simple, synchronous operations
3. Reserve cache usage for complex scenarios involving multiple contexts
4. Monitor cache usage and adjust partition sizes as needed
5. Consider using `startTransaction()` to generate a new transaction ID when you want to ensure separation between operations

Platform cache provides a powerful way to manage transaction IDs across different execution contexts, but it should be used thoughtfully based on your specific use case.


# Flows

Flows are a powerful low-code automation tool, and one that is often overlooked by logging frameworks. Let's take a look at how to incorporate Pharos Triton logging into your declarative powerhouse.

## Introduction

Salesforce Flows are a game-changer for automating business processes without writing a single line of code. However, like any powerful tool, they can become intricate, making debugging and monitoring a challenge. Enter Pharos Triton – your Flow's new best friend for logging. Let's dive into how you can supercharge your Flows with custom logging using the Triton framework.

## Why Triton Logging for Flows?

Once of the big advantages to using Flows is the ability to utilize Apex code. This technique really opens up a whole world of possibilities. We won't spend too much time here describing the intricacies of Invocable Apex. For more information on what these are all about, please refer to the [Salesforce documentation](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_InvocableMethod.htm).

While Flows are excellent for orchestrating processes, tracking their execution and diagnosing issues can be tedious. Triton provides an invocable Apex action that seamlessly integrates with Flows to create detailed log records. This integration ensures that every step of your Flow is transparent and traceable.

## Setting Up Triton Logging in Your Flow

Let's walk through a simple example: a Partner Intake Screen Flow. This flow captures data through a form and, based on the partner type, assigns a lead score before creating a lead record.

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FVmW7wMpj1LZthrRhFkbo%2FScreenshot%202025-02-12%20at%209.28.23%E2%80%AFAM.png?alt=media&amp;token=efb2ce0f-b695-4d50-a61c-156bbd26eeac" alt="" width="375"><figcaption><p><em>Partner Intake Screen Flow</em></p></figcaption></figure>

### Step 1: Add the First Triton Apex Action

To enable logging, you need to add the Triton Apex action to your Flow. It's best practice to add your logging action as the very first element in the flow. This ensures a log is always created, even if the flow fails at a later step. Additionally, this setup establishes log grouping, allowing any subsequent logs to be related to our initial log.

1. **Click (+)** and the "Action" element onto the canvas.

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2Fm1uo61uurd6H6BHn5vkH%2FScreenshot%202025-02-12%20at%209.31.58%E2%80%AFAM.png?alt=media&amp;token=acb71db4-c9a6-461b-bde4-025887050d72" alt="" width="171"><figcaption><p>Adding an Action</p></figcaption></figure>

2. **Search** for "triton" and select the `Add Log` action

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FXoUeilFJcj6BIWoaCLVY%2FScreenshot%202025-02-12%20at%209.35.43%E2%80%AFAM.png?alt=media&amp;token=8e181f9f-1c5a-4fa9-85b7-7a955788f2f8" alt="" width="181"><figcaption><p>Selecting Triton Action</p></figcaption></figure>

### Step 2: Configure the Log Parameters

Once the Triton action is added, you need to configure its parameters:

1. **Label** your log action, e.g., "Log Partner Intake Start".
2. **Set** the required parameters

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FM9ulEuOlujlzTWRC1Vjh%2FScreenshot%202025-02-10%20at%208.59.00%E2%80%AFPM.png?alt=media&amp;token=2b034b42-145f-4100-99df-d85d3f7a3e9b" alt="" width="375"><figcaption><p><em>Configuring the first log action</em></p></figcaption></figure>

#### Key Parameters Explained

* **Area**: Represents the functional area (see [Area enum](https://github.com/Pharos-AI/triton-docs/blob/main/beyond-apex/apex-logging-basics.md#area)), e.g., `Accounts`, `Opportunities`. This value conveys a business or data-centric description of functionality.
* **Category**: Best left as `Flow` for most logging purposes. This is one of the predefined [Category enum](https://github.com/Pharos-AI/triton-docs/blob/main/beyond-apex/apex-logging-basics.md#category) values that determines how Pharos displays your log records. If an invalid category is provided, it will default to Flow.
* **Type**: Indicates the technical classification (see [Type enum](https://github.com/Pharos-AI/triton-docs/blob/main/beyond-apex/apex-logging-basics.md#type)), such as: `Autolaunched Flow`, `Screen Flow`. Provides a more specific technical classification of the log.
* **Summary**: A brief description of the log entry.
* **Details**: Detailed information that includes any relevant context variables, record ids or other data that the flow is utilizing to make decisions.
* **Level**: Logging level for this log action (see [Level enum](https://github.com/Pharos-AI/triton-docs/blob/main/beyond-apex/apex-logging-basics.md#level)). Controls the verbosity of logging output, ranging from ERROR to FINEST. Defaults to INFO if an invalid level is provided.
* **Flow API Name**: Api name of this flow.
* **Interview GUID**: A unique identifier for the Flow instance. Use `$Flow.InterviewGuid` for consistency.
* **Operation** (Optional): Name of the operation being performed.
* **Transaction ID** (Optional): Can be used to explicitly group related logs together. If provided, will resume an existing transaction instead of creating a new one.
* **Stacktrace** (X-Ray Machine Only): Current stacktrace information for error tracking. This parameter is automatically supplied by the X-Ray machine.
* **Full Stacktrace** (X-Ray Machine Only): Complete stacktrace including previous traces, useful for error propagation. This parameter is automatically supplied by the X-Ray machine.

Special attention to one key parameter: the *Interview GUID*. This parameter represents an ID of the currently running Flow instance. We recommend that you always pass this value along by using the `$Flow.InterviewGuid` global variable. This will allow Pharos Triton to link up Flow failures to your custom logs and provide enhanced post-processing information including:

* Stack traces for error tracking
* User information
* Related object details
* Installed package information
* Pending jobs in the flow queue
* Total active session information

More details on this can be found in the [next section](https://triton.pharos.ai/1-42/beyond-apex/lwc-apex-and-flows).

#### Utilizing Constants for Common Log Parameters

To maintain consistency and simplify updates across all your logging actions, it's recommended to create constants for your log parameters. **Define** constants for parameters like `Area`, `Category`, `Type`\
These parameters should remain consistent across your logging actions. Adopting a **consistent naming convention** is key. In our example, we're prefixing all log-related resources with *Log* or *Log\_* for quick and easy filtering in the toolbox

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FhK4bIiVDu37IvXLkEqxT%2FScreenshot%202025-02-12%20at%209.49.01%E2%80%AFAM.png?alt=media&amp;token=5a2bdd04-75ba-4e6b-906b-50b708d2f36d" alt="" width="282"><figcaption><p>Log Constants</p></figcaption></figure>

Using constants is crucial, even in small Flows. Consider our example Flow with just 4 log actions - changing the *Area* parameter would require updating 4 separate locations without constants. With constants, you only need to update one place.

#### Utilizing Text Templates for Log Details

The Details parameter plays a crucial role in effective troubleshooting and debugging. When crafting your log details, include all relevant contextual information such as:

* Record IDs
* Decision variables
* User inputs
* Any data that influences flow execution

Text templates are the perfect tool for combining static text with dynamic data in your logs. While each log's details will vary, templates help you maintain consistent, well-formatted messages throughout your flow.

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2Fn7RwaYVxBMYgZD7EWQgO%2FScreenshot%202025-02-12%20at%2011.24.49%E2%80%AFAM.png?alt=media&amp;token=b8d7f8ea-2b72-4383-8e42-09db9deb3258" alt=""><figcaption><p><em>Defining a Text Template for Log Details</em></p></figcaption></figure>

{% hint style="info" %}
Following our naming conventions, we prefix these templates with `Log_Details_`. This makes it easy to filter and locate all log-related templates in your flow's toolbox.
{% endhint %}

### Step 3: Implement Logging Throughout Your Flow

With our initial log action in place, it's time to add logging throughout the rest of the flow. While you can clone and paste your existing log action, we recommend creating fresh log actions each time. This approach helps avoid common issues that can arise from cloning, such as confusing element names or incorrect parameter mappings.

Strategic placement of log actions is key. Here are the critical points where you should consider adding logs:

1. **Start of the Flow**: Capture the flow's initiation and any input parameters
2. **User Interactions**: Record form submissions, screen inputs, and user decisions
3. **Data Operations**: Log before and after any DML operations, callouts, or data transformations
4. **Decision Points**: Document which branch of logic the flow is following
5. **Error Handling**: Add detailed logging in fault paths to aid troubleshooting

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FdOXmc8GnFtYFw2vdtd3A%2FScreenshot%202025-02-10%20at%208.24.20%E2%80%AFPM.png?alt=media&amp;token=bae4ff27-7906-41b2-aab7-19df1e49c687" alt="" width="375"><figcaption><p>Partner Intake Flow With Added Logging</p></figcaption></figure>

### Step 4: Viewing the Log Output

Let's examine what our logging looks like in action. We'll run our Partner Intake flow, which we've configured to fail during lead creation to demonstrate error handling.

When you navigate to the Partner Intake Flow Start log, you'll see a comprehensive view of the flow's execution:

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FBdZtlSe6ruBL0FNlqJK9%2FScreenshot_2025-02-10_at_9_06_34%E2%80%AFPM.png?alt=media&amp;token=d6e1b849-79a1-4e1e-afba-9f9e2b184c87" alt=""><figcaption><p><em>All logs related to the same Flow instance are grouped under a parent log using the Interview GUID.</em></p></figcaption></figure>

Each log entry is interactive - clicking on one reveals the detailed information we configured in our log actions, including any custom parameters and context we added:

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2F8zBtQCAMYFA1ewgYsazj%2FScreenshot%202025-02-12%20at%2011.44.45%E2%80%AFAM.png?alt=media&amp;token=7281548b-0aeb-45df-984f-ac0fd6567375" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Pay special attention to the final log entry labeled *Error Occurred*. This entry wasn't created by our custom logging - it's an automatically captured unhandled Flow exception. Triton automatically detects and logs these errors, providing valuable debugging information without any additional configuration.
{% endhint %}

When you open this error log entry, you'll access the standard Pharos flow debug view. This powerful interface breaks down every aspect of the flow's execution, from its current state to error details and decision pathways.

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FQauYP1Z8ivZ3Dv1uB55P%2FScreenshot_2025-02-10_at_9_17_19%E2%80%AFPM.png?alt=media&amp;token=10683bff-d5ee-43cb-b0c3-3b5bc9226c0c" alt=""><figcaption><p>Unhandled Flow Error is automatically pull into our logs</p></figcaption></figure>

### Pass Additional Log Fields (Optional)

If you need to log additional information, use the "Additional Fields" parameter:

1. **Create** a JSON map using a Text Template resource.
2. **Pass** this JSON map to the "Additional Fields" parameter.

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FVCVpaw6Osjm4TtqVN9GP%2FScreenshot_2024-09-08_at_5_06_01_PM.png?alt=media&amp;token=05e8ec19-0fe4-402e-8385-92706acb3881" alt=""><figcaption><p><em>Use a well-formed JSON object to include extra contextual information.</em></p></figcaption></figure>

{% hint style="info" %}
It's best to utilize the Plain Text view here since rich text formatting is completely irrelevant in this context.
{% endhint %}

### Best Practices

* **Strategic Placement**: Add logs at critical points - flow start, before/after DML operations, decision points, and error paths
* **Use Constants**: Maintain consistency by using constants for common log parameters like Area, Category, and Type
* **Use Text Templates**: Create formatted detail messages that combine static text with dynamic flow data
* **Consistent Naming Conventions**:
  * Prefix log actions with "Log\_"
  * Prefix constants with "Log\_"
  * Prefix text templates with "Log\_Details\_"
* **Interview GUID**: Always pass `$Flow.InterviewGuid` to ensure proper log grouping and error tracking
* **Detailed Context**: Include relevant record IDs, user inputs, and decision variables in your log details
* **Additional Fields**: Use JSON-formatted additional fields to capture extra contextual data when needed
* **Error Handling**: Add comprehensive logging in fault paths to aid troubleshooting

## Conclusion

Integrating Triton logging into your Salesforce Flows transforms them from black boxes into transparent, easily debuggable processes. The combination of strategic log placement, consistent naming conventions, and automated error capture creates a robust monitoring system that makes maintenance and troubleshooting straightforward.

By following this guide's best practices, you'll create Flows that are not only powerful automation tools but also self-documenting and easy to support. Whether you're building simple screen flows or complex auto-launched processes, proper logging will be your ally in maintaining and evolving your solutions. Happy Flowing – with the power of Triton logging at your command!


# LWC, Apex and Flows

In this article we will take a look at a more complex logging scenario involving an LWC component, a corresponding Apex controller, and an autolaunched Flow.

In this article, we'll explore a more complex logging scenario involving three Salesforce technologies: an LWC component, its Apex controller, and an autolaunched Flow. Our goal is to produce a unified log trace across all three layers while demonstrating both direct parameter passing and cache-based approaches for transaction management.

The scenario follows this sequence:

1. User clicks a button in LWC
2. Apex controller performs a DML operation
3. Autolaunched Flow triggers from the DML
4. Flow performs some operations and logs its progress

## Implementation Approaches

Let's examine two different approaches to managing transaction IDs across these contexts, with separate implementations for each.

### Approach 1: Direct Parameter Passing

This approach explicitly passes the transaction ID through method parameters.

#### LWC Controller

```javascript
// logDemoDirectParams.js
import apexActionThatTriggersFlow from '@salesforce/apex/LogDemoDirectController.apexActionThatTriggersFlow';
import Triton, { AREA, TYPE } from 'c/triton';

export default class LogDemoDirectParams extends LightningElement {
    triton;
    
    connectedCallback() {
        // Bind triton to this component
        this.triton = new Triton().bindToComponent('LogDemoDirectParams');
    }
    
    async executeScenario() {
        // Create initial LWC log and get transaction ID
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('Flow Demo - Start')
                .details('Starting execution with direct parameter passing')
        );

        try {
            // Pass transaction ID to Apex
            await apexActionThatTriggersFlow({
                transactionId: this.triton.transactionId
            });
        } catch (error) {
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}
```

#### Apex Controller

```apex
// LogDemoDirectController.cls
public with sharing class LogDemoDirectController {
    @AuraEnabled
    public static void apexActionThatTriggersFlow(String transactionId) {
        // Resume the transaction started in LWC
        Triton.instance.resumeTransaction(transactionId);
        
        Triton.instance.debug(
            TritonTypes.Type.Backend,
            TritonTypes.Area.Community,
            'Flow Demo - Apex',
            'Performing DML to trigger flow'
        );
        
        try {
            // Update account to trigger flow
            List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
            if (!accounts.isEmpty()) {
                accounts[0].Name = 'Flow Demo';
                update accounts;
            }
        } catch (Exception e) {
            Triton.instance.error(TritonTypes.Area.Community, e);
        }
    }
}
```

### Approach 2: Using Platform Cache

This approach uses platform cache to automatically share the transaction ID.

#### LWC Controller

```javascript
// logDemoCache.js
import apexActionThatTriggersFlow from '@salesforce/apex/LogDemoCacheController.apexActionThatTriggersFlow';
import Triton, { AREA, TYPE } from 'c/triton';

export default class LogDemoCache extends LightningElement {
    triton;
    
    connectedCallback() {
        // Bind triton to this component
        this.triton = new Triton().bindToComponent('LogDemoCache');
    }
    
    async executeScenario() {
        // Initial log will be cached automatically
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('Flow Demo - Start')
                .details('Starting execution with cache enabled')
        );

        try {
            // No need to pass transaction ID
            await apexActionThatTriggersFlow();
        } catch (error) {
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}
```

#### Apex Controller

```apex
// LogDemoCacheController.cls
public with sharing class LogDemoCacheController {
    @AuraEnabled
    public static void apexActionThatTriggersFlow() {
        // Enable cache to automatically retrieve transaction ID
        Triton.instance.withCache();
        
        Triton.instance.debug(
            TritonTypes.Type.Backend,
            TritonTypes.Area.Community,
            'Flow Demo - Apex',
            'Performing DML to trigger flow'
        );
        
        try {
            // Update account to trigger flow
            List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
            if (!accounts.isEmpty()) {
                accounts[0].Name = 'Flow Demo';
                update accounts;
            }
        } catch (Exception e) {
            Triton.instance.error(TritonTypes.Area.Community, e);
        }
    }
}
```

## Transaction ID Flow

Understanding how the transaction ID connects logs across contexts is crucial:

1. **LWC Initialization**
   * Direct Params: Transaction ID is generated when first log is created
   * Cache: Transaction ID is generated and automatically cached
2. **Apex Execution**
   * Direct Params: Transaction ID is passed via method parameter and resumed
   * Cache: Transaction ID is automatically retrieved from cache
3. **Flow Execution**
   * The Flow's Interview GUID is automatically associated with the transaction
   * All Flow logs are grouped under the same transaction

Here's what the resulting log structure looks like in Pharos:

```
Transaction: 7fb8c320-e8f9-4f1b-9742-1a5768b9e0d2
├── LWC Debug Log (Start)
├── Apex Debug Log (DML Operation)
└── Flow Execution
    ├── Flow Start Log
    ├── Flow Operation Log
    └── Flow Completion Log
```

## Apex Controller

The Apex controller can handle both approaches:

{% code title="LogDemoController.cls" lineNumbers="true" %}

```apex
public with sharing class LogDemoController {
    @AuraEnabled
    public static void apexActionThatTriggersFlow(String transactionId, Boolean cacheEnabled) {
        if (cacheEnabled) {
            Triton.instance.withCache();
        } else if (String.isNotBlank(transactionId)) {
            Triton.instance.resumeTransaction(transactionId);
        }
        
        Triton.instance.debug(
            TritonTypes.Type.Backend,
            TritonTypes.Area.Community,
            'Flow Demo - Apex',
            'Performing DML to trigger flow'
        );
        
        try {
            // Update account to trigger flow
            List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
            if (!accounts.isEmpty()) {
                accounts[0].Name = 'Flow Demo';
                update accounts;
            }
        } catch (Exception e) {
            Triton.instance.error(TritonTypes.Area.Community, e);
        }
    }
}
```

{% endcode %}

## The Flow

The Flow setup remains similar to what's detailed in [Flows](https://triton.pharos.ai/1-42/beyond-apex/flows), with one key difference - we need to ensure the Flow can access the same transaction context regardless of which approach was used to manage the transaction ID.

### Flow Configuration

1. Add the Triton Apex action as the first element
2. Pass the Interview GUID using `$Flow.InterviewGuid`
3. Configure logging parameters as described in the [Flows](https://triton.pharos.ai/1-42/beyond-apex/flows) documentation

<figure><img src="https://3168737167-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsJe8d4KWviwaUiUo8xmI%2Fuploads%2FZArWWRbWmwBYsUK5Vz2B%2FScreenshot%202024-06-14%20at%209.46.09%20AM.png?alt=media&amp;token=d0db6856-889a-4114-a71b-9b69dafc0465" alt="" width="268"><figcaption><p>Basic Flow</p></figcaption></figure>

## Choosing Between Approaches

### Direct Parameter Passing

* Best for simple, linear execution paths
* More explicit and easier to debug
* Recommended for initial implementation

### Platform Cache

* Better for complex scenarios with multiple components
* Handles asynchronous operations more elegantly
* Useful when direct parameter passing becomes cumbersome

{% hint style="info" %}
Both approaches will result in the same unified log structure, showing the complete execution path from LWC through Apex and into the Flow.
{% endhint %}

## The Result

Regardless of the approach chosen, you'll see this log structure:

* Parent LWC Debug Log
  1. Child Apex Debug Log
  2. Child Flow Debug Log
  3. Additional Flow logs as configured
  4. Any error logs if exceptions occur

This unified view provides complete visibility into your execution path across all three technologies.

## Handling Flow Failures

When an unhandled error occurs in your Flow, Pharos automatically captures and correlates this failure with your existing transaction logs. This is possible because:

1. The Flow's Interview GUID is passed to each Triton log action
2. Pharos automatically captures unhandled Flow errors
3. The transaction ID links everything together

### Example of an Unhandled Flow Error

Let's modify our example to trigger an error in the Flow:

```apex
// LogDemoCacheController.cls
public with sharing class LogDemoCacheController {
    @AuraEnabled
    public static void apexActionThatTriggersFlow() {
        Triton.instance.withCache();
        
        Triton.instance.debug(
            TritonTypes.Type.Backend,
            TritonTypes.Area.Community,
            'Flow Demo - Apex',
            'Triggering flow that will fail'
        );
        
        try {
            // Update account with invalid data to cause Flow failure
            List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
            if (!accounts.isEmpty()) {
                accounts[0].Name = null; // This will cause Flow validation to fail
                update accounts;
            }
        } catch (Exception e) {
            Triton.instance.error(TritonTypes.Area.Community, e);
        }
    }
}
```

### Resulting Log Structure

When the Flow fails, you'll see this structure in Pharos:

```
Transaction: 7fb8c320-e8f9-4f1b-9742-1a5768b9e0d2
├── LWC Debug Log (Start)
├── Apex Debug Log (DML Operation)
└── Flow Execution
    ├── Flow Start Log
    ├── Flow Operation Log
    └── Unhandled Flow Error
        └── Flow Debug Details
            ├── Interview GUID
            ├── Current Element
            ├── Error Message
            └── Stack Trace
```

{% hint style="info" %}
The automatic correlation of unhandled Flow errors is a key feature that helps maintain visibility across your entire execution path, even when things go wrong. This is particularly valuable in production environments where direct Flow debugging isn't available.
{% endhint %}

### Benefits of Automatic Error Correlation

1. **Complete Context**: See the entire execution path that led to the failure
2. **No Extra Code**: No additional error handling required to capture Flow failures
3. **Production Debugging**: Valuable insight into production issues without debug logs
4. **Time Savings**: Quickly identify where in the process the failure occurred

For more details on Flow logging and error handling, see the [Flows](https://triton.pharos.ai/1-42/beyond-apex/flows) documentation.


# Profiling

Capture rich performance telemetry from your LWC components — backend calls, user interactions, render cycles, and custom marks — using Triton's built-in profiling APIs.

LWC components don't just need logging — they need to be *fast*. Slow page loads, sluggish form submissions, and runaway re-renders all hurt the user experience, and they're notoriously hard to diagnose after the fact. Triton ships with a set of profiling helpers that piggy-back on the existing logger so you can capture performance data with the same fluent API you already use for logs.

Every profiling event ends up as a regular `pharos__Log__c` record, with a `duration` value and a typed `TYPE.*` marker, which means everything you've already built around Triton (dashboards, notifications, taxonomies, issue tracking) lights up automatically once you start instrumenting components.

## What Triton Captures

Triton's profiling layer covers four common LWC performance scenarios:

| Scenario                            | Method                                                 | Log type                   |
| ----------------------------------- | ------------------------------------------------------ | -------------------------- |
| Apex / backend wire calls           | `timeBackendCall(name, fn)`                            | `TYPE.BACKEND_CALL`        |
| User-driven interactions            | `timeUserInteraction(name, fn)`                        | `TYPE.USER_INTERACTION`    |
| Component lifecycle (mount/unmount) | `trackComponentLifecycle('connected'\|'disconnected')` | `TYPE.COMPONENT_LIFECYCLE` |
| Render cycles                       | `trackComponentRender()`                               | `TYPE.COMPONENT_RENDER`    |
| Arbitrary timed regions             | `startPerformanceMark` / `endPerformanceMark`          | `TYPE.PERFORMANCE`         |

The expanded `TYPE` enum in `c/triton` looks like this:

```javascript
export const TYPE = {
    BACKEND: 'Backend',
    FRONTEND: 'Frontend',
    BACKEND_CALL: 'BackendCall',
    COMPONENT_LIFECYCLE: 'ComponentLifecycle',
    COMPONENT_RENDER: 'ComponentRender',
    USER_INTERACTION: 'UserInteraction',
    PERFORMANCE: 'Performance'
};
```

## Component Binding is Required

The profiling APIs only work after you've called `bindToComponent()`. The same binding you use for [regular LWC logging](https://triton.pharos.ai/1-42/beyond-apex/lwc) doubles as the anchor for performance tracking — Triton generates a unique instance ID under the hood (`componentKey = name-uuid`) so two instances of the same component on a page get isolated marks, render counts, and lifecycle events.

If you call a profiling method without binding first, Triton logs a console warning and returns without doing anything — it deliberately won't throw and break your component.

{% hint style="info" %}
You only need to bind once per component. The instance you get back from `bindToComponent()` is a Proxy around the singleton `Triton` instance, so calling `new Triton().bindToComponent('Name')` in two components on the same page is perfectly safe.
{% endhint %}

## Minimum Viable Setup

Here's a complete example that wires Triton up for performance tracking. Add this skeleton to any component you want to profile and you'll get lifecycle and render telemetry for free, plus the option to instrument specific operations.

{% code title="myComponent.js" lineNumbers="true" %}

```javascript
import Triton from 'c/triton';

export default class MyComponent extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('MyComponent');
        this.triton.trackComponentLifecycle('connected');
    }

    renderedCallback() {
        this.triton.trackComponentRender();
    }

    disconnectedCallback() {
        this.triton.trackComponentLifecycle('disconnected');
    }
}
```

{% endcode %}

That's it. Every mount, unmount, and render now produces a structured log entry tied to your component, the current transaction, and the bound user. From here you can layer in the more specialized profiling helpers covered in the rest of this section.

## Locker Service Compatibility

All profiling internals use a safe `getCurrentTime()` helper that prefers `performance.now()` and falls back to `Date.now()` when the Performance API is restricted (which happens under Locker Service in some component contexts). You don't need to think about it — timing will work everywhere your LWC runs.

## Where to Go Next

Pick the area that matches what you're trying to measure:

* [Backend Calls](https://triton.pharos.ai/1-42/beyond-apex/profiling/backend-calls) — wrap your Apex calls in `timeBackendCall(...)` and pick from four error-handling scenarios.
* [User Interactions](https://triton.pharos.ai/1-42/beyond-apex/profiling/user-interactions) — time anything kicked off by a user (form submits, multi-step flows) with `timeUserInteraction(...)`.
* [Component Lifecycle](https://triton.pharos.ai/1-42/beyond-apex/profiling/component-lifecycle) — track mounts, unmounts, render counts, and understand per-instance isolation.
* [Custom Performance Marks](https://triton.pharos.ai/1-42/beyond-apex/profiling/custom-marks) — drop browser-style marks anywhere in your code with `startPerformanceMark` / `endPerformanceMark`.


# Backend Calls

Wrap Apex calls in timeBackendCall(...) to capture durations, start/complete events, and exceptions — with four flexible error-handling scenarios.

Most LWC performance problems live in the round trip to the server. `timeBackendCall(methodName, apexCall)` is the workhorse for measuring that round trip. It logs the start of the call, waits for the promise, logs completion (with duration), and — if something goes wrong — logs the failure with the same duration baseline plus the exception.

Under the hood it returns a `PerformanceCallBuilder`, which lets you tune *how* errors are handled before the call is actually executed.

## Basic Usage

{% code title="productSearch.js" lineNumbers="true" %}

```javascript
import Triton from 'c/triton';
import searchProducts from '@salesforce/apex/ProductController.searchProducts';

export default class ProductSearch extends LightningElement {
    triton;
    products = [];

    connectedCallback() {
        this.triton = new Triton().bindToComponent('ProductSearch');
        this.triton.trackComponentLifecycle('connected');
    }

    async handleSearch() {
        const searchTerm = this.searchInput.value;

        try {
            const results = await this.triton.timeBackendCall(
                'searchProducts',
                () => searchProducts({ searchTerm })
            ).execute();

            this.products = results;
        } catch (error) {
            this.showErrorMessage('Search failed. Please try again.');
        }
    }
}
```

{% endcode %}

Three things to notice:

1. The Apex call is wrapped in an arrow function so Triton controls when it runs.
2. `methodName` ("searchProducts") is the label that ends up on the resulting log records. Use the real Apex method name so logs are easy to find.
3. `.execute()` is the trigger — until you call it, no logging or Apex invocation happens.

## The Four Error-Handling Scenarios

`PerformanceCallBuilder` exposes two modifiers that combine into four scenarios. The defaults (built-in logging + rethrow) match what 90% of code wants.

| Modifiers                                                | Error handler           | Rethrow | When to use                                                                            |
| -------------------------------------------------------- | ----------------------- | ------- | -------------------------------------------------------------------------------------- |
| `.execute()`                                             | Built-in (logs failure) | Yes     | Default. The standard try/catch pattern.                                               |
| `.withoutRethrow().execute()`                            | Built-in (logs failure) | No      | You want failures logged but don't need an exception in the calling code.              |
| `.withCustomErrorHandler(fn).execute()`                  | Custom only             | Yes     | You want full control over the side effects but the calling code still needs to react. |
| `.withCustomErrorHandler(fn).withoutRethrow().execute()` | Custom only             | No      | Fire-and-forget calls with custom telemetry/UX.                                        |

### 1. Default: log + rethrow

```javascript
try {
    const result = await this.triton.timeBackendCall(
        'processPayment',
        () => processPayment({ amount: 100, cardToken: 'token123' })
    ).execute();

    this.showPaymentSuccess(result);
} catch (error) {
    this.handlePaymentError(error);
}
```

The failure is automatically logged with the method name, duration, and exception, then re-thrown so your `catch` block runs as usual.

### 2. Built-in logging, no rethrow

```javascript
const result = await this.triton.timeBackendCall(
    'processPayment',
    () => processPayment({ amount: 100, cardToken: 'token123' })
)
.withoutRethrow()
.execute();

if (result) {
    this.showPaymentSuccess(result);
} else {
    this.showPaymentWarning('Payment could not be processed');
}
```

Useful when you want the call to fail silently from a control-flow perspective but still capture the failure log. A `null` return is your signal that something went wrong.

### 3. Custom handler + rethrow

```javascript
try {
    const result = await this.triton.timeBackendCall(
        'processPayment',
        () => processPayment({ amount: 100, cardToken: 'token123' })
    )
    .withCustomErrorHandler((error, context) => {
        this.sendToErrorTracking({
            method: context.methodName,
            duration: context.duration,
            error: error.message,
            component: 'PaymentProcessor'
        });
    })
    .execute();

    this.showPaymentSuccess(result);
} catch (error) {
    this.handlePaymentError(error);
}
```

Custom handlers receive `(error, context)` where `context` is `{ methodName, duration }` for backend calls. Use this when you want to enrich the failure with extra side effects (external monitoring, fancy toasts) but still need an exception to bubble.

{% hint style="warning" %}
A custom handler **replaces** the built-in failure log — it doesn't run alongside it. If you still want a Triton log on failure, call `this.triton.log(...)` from inside your handler.
{% endhint %}

### 4. Custom handler, no rethrow

```javascript
const result = await this.triton.timeBackendCall(
    'processPayment',
    () => processPayment({ amount: 100, cardToken: 'token123' })
)
.withCustomErrorHandler((error, context) => {
    this.showUserFriendlyPaymentError(error);
    this.logToExternalService('payment_failure', {
        duration: context.duration,
        method: context.methodName,
        error: error.message
    });
})
.withoutRethrow()
.execute();

if (result) {
    this.showPaymentSuccess(result);
}
```

The most "tolerant" mode — perfect for non-critical operations like notifications, where a failure shouldn't poison the rest of the flow.

## Parallel Calls

`timeBackendCall` returns a builder, and `.execute()` returns a regular `Promise`, so you can fan out calls and wait on them with `Promise.all`. Each call gets its own timing, start log, and completion log.

```javascript
async connectedCallback() {
    this.triton = new Triton().bindToComponent('AccountDashboard');
    this.triton.trackComponentLifecycle('connected');

    try {
        const [accountData, relatedRecords, userPreferences] = await Promise.all([
            this.triton.timeBackendCall('getAccountData',
                () => getAccountData({ accountId: this.recordId })).execute(),
            this.triton.timeBackendCall('getRelatedRecords',
                () => getRelatedRecords({ accountId: this.recordId })).execute(),
            this.triton.timeBackendCall('getUserPreferences',
                () => getUserPreferences({})).execute()
        ]);

        this.accountData = accountData;
        this.relatedRecords = relatedRecords;
    } catch (error) {
        console.error('Failed to load dashboard data:', error);
    }
}
```

This pattern is especially powerful for record pages — you instantly get a per-call breakdown of which Apex method is the slow one, instead of staring at a single aggregated load time.

## What Gets Logged

For a successful backend call, you get two log entries:

| Log        | Type           | Summary                                | Notable fields                      |
| ---------- | -------------- | -------------------------------------- | ----------------------------------- |
| Start      | `BACKEND_CALL` | `Backend call started: <methodName>`   | `action = <methodName>`             |
| Completion | `BACKEND_CALL` | `Backend call completed: <methodName>` | `duration`, `action = <methodName>` |

A failure produces the start log plus a `Backend call failed: <methodName>` entry with `duration`, the exception details, and the stack trace (unless you've supplied a custom handler).

## Best Practices

* Use the real Apex method name as `methodName` — searching and grouping logs by method is dramatically easier.
* Keep the arrow function passed to `timeBackendCall` thin. Anything you do *inside* it that isn't the Apex call gets folded into the duration measurement.
* Lean on `withoutRethrow()` for fire-and-forget side effects (analytics pings, optional enrichment) so a flaky non-critical call can't break your component.
* Combine with [User Interactions](https://triton.pharos.ai/1-42/beyond-apex/profiling/user-interactions) when a single user action triggers multiple backend calls — you'll get a parent interaction record plus children for each call.


# User Interactions

Time user-driven flows — form submissions, multi-step actions, and nested backend calls — with timeUserInteraction(...) and the unified PerformanceCallBuilder.

A "backend call" is a single trip to Apex. A "user interaction" is everything that happens between the user clicking a button and seeing the result — which may involve several backend calls, some client-side work, and a final UI update.

`timeUserInteraction(interactionName, fn)` is the umbrella timer for those higher-level flows. It uses the same `PerformanceCallBuilder` as [Backend Calls](https://triton.pharos.ai/1-42/beyond-apex/profiling/backend-calls), so the error-handling story is identical (default, `withoutRethrow`, custom handler, both). The only difference is the log type — interactions land as `TYPE.USER_INTERACTION` and the error context exposes `interactionName` instead of `methodName`.

## Basic Usage

{% code title="formHandler.js" lineNumbers="true" %}

```javascript
import Triton from 'c/triton';
import submitFormData from '@salesforce/apex/FormController.submitFormData';
import validateFormData from '@salesforce/apex/FormController.validateFormData';

export default class FormHandler extends LightningElement {
    triton;
    formData = {};

    connectedCallback() {
        this.triton = new Triton().bindToComponent('FormHandler');
        this.triton.trackComponentLifecycle('connected');
    }

    async handleSubmit() {
        await this.triton.timeUserInteraction('form-submit', async () => {
            const data = this.collectFormData();

            const validation = await this.triton.timeBackendCall(
                'validateFormData',
                () => validateFormData({ data })
            ).execute();

            if (!validation.isValid) {
                throw new Error(`Form validation failed: ${validation.errors.join(', ')}`);
            }

            const result = await this.triton.timeBackendCall(
                'submitFormData',
                () => submitFormData({ data })
            ).execute();

            this.showSuccessMessage(result);
            return result;
        }).execute();
    }
}
```

{% endcode %}

What you get out of this:

* One `User interaction started: form-submit` log when the user clicks.
* Two `Backend call started/completed` pairs for the validate + submit Apex methods.
* One `User interaction completed: form-submit` log at the end, with the *total* duration including both backend calls and any client-side work in between.

That parent-child relationship — interaction with nested backend calls — is the key reason to use `timeUserInteraction` even when "it's just one Apex call". It gives you a single record per user click that aggregates the whole experience.

## Nested Calls With Per-Step Resilience

Real-world flows often want different error policies per step. Here's a payment flow where notification failures don't kill the transaction:

```javascript
async handleComplexUserFlow() {
    await this.triton.timeUserInteraction('payment-flow', async () => {
        const validation = await this.triton.timeBackendCall(
            'validatePaymentInfo',
            () => validatePaymentInfo({ cardToken: this.cardToken })
        ).execute();

        if (!validation.isValid) {
            throw new Error('Invalid payment information');
        }

        const paymentResult = await this.triton.timeBackendCall(
            'processPayment',
            () => processPayment({ amount: this.amount, cardToken: this.cardToken })
        ).execute();

        // Non-critical: log the failure but don't break the flow.
        await this.triton.timeBackendCall(
            'sendNotification',
            () => sendNotification({
                type: 'payment_success',
                userId: this.userId,
                paymentId: paymentResult.id
            })
        )
        .withCustomErrorHandler((error, context) => {
            console.warn(`Notification failed after ${context.duration}ms:`, error);
        })
        .withoutRethrow()
        .execute();

        return paymentResult;
    })
    .withCustomErrorHandler((error, context) => {
        // context.interactionName === 'payment-flow'
        console.error(`Payment flow failed for ${context.interactionName} after ${context.duration}ms:`, error);
        this.showPaymentFlowError(error);
    })
    .withoutRethrow()
    .execute();
}
```

Validation and processing rethrow (so a failure short-circuits the flow), notifications swallow their own errors, and the outer interaction wrap catches everything that escaped — surfacing a single user-facing error and a single top-level failure log.

## Custom Handler Context

Custom error handlers on user interactions receive:

```javascript
{ interactionName: 'form-submit', duration: 1234 }
```

Contrast with backend calls, which use `methodName` instead of `interactionName`. The duration is measured from `timeUserInteraction(...)` to the moment the error was thrown.

## When to Use Interactions vs. Backend Calls

| If the work is...                                                       | Use                                                                                                                           |
| ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| A single Apex round trip                                                | [`timeBackendCall`](https://triton.pharos.ai/1-42/beyond-apex/profiling/backend-calls)                                        |
| A user-triggered flow with one or more Apex calls and client-side logic | `timeUserInteraction` (often wrapping `timeBackendCall` inside)                                                               |
| Purely client-side timing (DOM work, animations, sync work)             | [`startPerformanceMark` / `endPerformanceMark`](https://triton.pharos.ai/1-42/beyond-apex/profiling/custom-marks)             |
| Component mount / unmount / re-render telemetry                         | [`trackComponentLifecycle` / `trackComponentRender`](https://triton.pharos.ai/1-42/beyond-apex/profiling/component-lifecycle) |

## Best Practices

* Use a stable, descriptive `interactionName`. Treat it like an event name (`'checkout-submit'`, `'opportunity-clone'`) — it'll become a primary grouping key in dashboards.
* When nesting, let inner failures rethrow by default. The outer interaction will record the failure and you don't need to duplicate logging at every level.
* Don't reach for `timeUserInteraction` when there's no user. For background or lifecycle work, the more specific helpers below give better signal.


# Component Lifecycle

Track LWC mount/unmount events and render counts with per-instance isolation, Locker Service-safe timing, and zero-effort multi-instance support.

Knowing *when* a component shows up and *how often* it re-renders is half the battle for UI performance. Triton ships two helpers for this — `trackComponentLifecycle` and `trackComponentRender` — and both work transparently across multiple instances of the same component on a single page.

## `trackComponentLifecycle(event)`

Call this in `connectedCallback` and `disconnectedCallback` to log mount and unmount events. The accepted strings are `'connected'` and `'disconnected'`.

```javascript
connectedCallback() {
    this.triton = new Triton().bindToComponent('AccountDashboard');
    this.triton.trackComponentLifecycle('connected');
}

disconnectedCallback() {
    this.triton.trackComponentLifecycle('disconnected');
}
```

Each call produces a `TYPE.COMPONENT_LIFECYCLE` log entry with:

* `summary` = `Component lifecycle: <componentName> - <event>`
* `action` = `lifecycle-connected` or `lifecycle-disconnected`

These records are great for spotting components that mount unexpectedly, churn through DOM updates, or never get torn down properly (a common Aura → LWC migration headache).

## `trackComponentRender()`

Call from `renderedCallback`. Each invocation increments a per-instance counter and emits a `TYPE.COMPONENT_RENDER` log entry.

```javascript
renderedCallback() {
    this.triton.trackComponentRender();
}
```

The log entry includes:

* `summary` = `Component render: <componentName>`
* `details` = `Render count: <n>` — useful for spotting components that re-render an order of magnitude more than expected.

{% hint style="warning" %}
`renderedCallback` fires on every reactive update. If you instrument a noisy component, expect a lot of records. Combine with a sampling strategy (e.g. only log every Nth render) if you need to keep volume in check.
{% endhint %}

## Per-Instance Isolation

When you call `bindToComponent('ProductSearch')`, Triton mints a UUID v4 behind the scenes and stores tracking data under a key like:

```
ProductSearch-550e8400-e29b-41d4-a716-446655440000
```

That means three instances of `<c-product-search>` on the same page produce three independent streams of render counts, lifecycle events, and custom marks — even though the component name is identical.

```javascript
// Instance 1: ProductSearch-550e8400-e29b-41d4-a716-446655440000
// Instance 2: ProductSearch-7b2c5f8d-3e4a-4d5b-8c9f-1a2b3c4d5e6f
// Instance 3: ProductSearch-9a8b7c6d-5e4f-3d2c-1b0a-fedcba987654

export default class ProductSearch extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('ProductSearch');
        this.triton.trackComponentLifecycle('connected');
    }

    renderedCallback() {
        this.triton.trackComponentRender();
    }
}
```

You don't need to manage instance IDs yourself — the proxy returned by `bindToComponent` carries them implicitly. The component name you pass is the *grouping* key (so dashboards can roll up across instances), and the UUID is the *uniqueness* key (so individual instances don't clobber each other's data).

## Initialization Timing

Where to bind depends on whether your component uses `@wire`. Same rule as in [LWC logging](https://triton.pharos.ai/1-42/beyond-apex/lwc#creating-an-lwc-logger):

* **Without `@wire`** — bind and call `trackComponentLifecycle('connected')` inside `connectedCallback`.
* **With `@wire`** — bind in the constructor so the logger exists before wire callbacks fire, but still call `trackComponentLifecycle('connected')` from `connectedCallback` for the mount semantics to be accurate.

```javascript
export default class AccountDashboard extends LightningElement {
    triton;

    constructor() {
        super();
        this.triton = new Triton().bindToComponent('AccountDashboard');
    }

    @wire(getAccountData, { accountId: '$recordId' })
    wiredData({ error, data }) {
        // logger is already bound here
    }

    connectedCallback() {
        this.triton.trackComponentLifecycle('connected');
    }

    renderedCallback() {
        this.triton.trackComponentRender();
    }

    disconnectedCallback() {
        this.triton.trackComponentLifecycle('disconnected');
    }
}
```

## Locker Service-Safe Timing

Lifecycle and render entries timestamp themselves with `Date.now()` directly, and the broader profiling stack uses a `getCurrentTime()` helper that prefers `performance.now()` and silently falls back to `Date.now()` when the Performance API is restricted under Locker Service.

You don't need to special-case Locker Service in your code — every profiling helper in this section is built to degrade gracefully.

## What Happens Without `bindToComponent`

Both lifecycle and render helpers check the binding first. If you call them on an unbound logger:

```javascript
// MISSING bindToComponent
this.triton = new Triton();
this.triton.trackComponentLifecycle('connected'); // no-op, console warning
```

…they emit a console warning (`Triton performance tracking requires bindToComponent() to be called first`) and return. Nothing crashes; you just won't see the records.

## Best Practices

* Pair every `trackComponentLifecycle('connected')` with a `trackComponentLifecycle('disconnected')`. Missing disconnects are the smoking gun for memory-leak-shaped problems.
* Add `trackComponentRender()` early in the rollout to baseline normal render counts — once you have that baseline, regressions stand out instantly.
* Use the component name to your advantage: keep it stable and human-readable (the class name is usually the right call), so logs are easy to group and search.


# Custom Performance Marks

Drop browser-style performance marks anywhere in your LWC code with startPerformanceMark / endPerformanceMark — fully per-instance and Locker Service-safe.

The high-level helpers (`timeBackendCall`, `timeUserInteraction`, `trackComponentLifecycle`, `trackComponentRender`) cover the common cases. When you need to time something that doesn't fit those moulds — a chunk of client-side data shaping, an animation, a debounce window, a delay between async steps — reach for raw performance marks.

The API mirrors the browser's `performance.mark()` pattern:

```javascript
this.triton.startPerformanceMark('product-search');
// ... do work ...
this.triton.endPerformanceMark('product-search');
```

`startPerformanceMark` stores a starting timestamp keyed by mark name and component instance. `endPerformanceMark` computes the duration, emits a `TYPE.PERFORMANCE` log entry, and clears the mark.

## When to Reach for Marks

Marks are the right tool when:

* You're measuring purely client-side work that has no backend round trip — e.g. parsing a CSV, computing a derived data structure, an animation timeline.
* You want to wrap *both sides* of an async boundary that the higher-level helpers don't model — e.g. starting a timer when a debounce fires, stopping it when the next user event arrives.
* You want a single duration record without the auto-generated start/complete pair that `timeBackendCall` produces.

If your work *is* an Apex call or a user-triggered flow, the higher-level helpers are almost always a better fit — they give you start/complete records and standard error handling for free.

## Example: Wrapping a Search Flow

```javascript
async handleSearch() {
    const searchTerm = this.searchInput.value;

    this.triton.startPerformanceMark('product-search');
    try {
        const results = await this.triton.timeBackendCall(
            'searchProducts',
            () => searchProducts({ searchTerm })
        ).execute();

        this.products = results;
    } finally {
        // Always pair the start with an end — even on failure.
        this.triton.endPerformanceMark('product-search');
    }
}
```

This pattern is handy when you want a single "user-perceived search latency" record (the mark) plus the more granular backend call timing inside it. The mark captures the whole stretch — including the time between the backend response and the UI being ready — while the backend call captures just the round trip.

{% hint style="info" %}
You can have multiple marks active at once. Names are independent: `startPerformanceMark('search')` and `startPerformanceMark('hydrate')` coexist happily and end independently.
{% endhint %}

## Per-Instance Isolation

Marks are stored per component instance, just like lifecycle and render counts. Two instances of the same component can each have an active `product-search` mark and neither will interfere with the other.

```javascript
export default class ProductSearch extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('ProductSearch');
        this.triton.trackComponentLifecycle('connected');
    }

    async search() {
        // Each instance's mark is isolated.
        this.triton.startPerformanceMark('search-operation');

        const results = await this.triton.timeBackendCall(
            'searchProducts',
            () => searchProducts({ term: this.searchTerm })
        ).execute();

        this.triton.endPerformanceMark('search-operation');
        this.products = results;
    }
}
```

## What Gets Logged

Each `endPerformanceMark` call emits one log entry:

| Field      | Value                                       |
| ---------- | ------------------------------------------- |
| `type`     | `TYPE.PERFORMANCE`                          |
| `summary`  | `Performance: <componentName> - <markName>` |
| `details`  | `Duration: <ms>ms`                          |
| `duration` | the measured milliseconds                   |
| `action`   | the mark name                               |

No log is produced on `startPerformanceMark` — marks are silent until they're closed. If you call `endPerformanceMark` for a name that was never started, Triton emits a console warning and skips the log.

## Locker Service Compatibility

Mark timing uses the same `getCurrentTime()` helper described in [Component Lifecycle](https://triton.pharos.ai/1-42/beyond-apex/profiling/component-lifecycle#locker-service-safe-timing): `performance.now()` when available, `Date.now()` otherwise. You get sub-millisecond precision where allowed, and you never need a fallback path in your code.

## Best Practices

* **Always pair `startPerformanceMark` with `endPerformanceMark`.** Wrap the end in `finally` so an exception in the middle doesn't leave a dangling mark.
* **Use descriptive, hyphenated names.** They show up directly in dashboards (`action` column).
* **Bind first.** Custom marks require `bindToComponent()` — without it you'll just get a console warning and no log.
* **Don't double up.** If you're already wrapping with `timeBackendCall` or `timeUserInteraction`, you usually don't need a custom mark on top — the helpers already record duration.


# Best Practices & Standards

Comprehensive best practices and standards for implementing Pharos Triton logging across Salesforce Apex, LWC, and Flow with real-world examples and practical guidance.

> **Audience:** Salesforce architects and senior developers\
> **Context:** Brand-new Triton rollout in an org with significant legacy automation & code

This comprehensive guide defines **authoritative, practical standards** for implementing the **Pharos Triton** logging framework across Apex, LWC, and Flow. It blends **Triton-specific** capabilities with **Salesforce engineering best practices**, focuses on **maximizing context and consistency**, and shows realistic code patterns for Batch, Queueable, Triggers, LWC, and Exception logging.

## What You'll Learn

This guide covers everything from fundamental logging principles to advanced implementation strategies:

* **Core Principles**: Understanding the foundational goals and principles of effective logging
* **Log Levels**: When and how to use different log levels appropriately
* **Template Patterns**: Leveraging templates for consistency and maintainability
* **Buffering & Flushing**: Smart strategies for performance and reliability
* **Transaction Management**: Correlating logs across LWC → Apex → Flow boundaries
* **Implementation Patterns**: Real-world examples for different Salesforce contexts
* **Context & Related Objects**: Maximizing the value of your log data
* **Taxonomy & Standards**: Establishing consistent classification systems
* **Exception Handling**: Best practices for error logging and debugging
* **Standards Enforcement**: Code review checklists and CI automation
* **Legacy Migration**: Strategies for rolling out Triton in existing orgs

## The Logging Challenge

Implementing a comprehensive logging framework in a Salesforce org presents unique challenges that go far beyond simply adding debug statements. Organizations often struggle with fragmented logging approaches, inconsistent patterns, and the inability to correlate issues across different technologies and contexts. When problems arise in production, teams find themselves piecing together information from multiple sources—debug logs, error emails, Flow execution details, and user reports—often without the context needed to quickly identify root causes.

The complexity increases exponentially when dealing with modern Salesforce architectures that span multiple technologies. A single user action might trigger an LWC component, which calls an Apex controller, which triggers a Flow, which executes additional Apex code, and potentially makes external API calls. When something goes wrong in this chain, traditional debugging approaches fall short. Teams spend hours or days trying to trace the execution path, often resorting to guesswork or extensive manual investigation. This not only impacts developer productivity but also directly affects business operations, customer experience, and support costs.

Moreover, the lack of standardized logging creates technical debt that compounds over time. Different developers implement logging in different ways, leading to inconsistent data quality, varying levels of detail, and difficulty in establishing meaningful patterns. Without proper structure and taxonomy, logs become noise rather than actionable intelligence. Organizations find themselves with terabytes of log data but little ability to extract meaningful insights or quickly resolve issues.

This guide addresses these fundamental challenges by providing a comprehensive framework that ensures consistency, enables correlation across technology boundaries, and delivers the rich context needed for effective debugging and monitoring. By following these best practices, organizations can transform their logging from a reactive debugging tool into a proactive observability platform that supports both immediate troubleshooting and long-term system optimization.

## Getting Started

We recommend working through these articles in order, as each builds upon the previous concepts:

| Article                                                                                                              | Description                                                                                                                                    |
| -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| [Core Principles](https://triton.pharos.ai/1-42/triton-best-practices/core-principles)                               | Understanding the foundational goals and principles of effective Triton logging implementation across Salesforce technologies.                 |
| [Log Levels: When to Use What](https://triton.pharos.ai/1-42/triton-best-practices/log-levels-and-usage)             | Understanding when and how to use different log levels appropriately in Triton logging for optimal debugging and monitoring.                   |
| [Templates & the Builder Pattern](https://triton.pharos.ai/1-42/triton-best-practices/templates-and-builder-pattern) | Leveraging templates and the builder pattern for consistent, maintainable Triton logging across Apex and LWC.                                  |
| [Buffering & Flushing](https://triton.pharos.ai/1-42/triton-best-practices/buffering-and-flushing)                   | Smart strategies for buffering and flushing logs in Triton for optimal performance and reliability across Apex and LWC.                        |
| [Transaction Management](https://triton.pharos.ai/1-42/triton-best-practices/transaction-management)                 | Correlating logs across LWC → Apex → Flow boundaries using transaction management for end-to-end traceability.                                 |
| [Implementation Patterns](https://triton.pharos.ai/1-42/triton-best-practices/implementation-patterns)               | Real-world implementation patterns for Triton logging across different Salesforce contexts including triggers, batches, queueables, and flows. |
| [Context & Related Objects](https://triton.pharos.ai/1-42/triton-best-practices/context-and-related-objects)         | Maximizing the value of your log data through rich context and related object tracking in Triton logging.                                      |
| [Taxonomy & Standards](https://triton.pharos.ai/1-42/triton-best-practices/taxonomy-and-standards)                   | Establishing consistent classification systems and taxonomy standards for Triton logging across your Salesforce org.                           |
| [Exception Handling](https://triton.pharos.ai/1-42/triton-best-practices/exception-handling)                         | Best practices for error logging and debugging with Triton, including exception handling patterns and debugging strategies.                    |
| [Standards Enforcement](https://triton.pharos.ai/1-42/triton-best-practices/standards-enforcement)                   | Code review checklists and CI automation for enforcing Triton logging standards across your Salesforce org.                                    |
| [Legacy Code Logging Rollout](https://triton.pharos.ai/1-42/triton-best-practices/legacy-migration)                  | Strategies for rolling out Triton logging in existing Salesforce orgs with legacy automation and code.                                         |

## Key Benefits

By following these best practices, your org will achieve:

* **Consistent Logging**: Standardized patterns across all code and automation
* **Rich Context**: Comprehensive debugging information with minimal effort
* **Performance Optimization**: Smart buffering and flushing strategies
* **End-to-End Tracing**: Complete visibility across technology boundaries
* **Maintainable Code**: Template-based approaches that reduce duplication
* **Production Readiness**: Proper error handling and monitoring capabilities


# Core Principles

Understanding the foundational goals and principles of effective Triton logging implementation across Salesforce technologies.

## Goals & Principles

Effective logging with Triton is built on seven core principles that ensure your logs are consistent, useful, and maintainable:

### 1. **Consistency First**

Every log must carry consistent metadata (Category, Type, Area, Level, TransactionId, Operation/Function, Context). This consistency enables powerful filtering, grouping, and analysis across your entire org.

### 2. **Context-Rich**

Prefer builder + template patterns to capture **who/what/where/when/how** (user, related objects, stack/operation, runtime info, duration). Rich context transforms logs from simple messages into powerful debugging tools.

### 3. **Standards-Driven**

Enforce a **Type/Area taxonomy** org-wide. Don't invent ad-hoc strings. Use the established enums and extend them systematically when needed.

### 4. **Right Level, Right Volume**

Use **Level** appropriately; rely on Triton's dynamic filtering (e.g., via metadata) rather than hard-coding if/else conditions. This allows you to tune verbosity by environment without code changes.

### 5. **Safe & Useful**

Never log secrets/PII. Do log correlation identifiers, IDs, and performance signals. Balance security with debugging value.

### 6. **Transaction-Aware**

Start/Resume/Stop transactions across LWC → Apex → Flow boundaries to correlate events end-to-end. This creates complete execution traces across technology boundaries.

### 7. **Buffer Smartly**

Use Triton buffering + auto-flush for performance; flush at boundaries and on errors. This optimizes performance while ensuring critical logs are never lost.

## Why These Principles Matter

These principles work together to create a logging system that:

* **Scales with your org**: Consistent patterns work across teams and technologies
* **Provides actionable insights**: Rich context enables effective debugging and monitoring
* **Maintains performance**: Smart buffering and filtering keep overhead minimal
* **Enables correlation**: Transaction awareness creates end-to-end visibility
* **Supports compliance**: Proper handling of sensitive data and audit requirements

## Implementation Philosophy

The principles guide implementation decisions:

* **Templates over convenience methods**: Templates ensure consistency and reduce drift
* **Context over brevity**: More context is better than less, within reason
* **Standards over flexibility**: Consistent taxonomy enables powerful analysis
* **Performance awareness**: Buffer appropriately and flush strategically
* **Security first**: Never compromise security for debugging convenience

By following these principles, you'll create a logging system that grows with your org and provides lasting value for debugging, monitoring, and compliance.




---

[Next Page](https://triton.pharos.ai/llms-full.txt/1)

