> 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/apex-methods-reference/tritonhelper.md).

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

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

**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.md)

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)
