> 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/context-and-related-objects.md).

# Context & Related Objects

## Maximizing Log Value

The most valuable logs contain rich context that enables effective debugging and analysis. Triton provides powerful capabilities for capturing comprehensive context and tracking related objects.

## Related Objects

### Apex – Single Object

```apex
Triton.instance.log(
    Triton.instance.fromTemplate()
        .relatedObject(accountId)  // Single related object
        .summary('Account processed')
        .details('status=completed')
);
```

### Apex – Multiple Objects

```apex
// Order processing with related objects
public class OrderProcessingService {
    public static void processOrder(Id orderId) {
        // Set up template for order processing
        Triton.instance.setTemplate(
            Triton.makeBuilder()
                .category(TritonTypes.Category.Apex)
                .type(TritonTypes.Type.Backend)
                .area(TritonTypes.Area.OrderProcessing)
                .relatedObject(orderId)  // Primary object
        );
        
        try {
            // Get related records
            Order order = [SELECT Id, AccountId, OpportunityId FROM Order WHERE Id = :orderId];
            
            // Process order
            processOrderLogic(order);
            
            // Log success with all related objects
            Triton.instance.log(
                Triton.instance.fromTemplate()
                    .summary('Order processed successfully')
                    .details('orderId=' + orderId)
                    .relatedObjects(new Set<Id>{
                        orderId,           // Order
                        order.AccountId,   // Account
                        order.OpportunityId // Opportunity
                    })
            );
            
        } catch (Exception e) {
            Triton.instance.log(
                Triton.instance.fromTemplate()
                    .exception(e)
                    .summary('Order processing failed')
            );
            throw e;
        }
    }
}
```

### LWC – Related Objects

```js
// LWC component with related object tracking
export default class OrderManager extends LightningElement {
    triton;
    
    connectedCallback() {
        this.triton = new Triton().bindToComponent('c-order-manager');
        
        // Set up template with primary related object
        this.triton.setTemplate(
            this.triton.makeBuilder()
                .type(TYPE.FRONTEND)
                .area(AREA.ORDER_MANAGEMENT)
                .relatedObjects([this.recordId])  // Primary order
        );
    }
    
    async handleOrderUpdate() {
        try {
            const result = await updateOrder({ 
                orderId: this.recordId,
                orderData: this.orderData 
            });
            
            // Log with all related objects
            this.triton.log(
                this.triton.fromTemplate()
                    .summary('Order updated successfully')
                    .details(JSON.stringify({ 
                        orderId: this.recordId,
                        accountId: result.AccountId,
                        opportunityId: result.OpportunityId 
                    }))
                    .relatedObjects([
                        this.recordId,        // Order
                        result.AccountId,     // Account
                        result.OpportunityId  // Opportunity
                    ])
            );
            
        } catch (error) {
            this.triton.logNow(
                this.triton.fromTemplate()
                    .exception(error)
                    .summary('Order update failed')
            );
        }
    }
}
```

## Rich Context Capture

### Duration Tracking

```apex
public class PerformanceTracking {
    public static void processBatch(List<SObject> records) {
        Long startTime = System.now().getTime();
        
        Triton.instance.setTemplate(
            Triton.makeBuilder()
                .category(TritonTypes.Category.Apex)
                .type(TritonTypes.Type.Backend)
                .area(TritonTypes.Area.BatchProcessing)
        );
        
        try {
            // Process records
            for (SObject record : records) {
                processRecord(record);
            }
            
            // Log completion with duration
            Triton.instance.log(
                Triton.instance.fromTemplate()
                    .summary('Batch processing completed')
                    .details('processed=' + records.size())
                    .duration(System.now().getTime() - startTime)
                    .relatedObjects(new Map<Id, SObject>(records).keySet())
            );
            
        } catch (Exception e) {
            Triton.instance.log(
                Triton.instance.fromTemplate()
                    .exception(e)
                    .summary('Batch processing failed')
                    .duration(System.now().getTime() - startTime)
            );
            throw e;
        }
    }
}
```

### Integration Payloads

