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

# Pharos Triton Instrumentation

Discover the Pharos Triton logger and how to add custom instrumentation to your Salesforce applications.

Pharos Triton is an open-source logging framework that enables custom instrumentation across Apex, Lightning Web Components (LWC), and Flows. While Pharos automatically captures unhandled exceptions through passive monitoring, Triton empowers developers to actively log custom events, creating comprehensive visibility into application behavior, performance characteristics, and business process flows.

## What is Triton?

Triton serves as the programmable counterpart to Pharos's automated error collection. Where automated collection passively waits for failures to occur, Triton allows developers to deliberately instrument code paths—logging successful operations, tracking performance metrics, capturing business milestones, and creating transaction traces that span multiple execution contexts. This proactive approach transforms observability from reactive ("what broke?") to comprehensive ("what happened?").

The framework provides consistent logging APIs across Salesforce's major development platforms. Apex classes and triggers can use Triton's native Apex API, Lightning Web Components leverage a JavaScript library for client-side logging, and Flows utilize custom actions to log from declarative automation. This multi-platform support ensures teams can instrument their entire application stack using a unified logging approach, with all logs flowing into the same Pharos system for centralized visibility.

{% hint style="info" %}
**Open Source Advantage:** Unlike proprietary logging frameworks, Triton's source code is fully accessible within your Salesforce org. Teams can modify Triton to meet specific organizational requirements, extend functionality, or integrate with custom systems—all without vendor dependencies or licensing constraints.
{% endhint %}

## Why Custom Instrumentation Matters

Automated error collection operates by waiting for unhandled exceptions—failures that breach the application's normal error handling and bubble up to Salesforce's exception infrastructure. This approach is powerful for baseline monitoring but inherently limited. It cannot capture errors that developers intentionally handle within try-catch blocks, cannot log successful operations or business milestones, provides no visibility into performance characteristics before failures occur, and cannot trace multi-step processes across execution boundaries.

Custom instrumentation fills these gaps by giving developers explicit control over what gets logged and when. Performance monitoring becomes possible when you can log execution times and identify slow operations before they timeout. User experience analytics emerge when you track which LWC components users interact with most frequently and where they encounter friction. Business process visibility improves dramatically when you log each step of complex workflows—order processing, approval chains, multi-system integrations—creating a narrative of what happened rather than just recording what failed.

Perhaps most critically, custom instrumentation makes handled exceptions visible. In production systems, defensive programming often requires catching exceptions to prevent full transaction rollbacks or provide graceful degradation. When your code wraps risky operations in try-catch blocks, those failures become invisible to automated monitoring—leading to silent degradation where errors occur but go undetected. Triton ensures these handled exceptions appear in your observability system, preventing silent failures from accumulating into systemic problems.

{% hint style="warning" %}
**Critical Gap: Try-Catch Blocks Create Blind Spots**

When Apex code uses `try { } catch { }` without logging, those errors are completely invisible to Pharos automated error collection. Many integration implementations catch all exceptions to maintain transaction integrity—meaning integration failures could occur thousands of times without detection. Triton instrumentation is not optional for these code paths; it's the only way to achieve visibility.
{% endhint %}

## Core Capabilities

### Multi-Platform Support

Modern Salesforce applications rarely exist within a single technology stack. A typical business process might begin with a Lightning Web Component handling user interaction, trigger an Apex controller for server-side processing, invoke a Flow for orchestration, and call external systems via API. Triton provides consistent logging APIs across all these platforms, allowing teams to instrument end-to-end processes using a unified framework.

The Apex API supports logging from classes, triggers, batch jobs, queueables, schedulables, and any other Apex context. The LWC JavaScript library enables client-side logging, capturing user interactions, component lifecycle events, and frontend errors. Flow actions allow declarative developers to add logging without writing code, bringing observability to the growing population of admin-configured automation. All three platforms publish logs through the same infrastructure, appearing together in Pharos with unified search, filtering, and analysis capabilities.

### Transaction Management

Transaction tracing is Triton's most powerful capability, solving one of the hardest problems in distributed systems observability: understanding causality across execution boundaries. In Salesforce, a single business operation rarely completes within one execution context—it typically fragments across synchronous triggers, asynchronous queueables, flow orchestrations, and external API calls, each technically a separate "transaction" from Salesforce's perspective but conceptually part of a single logical operation.

