> 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/triton-best-practices/legacy-migration.md).

# 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.md). 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.md) 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.md)).
* **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.md).
* The CI guardrails that keep legacy regressions from creeping back: [Standards Enforcement](https://triton.pharos.ai/triton-best-practices/standards-enforcement.md).
