> For the complete documentation index, see [llms.txt](https://triton.pharos.ai/pharos-triton/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/pharos-triton/triton-best-practices/standards-enforcement.md).

# Standards Enforcement

## Code Review Checklist (Peer Review)

### Essential Checks

* [ ] **Template Usage**: All logging uses `setTemplate()` + `fromTemplate()` pattern
* [ ] **Transaction Management**: Proper `startTransaction()`/`resumeTransaction()`/`stopTransaction()` usage
* [ ] **Taxonomy Consistency**: All logs use appropriate Category/Type/Area combinations
* [ ] **Error Handling**: All exceptions are logged with `exception()` method
* [ ] **Context Richness**: Logs include relevant related objects, duration, and business context
* [ ] **Level Appropriateness**: Log levels match the information being logged
* [ ] **Buffering Strategy**: Appropriate use of `addLog()` vs `log()` for performance
* [ ] **Integration Payloads**: External calls include `integrationPayload()` for debugging

### Apex-Specific Checks

* [ ] **No System.debug**: All `System.debug()` statements replaced with Triton logging
* [ ] **Template Setup**: Templates set early in methods with consistent properties
* [ ] **Exception Logging**: All catch blocks include proper exception logging
* [ ] **Transaction Boundaries**: Transactions started/resumed/stopped at appropriate points
* [ ] **Related Objects**: Relevant record IDs included in `relatedObjects()`
* [ ] **Duration Tracking**: Performance-critical operations include duration measurement

### LWC-Specific Checks

* [ ] **Component Binding**: `bindToComponent()` used for all Triton instances
* [ ] **Template Consistency**: Templates set in `connectedCallback()` or constructor
* [ ] **Error Handling**: Wire errors and imperative call errors properly logged
* [ ] **Transaction Correlation**: Transaction IDs passed to Apex methods when needed
* [ ] **Component Lifecycle**: Logs flushed in `disconnectedCallback()` when appropriate
* [ ] **User Context**: Relevant user and component context included in logs

### Flow-Specific Checks

* [ ] **Interview GUID**: `$Flow.InterviewGuid` used in all Flow log actions
* [ ] **Constants Usage**: Log parameters use constants for consistency
* [ ] **Text Templates**: Log details use text templates for formatting
* [ ] **Strategic Placement**: Logs added at critical points (start, decisions, errors)
* [ ] **Error Paths**: Fault connectors include comprehensive logging
* [ ] **Additional Fields**: JSON-formatted additional fields used when needed

## Automated Validation

### Static Code Analysis

```apex
// Example PMD rules for Triton standards
public class TritonStandardsValidator {
    
    // Check for System.debug usage
    public static void validateNoSystemDebug(String code) {
        if (code.contains('System.debug')) {
            throw new ValidationException('System.debug found. Use Triton logging instead.');
        }
    }
    
    // Check for template usage
    public static void validateTemplateUsage(String code) {
        if (code.contains('Triton.makeBuilder()') && !code.contains('setTemplate')) {
            throw new ValidationException('Direct Triton.makeBuilder() usage found. Use templates instead.');
        }
    }
    
    // Check for exception logging
    public static void validateExceptionLogging(String code) {
        if (code.contains('catch (') && !code.contains('.exception(')) {
            throw new ValidationException('Exception caught but not logged with Triton.');
        }
    }
}
```

### CI/CD Integration

```yaml
# Example GitHub Actions workflow
name: Triton Standards Check
on: [push, pull_request]

jobs:
  triton-standards:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Check for System.debug
        run: |
          if grep -r "System.debug" src/; then
            echo "❌ System.debug found. Use Triton logging instead."
            exit 1
          fi
      
      - name: Check for template usage
        run: |
          if grep -r "Triton.makeBuilder()" src/ | grep -v "setTemplate"; then
            echo "❌ Direct Triton.makeBuilder() usage found. Use templates."
            exit 1
          fi
      
      - name: Check for exception handling
        run: |
          if grep -r "catch (" src/ | grep -v ".exception("; then
            echo "❌ Exceptions caught but not logged with Triton."
            exit 1
          fi
```

## Quality Gates

### Pre-Deployment Checks

1. **Static Analysis**: Automated checks for common anti-patterns
2. **Code Coverage**: Ensure logging code is covered by tests
3. **Manual Review**: Peer review for complex logging scenarios
4. **Performance Impact**: Assess logging overhead on critical paths

### Post-Deployment Monitoring

1. **Log Volume**: Monitor log generation rates
2. **Error Rates**: Track logging-related errors
3. **Performance Metrics**: Monitor impact on system performance
4. **User Feedback**: Gather feedback on logging effectiveness

## Training and Documentation

### Developer Training

* **Onboarding**: New developers trained on Triton standards
* **Best Practices**: Regular sessions on logging best practices
* **Code Examples**: Comprehensive examples for common scenarios
* **Troubleshooting**: Training on debugging with logs

### Documentation Standards

* **Style Guide**: Comprehensive logging style guide
* **Examples Repository**: Collection of real-world examples
* **FAQ**: Common questions and answers
* **Troubleshooting Guide**: Common issues and solutions

## Metrics and Monitoring

### Compliance Metrics

* **Template Usage Rate**: Percentage of logs using templates
* **Exception Logging Rate**: Percentage of exceptions properly logged
* **Transaction Correlation Rate**: Percentage of cross-context logs correlated
* **Context Richness**: Average number of related objects per log

### Quality Metrics

* **Log Completeness**: Percentage of logs with all required fields
* **Taxonomy Consistency**: Percentage of logs using standard taxonomy
* **Performance Impact**: Average logging overhead per transaction
* **Debugging Effectiveness**: Time to resolution using logs

## Enforcement Strategies

### Gradual Rollout

1. **Phase 1**: Establish standards and training
2. **Phase 2**: Implement automated checks
3. **Phase 3**: Enforce standards in new code
4. **Phase 4**: Migrate existing code to standards

### Incentives and Recognition

* **Code Quality Awards**: Recognize excellent logging implementations
* **Peer Recognition**: Highlight good examples in team meetings
* **Career Development**: Include logging quality in performance reviews
* **Team Competitions**: Friendly competitions for best logging practices

### Continuous Improvement

* **Regular Reviews**: Periodic assessment of standards effectiveness
* **Feedback Loops**: Gather input from developers and support teams
* **Standard Updates**: Evolve standards based on lessons learned
* **Tool Improvements**: Enhance automated validation tools

## Common Anti-Patterns

### What to Avoid

* ❌ Using `System.debug()` instead of Triton logging
* ❌ Direct `Triton.makeBuilder()` usage without templates
* ❌ Catching exceptions without logging them
* ❌ Missing transaction correlation across contexts
* ❌ Inconsistent taxonomy usage
* ❌ Logging sensitive information (PII, secrets)
* ❌ Excessive logging in tight loops
* ❌ Missing context in error logs

### Correction Examples

```apex
// ❌ Anti-pattern: Direct builder usage
Triton.instance.log(
    Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .type(TritonTypes.Type.Backend)
        .area(TritonTypes.Area.Accounts)
        .summary('Account processed')
);

// ✅ Correct: Template usage
Triton.instance.setTemplate(
    Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .type(TritonTypes.Type.Backend)
        .area(TritonTypes.Area.Accounts)
);

Triton.instance.log(
    Triton.instance.fromTemplate()
        .summary('Account processed')
);
```

By implementing comprehensive standards enforcement, you'll ensure consistent, high-quality logging across your entire Salesforce org, enabling effective debugging and monitoring capabilities.
