> For the complete documentation index, see [llms.txt](https://triton.pharos.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://triton.pharos.ai/methods-reference/lwc/triton.md).

# 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.md) 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.md). 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 %}
