Templates & the Builder Pattern

Leveraging templates and the builder pattern for consistent, maintainable Triton logging across Apex and LWC.

Why Templates Matter

  • Always prefer TritonBuilder + template cloning over convenience helpers.

  • Why: Templates standardize category, type, area, base details, and reduce copy/paste drift.

Apex – Set & Reuse a Template

// Early in the transaction (e.g., controller entry, batch start)
Triton.instance.setTemplate(
    Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .level(TritonTypes.Level.DEBUG)
        .type(TritonTypes.Type.Backend)
        .area(TritonTypes.Area.OpportunityManagement) // agreed taxonomy
);

// Later: clone and specialize
Triton.instance.log(
    Triton.instance.fromTemplate()
        .level(TritonTypes.Level.INFO)
        .summary('Opportunity sync started')
        .details('seed=nightly, source=ERP')
);

LWC – Component-Scoped Template

Real-World Example: Customer Service Portal

Template Benefits

Consistency

  • All logs in a method/component share the same base properties

  • Reduces the risk of inconsistent categorization

  • Ensures proper context across all log entries

Maintainability

  • Changes to common properties only need to be made in one place

  • Reduces code duplication and drift

  • Makes updates and refactoring easier

Reduced Errors

  • No risk of forgetting to set important properties

  • Template ensures all required fields are populated

  • Consistent structure across all logging calls

Performance

  • Template cloning is efficient

  • Reduces object creation overhead

  • Maintains singleton pattern benefits

Template Override Pattern

Show how to override template properties when needed:

Best Practices

Do's

  • βœ… Clone from fromTemplate() to get a pre-filled builder and add specifics

  • βœ… Set templates early in methods/components

  • βœ… Use templates for all logging calls within a scope

  • βœ… Override only what's specific to each log entry

Don'ts

  • ❌ Call addEvent/addDebug directly in new code

  • ❌ Use makeBuilder() for every log entry

  • ❌ Forget to set templates in new methods

  • ❌ Override template properties unnecessarily

Template Scoping

Method-Level Templates

Component-Level Templates

Advanced Template Patterns

Conditional Template Properties

Template Inheritance

By mastering the template pattern, you'll create logging code that is consistent, maintainable, and efficient while providing rich context for all your log entries.

Last updated