Traditional logging approaches treat each execution context independently, creating disconnected log entries with no obvious relationship. When troubleshooting a complex failure, developers must manually correlate timestamps, user IDs, and record IDs to reconstruct what happened—a time-consuming and error-prone process. Triton solves this through logical transaction IDs: globally unique identifiers (GUIDs) that link all log entries belonging to the same business operation, regardless of execution context.

**How Transaction Tracing Works:**

At the beginning of a business process—typically when a user action initiates the workflow—a transaction ID is generated (a standard GUID). This ID is then explicitly passed through every execution context: from LWC to Apex via method parameters, from Apex trigger to queueable via custom fields or platform events, from queueable to Flow via flow variables, and even to external systems via API headers or payload fields. Each execution context "resumes" the transaction using Triton's API, causing all subsequent logs to be tagged with that transaction ID.

The result is end-to-end visibility: a single transaction view in Pharos showing all log entries chronologically, even though they span multiple Salesforce transactions, different execution contexts, asynchronous boundaries, and even external systems. When a failure occurs anywhere in this chain, developers can instantly see the complete history leading up to the error.

{% hint style="success" %}
**Game Changer for Complex Systems:** Transaction tracing transforms debugging from "hunting for related log entries" to "viewing the complete process timeline." What might take hours of manual correlation—searching logs, matching timestamps, validating record IDs—becomes a single click to view the transaction trace.
{% endhint %}

### Granular Log Levels

Log verbosity is rarely a one-size-fits-all decision. During active development, developers want maximum detail—every variable value, every conditional branch, every iteration of a loop. In production, this level of verbosity creates overwhelming log volumes and performance overhead. Triton addresses this through hierarchical log levels that control verbosity dynamically, configured through log-level rules (custom metadata) rather than code changes.

The log level hierarchy ranges from `ERROR` (only critical failures) through `WARNING` (potential issues), `INFO` (significant milestones), `DEBUG` (detailed execution flow), and into progressively more verbose levels (`FINE`, `FINER`, `FINEST`) for deep troubleshooting. Each log statement in code is tagged with an appropriate level—`Triton.error(...)`, `Triton.info(...)`, `Triton.debug(...)`. When log-level rules match a log, the most specific one decides, and Triton drops anything more verbose than its level; with no rules, every log is saved.

| Log Level | Purpose                                | Production Use            | Investigation Use    |
| --------- | -------------------------------------- | ------------------------- | -------------------- |
| `ERROR`   | Handled exceptions, critical failures  | ✓ Always                  | ✓ Always             |
| `WARNING` | Potential issues, degraded performance | ✓ Always                  | ✓ Always             |
| `INFO`    | Key milestones, business events        | ✓ Recommended             | ✓ Always             |
| `DEBUG`   | Detailed execution flow                | ✗ Too verbose             | ✓ Primary level      |
| `FINE`    | Verbose debugging                      | ✗ Only for critical paths | ✓ Deep investigation |
| `FINER`   | Very detailed tracing                  | ✗ Never                   | △ Rare cases only    |
| `FINEST`  | Extreme detail                         | ✗ Never                   | △ Extreme debugging  |

