> 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/beyond-apex/lwc.md).

# 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.md#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.md) 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.md) — how logs get grouped and auto-flushed.
* [LWC and Apex](https://triton.pharos.ai/beyond-apex/lwc-and-apex.md) — one transaction spanning a click and its server call.
* [End-to-End Logging](https://triton.pharos.ai/end-to-end.md) — the full LWC → Apex → Flow trace.