```apex
public class IntegrationService {
    public static void callExternalAPI(String endpoint, String payload) {
        Long startTime = System.now().getTime();
        
        Triton.instance.setTemplate(
            Triton.makeBuilder()
                .category(TritonTypes.Category.Integration)
                .type(TritonTypes.Type.Backend)
                .area(TritonTypes.Area.ExternalAPI)
        );
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint(endpoint);
        req.setMethod('POST');
        req.setBody(payload);
        
        try {
            HttpResponse response = new Http().send(req);
            
            if (response.getStatusCode() == 200) {
                // Log successful call with payload
                Triton.instance.log(
                    Triton.instance.fromTemplate()
                        .summary('External API call successful')
                        .details('endpoint=' + endpoint + ', statusCode=' + response.getStatusCode())
                        .integrationPayload(req, response)
                        .duration(System.now().getTime() - startTime)
                );
            } else {
                // Log failed call with payload
                Triton.instance.log(
                    Triton.instance.fromTemplate()
                        .summary('External API call failed')
                        .details('endpoint=' + endpoint + ', statusCode=' + response.getStatusCode())
                        .integrationPayload(req, response)
                        .duration(System.now().getTime() - startTime)
                );
            }
            
        } catch (Exception e) {
            // Log exception with request payload
            Triton.instance.log(
                Triton.instance.fromTemplate()
                    .exception(e)
                    .summary('External API call failed')
                    .details('endpoint=' + endpoint)
                    .integrationPayload(req, null)
                    .duration(System.now().getTime() - startTime)
            );
            throw e;
        }
    }
}
```

## Context Enrichment

### User Context

```apex
public class UserContextLogger {
    public static void logUserAction(String action, Id recordId) {
        Triton.instance.log(
            Triton.makeBuilder()
                .category(TritonTypes.Category.Apex)
                .type(TritonTypes.Type.Backend)
                .area(TritonTypes.Area.UserActions)
                .relatedObject(recordId)
                .userId(UserInfo.getUserId())  // Current user
                .summary('User action: ' + action)
                .details('user=' + UserInfo.getName() + ', profile=' + UserInfo.getProfileId())
        );
    }
}
```

### Runtime Information

```js
// LWC with runtime information
export default class PerformanceComponent extends LightningElement {
    triton;
    
    connectedCallback() {
        this.triton = new Triton().bindToComponent('c-performance-component');
        
        // Log component initialization with runtime info
        this.triton.log(
            this.triton.makeBuilder()
                .type(TYPE.FRONTEND)
                .area(AREA.PERFORMANCE)
                .summary('Component initialized')
                .details(JSON.stringify({
                    userAgent: navigator.userAgent,
                    screenSize: `${screen.width}x${screen.height}`,
                    timestamp: new Date().toISOString()
                }))
        );
    }
}
```

## Best Practices

### Related Object Strategy

1. **Primary object**: Always include the main object being processed
2. **Related records**: Include parent/child relationships that are relevant to the operation
3. **Transaction scope**: Include all objects that are part of the same transaction
4. **Error context**: Ensure related objects are included even in error scenarios

### Context Enrichment

1. **Duration tracking**: Measure and log processing time for performance analysis
2. **Integration payloads**: Always include request/response data for external calls
3. **User context**: Include user information for audit trails
4. **Runtime information**: Capture relevant system/environment details

### Performance Considerations

1. **Object limits**: Be mindful of the number of related objects (avoid excessive lists)
2. **Payload size**: Sanitize integration payloads to avoid storage issues
3. **Memory usage**: Consider the impact of rich context on memory consumption
4. **Filtering**: Use context to enable effective log filtering and analysis

## Advanced Patterns

### Dynamic Related Objects

```apex
public class DynamicObjectTracker {
    public static void processWithDynamicObjects(Id primaryId, Set<Id> relatedIds) {
        Set<Id> allObjects = new Set<Id>{ primaryId };
        allObjects.addAll(relatedIds);
        
        Triton.instance.log(
            Triton.instance.fromTemplate()
                .summary('Dynamic object processing')
                .details('primary=' + primaryId + ', related=' + relatedIds.size())
                .relatedObjects(allObjects)
        );
    }
}
```

### Context Templates

```apex
public class ContextTemplate {
    public static void setRichTemplate(Id recordId, String operation) {
        Triton.instance.setTemplate(
            Triton.makeBuilder()
                .category(TritonTypes.Category.Apex)
                .type(TritonTypes.Type.Backend)
                .area(TritonTypes.Area.DataProcessing)
                .relatedObject(recordId)
                .summary(operation)
                .details('timestamp=' + System.now() + ', user=' + UserInfo.getName())
        );
    }
}
```

By maximizing context and related object tracking, you'll create logs that provide comprehensive debugging information and enable powerful analysis capabilities across your Salesforce org.