The operational power of this system comes from its configuration mechanism: log levels are set with log-level rules—custom metadata you edit on **Pharos Admin → Advanced → Triton → Configuration → Log Levels**—not code. Triton 2.0 ships with no rules, so every log is saved until you add one. A production org can add a rule at `INFO` for baseline operations, then temporarily lower specific classes to `DEBUG` when investigating a reported issue—no code deployment required. Once the investigation completes, the level goes back to `INFO`, eliminating verbose logging overhead without touching the codebase. See [Log Levels](https://triton.pharos.ai/core-concepts/log-levels) in the Triton docs for how rules are matched.

{% hint style="info" %}
**Zero-Deployment Troubleshooting:** Custom metadata configuration means you can increase logging verbosity in production, investigate an issue, and reduce verbosity back—all within minutes and without requiring a deployment window. This is transformative for production troubleshooting where code deployments require change approval processes.
{% endhint %}

### Templates for Consistency

A template is a log builder you configure once in code, at the start of the Apex transaction, with `Triton.setTemplate(...)`. Every log then starts from `Triton.t`, a fresh copy of the template: the shared fields come along automatically, while per-log fields such as the summary never leak from one log into the next.

```mermaid
graph TD
    A[Template: Opportunity Sync]
    A --> B[Category: Apex - builder default]
    A --> C[Area: OpportunityManagement]
    A --> D[Type: Backend]
    A --> E[Related object: the Opportunity being synced]
```

*Usage: every log in the opportunity-sync code starts from this template*

Benefits:

* Standardized logging across team
* Easier searching and filtering
* Consistent alerting behavior
* Reduced code duplication

See [The Builder & Templates](https://triton.pharos.ai/core-concepts/builder-and-templates) in the Triton docs.

### Buffering for Efficiency

Triton accumulates log entries in a buffer and publishes them together:

**Without Buffering:**

```
10 log statements = 10 platform event publishes
→ Consumes 10 from daily allocation (250,000 limit)
```

**With Buffering:**

```
10 log statements → buffered → 1 platform event publish
→ Consumes 1 from daily allocation
```

{% hint style="info" %}
**Note:** Buffering is the default. Triton's level methods (`Triton.info(...)`, `Triton.error(...)` and the rest) add each log to an in-memory buffer, and `Triton.flush()` publishes everything buffered. Flush at natural boundaries—the end of a trigger handler, the end of a batch execute, a `finally` block. For a log you can't afford to lose, `Triton.logNow(...)` publishes it immediately. See [Buffering, Flushing & Deferred Publishing](https://triton.pharos.ai/core-concepts/buffering-flushing).
{% endhint %}

## When to Use Triton

Triton instrumentation requires deliberate effort—developers must add logging calls to code, decide which log levels to keep, and manage the resulting log volume. This investment is worthwhile when the observability gains justify the implementation cost, but counterproductive when applied indiscriminately. Understanding where Triton provides maximum value versus where it creates unnecessary overhead is critical for effective adoption.

### High-Value Scenarios

**Complex Integrations** represent Triton's sweet spot. When your Salesforce org communicates with external systems—ERPs, payment processors, shipping providers, marketing platforms—failures can occur at multiple points: authentication, data transformation, network transmission, external system processing, or response parsing. Triton instrumentation at each step creates a detailed narrative of what happened, making it possible to diagnose whether failures stem from Salesforce code, network issues, or external system problems.

**Mission-Critical Processes** that directly impact revenue or compliance warrant comprehensive instrumentation. Order-to-cash workflows where failures mean lost sales, financial calculations where errors could cause regulatory violations, or compliance-driven operations where audit trails are mandatory—these scenarios justify the overhead of detailed logging. The cost of a single undetected failure typically exceeds the cost of instrumenting the entire process.

**Performance-Sensitive Code** benefits from Triton's ability to track governor limit consumption and execution timing. Batch jobs processing millions of records, CPU-intensive algorithms performing complex calculations, or operations approaching governor limits can be instrumented to capture performance metrics. This enables teams to identify optimization opportunities before performance problems escalate into timeout errors.

**User Experience Tracking** becomes possible when LWC components log interactions. Understanding which features users interact with most, where they encounter errors, and how they recover from failures provides invaluable product intelligence. This goes beyond error monitoring to enable data-driven UI/UX decisions.

### Low-Value Scenarios

Conversely, some scenarios waste effort without providing meaningful observability gains. **Simple CRUD operations**—standard object saves, basic field updates, straightforward queries—already have adequate error visibility through automated error collection. Adding Triton logging to these operations creates log noise without additional value.

**High-volume, low-value events** should be avoided. Logging every iteration of a batch job processing 10 million records creates 10 million log entries that provide minimal incremental information beyond "the batch is still running." Similarly, logging trivial variable assignments or overly verbose debugging creates storage overhead and performance impact that outweighs any observability benefit.

**Sensitive data** should never be logged without explicit data masking. Passwords, API keys, authentication tokens, personally identifiable information (PII), and financial account numbers must either be excluded from logging entirely or pass through data masking rules before being persisted. Many compliance violations stem from sensitive data inadvertently captured in log files.

{% hint style="warning" %}
**Anti-Pattern: "Log Everything"**

New Triton users sometimes adopt a "log everything" mentality, instrumenting every method with verbose DEBUG statements. This creates several problems: overwhelming log volumes that obscure meaningful signals, performance overhead from constructing and publishing excessive log entries, and storage consumption that triggers retention issues. Instrument strategically, not comprehensively.
{% endhint %}

## Integration with Pharos Platform

Logs created via Triton instrumentation:

1. Published as platform events (asynchronous, reliable)
2. Consumed by Pharos background processing
3. Enriched with contextual metadata (user, record, environment)
4. Categorized and fingerprinted (optional)
5. Displayed in Pharos Log Viewer with full search capabilities
6. Linked to Issues (if error patterns emerge)
7. Available for alerting and ticketing rules

{% hint style="success" %}
**Triton + Automated Errors = Complete Visibility**

Pharos automated error collection provides baseline monitoring with zero effort. Triton custom instrumentation fills the gaps for scenarios requiring explicit logging. Together, they provide comprehensive observability.
{% endhint %}

## Getting Started with Triton

Triton is a separate, open-source unlocked package—**Pharos Triton**—that you install on top of Pharos; installing Pharos alone does not add it. Triton 2.0 requires Pharos 2.284.5 or later. See [Installing Pharos Triton](https://triton.pharos.ai/installing-pharos-triton). Triton doesn't automatically instrument code; developers must explicitly add logging calls to the code paths they want to monitor. This deliberate approach ensures teams control exactly what gets logged and can optimize for their specific observability needs.

Log-level filtering is optional. Out of the box, Triton 2.0 has no log-level rules and saves every log. Once you understand your log volume, add rules on the **Log Levels** tab (Pharos Admin → Advanced → Triton → Configuration)—many organizations keep INFO and above in production and DEBUG in sandboxes.

Next comes selective instrumentation—adding Triton logging calls to high-value code paths rather than attempting comprehensive coverage from day one. Focus on the 2-3 most critical business processes: complex integrations, error-prone workflows, or performance-sensitive operations. Instrument these thoroughly, validate that logs appear correctly in Pharos, and measure the impact on platform event consumption and storage. Triton's [instrumentation skills](https://triton.pharos.ai/instrumentation-skills)—agent playbooks for Apex, LWC, and Flows—can do this first pass for you.

Once initial instrumentation proves valuable, gradually expand coverage based on data-driven prioritization. Review Pharos's Issue Tracker to identify which errors occur most frequently, and instrument those code paths for better visibility. Add logging to areas where troubleshooting is currently difficult or time-consuming. Avoid the temptation to instrument everything—strategic coverage of high-impact areas provides most of the value with fraction of the effort.

{% hint style="info" %}
**Comprehensive Triton Documentation Available**

Triton has its own documentation site at [triton.pharos.ai](https://triton.pharos.ai), covering API references for Apex, LWC, and Flow logging, code examples and implementation patterns, performance tuning, and transaction tracing. This page covers when and why to use Triton; that site covers exactly how. For the Triton admin page inside Pharos — platform event configuration, the X-Ray Machine, and manual Flow logging — see [Triton](https://docs.pharos.ai/configuration-guide/advanced/triton.md).
{% endhint %}

## Best Practices for Triton Adoption

### Adopt Incrementally, Not Comprehensively

The most common mistake in Triton adoption is attempting comprehensive instrumentation from day one—adding logging to every Apex class, every LWC component, and every Flow in the org. This creates several problems: overwhelming implementation effort that delays time-to-value, excessive log volumes that create storage and performance issues, and log noise that obscures meaningful signals in a sea of trivial events.

Instead, adopt incrementally through deliberate phases. **Phase 1** focuses exclusively on critical paths—the 2-3 most business-critical processes in your org. For each process, instrument key decision points, error handlers, and external system interactions. Validate that logging overhead is acceptable and logs provide genuine troubleshooting value before expanding further.

**Phase 2** expands coverage to secondary high-value areas: integration callouts, batch jobs processing significant data volumes, and user-facing LWC components where errors impact customer experience. Enable transaction tracing for complex workflows spanning multiple execution contexts. Monitor log volume and adjust retention policies as necessary.

**Phase 3** is optimization—reducing or removing logging for events that proved low-value, flushing buffered logs at sensible boundaries to reduce platform event consumption, and tuning log levels per environment (less verbose in production, more verbose in development sandboxes). This continuous refinement ensures instrumentation provides maximum value with minimum overhead.

### Balance Visibility Against Resource Consumption

Logging is not free—it consumes measurable resources that must be managed. Constructing log messages consumes CPU time and heap memory, publishing logs draws on your org's daily platform event allocation (which varies by Salesforce edition and licensing), and persisted log records consume data storage. While Triton is efficient, high-volume logging can create resource constraints if not managed thoughtfully.

The key guideline: log enough to troubleshoot effectively, but not so much that logging itself creates performance or cost problems. This means being selective about what gets logged (decision points and error conditions, not every variable assignment), using appropriate log levels (INFO in production for most code, DEBUG only for investigation), and flushing buffered logs at sensible boundaries so multiple log statements are batched into fewer platform events.

{% hint style="info" %}
**Monitor Your Logging Overhead:** Pharos provides dashboards showing platform event consumption, log volume trends, and storage utilization. Review these regularly to ensure logging overhead remains within acceptable bounds. If platform events approach daily limits or storage grows unsustainably, reduce log levels or implement more aggressive retention policies before disabling valuable instrumentation.
{% endhint %}

### Write Meaningful, Contextual Log Messages

Log message quality directly impacts troubleshooting effectiveness. Vague messages like `'Error'` provide no actionable information—which error? in which context? affecting which records? Conversely, well-constructed messages contain enough context to understand the situation without accessing additional systems or data.

**Poor log messages:**

* `'Error'` — No context whatsoever
* `'Exception: ' + e.getMessage()` — What operation failed?
* `'Processing complete'` — What was processed? How many records?

**Effective log messages:**

* `'OrderProcessor: Failed to calculate tax for Order ' + orderId + '. Tax service returned HTTP 503. Will retry in 30 seconds.'` — Clear context, error details, and next action
* `'BatchInvoiceProcessor: Processed 2,847 invoices in 42 seconds. 12 skipped due to missing payment terms.'` — Quantified outcomes and exceptions
* `'AccountTrigger: Account ' + accountId + ' changed owner from ' + oldOwnerId + ' to ' + newOwnerId + ' by user ' + UserInfo.getUserId()` — Complete audit trail

The extra effort in constructing descriptive log messages pays dividends during troubleshooting—often making it possible to diagnose issues from log messages alone without reproducing errors or accessing debug logs.

### Always Use Transaction IDs for Multi-Context Processes

Transaction tracing is Triton's most powerful feature, but it only works if you propagate transaction IDs through your entire process flow. For any business operation spanning multiple execution contexts—LWC to Apex to queueable to Flow to external API—generate a transaction ID at the start and explicitly pass it through every boundary. This transforms disconnected log entries into coherent transaction narratives that show exactly what happened end-to-end.

Many organizations initially overlook transaction IDs, only adding them later when troubleshooting complex failures proves difficult. By building transaction tracing into code from the beginning—making it a standard practice rather than an afterthought—you ensure that comprehensive process visibility is available when problems inevitably occur.

## Example Use Case: Order Processing

A real-world example of Triton instrumentation:

**Scenario:** E-commerce order processing with multiple steps

**Without Triton:**

```
Problem: Orders sometimes fail to sync to ERP
Challenge: No visibility into which step failed
Impact: Manual investigation of each failed order (hours of work)
```

**With Triton:**

```
Step 1: LWC logs "Order created" with Transaction ID
Step 2: Apex trigger logs "Validation passed" 
Step 3: Queueable logs "Inventory check: 15 units available"
Step 4: Queueable logs "ERROR: ERP callout timeout after 10s"
Step 5: Flow logs "Order marked as Pending Manual Review"

Outcome: Complete trace shows exact failure point
Resolution time: 5 minutes instead of 2 hours
```

## Summary

Pharos Triton extends observability beyond automated error collection, providing developers with explicit control over what gets logged, when, and at what detail level. Its multi-platform support (Apex, LWC, Flows), transaction tracing capabilities, and flexible log level configuration make it the natural complement to Pharos's passive automated monitoring.

The key to successful Triton adoption is strategic, incremental implementation focused on high-value scenarios: complex integrations, mission-critical processes, performance-sensitive code, and user experience tracking. By avoiding comprehensive "log everything" approaches and instead instrumenting selectively based on business impact, teams achieve comprehensive visibility without overwhelming resource consumption or log noise.

When combined with Pharos automated error collection—which provides zero-effort baseline monitoring—Triton creates a complete observability solution. Automated collection catches unhandled exceptions across the entire org, while Triton fills gaps with targeted instrumentation of handled exceptions, business milestones, and transaction traces. Together, they transform Salesforce from an opaque black box into a fully observable system.

{% hint style="info" %}
**Next Steps:** For detailed API documentation, implementation patterns, code examples, and step-by-step instrumentation guides, refer to the dedicated Triton documentation site at [triton.pharos.ai](https://triton.pharos.ai). It is public—no sign-in needed.
{% endhint %}
