> 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/log-levels-and-usage.md).

# Log Levels: When to Use What

## Understanding Log Levels

Log levels in Triton follow a standard hierarchy from least verbose to most verbose:

| Level                       | Use for                                         | Examples                                                                      | Don'ts                                                          |
| --------------------------- | ----------------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------- |
| **ERROR**                   | Failures impacting user flows or data integrity | Uncaught exceptions, failed DML batches, failed callouts, validation breaches | Don't log benign/expected conditions as ERROR                   |
| **WARNING**                 | Unexpected but recoverable states               | Fallback behavior, degraded external service, approaching governor limits     | Don't spam warnings on every retry unless unique                |
| **INFO**                    | Lifecycle & business milestones                 | "Batch started/finished", "Wire loaded 250 rows", "Converted 12 Leads"        | Don't log every loop iteration as INFO                          |
| **DEBUG/FINE/FINER/FINEST** | Developer diagnostics & verbose traces          | Query shapes, branch decisions, payload snippets                              | Don't enable noisy DEBUG in prod; rely on dynamic level control |

> **Guideline:** Tune logging frequency by environment via metadata / runtime config. In lower environments, allow DEBUG/FINE; in production, default to INFO/WARN/ERROR and elevate temporarily when investigating.

## Real-World Example: E-commerce Order Processing

```apex
// Order processing batch - appropriate level usage
public class OrderProcessingBatch implements Database.Batchable<SObject> {
    public void execute(Database.BatchableContext bc, List<Order> scope) {
        Long startTime = System.now().getTime();
        
        // Set up template for all order processing logs
        Triton.instance.setTemplate(
            Triton.makeBuilder()
                .category(TritonTypes.Category.Apex)
                .type(TritonTypes.Type.Backend)
                .area(TritonTypes.Area.OpportunityManagement)
        );
        
        // INFO: Business milestone
        Triton.instance.log(
            Triton.instance.fromTemplate()
                .level(TritonTypes.Level.INFO)
                .summary('Processing order batch')
                .details('batchSize=' + scope.size())
        );
        
        try {
            for (Order order : scope) {
                // DEBUG: Individual record processing
                Triton.instance.addLog(
                    Triton.instance.fromTemplate()
                        .level(TritonTypes.Level.DEBUG)
                        .summary('Processing order')
                        .details('orderId=' + order.Id + ', status=' + order.Status)
                        .relatedObject(order.Id)
                );
                
                processOrder(order);
            }
            
            // INFO: Success milestone with duration
            Triton.instance.log(
                Triton.instance.fromTemplate()
                    .level(TritonTypes.Level.INFO)
                    .summary('Order batch completed')
                    .details('processed=' + scope.size())
                    .duration(System.now().getTime() - startTime)
            );
            
        } catch (Exception e) {
            // ERROR: Critical failure
            Triton.instance.log(
                Triton.instance.fromTemplate()
                    .exception(e)
                    .relatedObjects(new Map<Id, Order>(scope).keySet())
            );
            throw e;
        }
    }
}
```

## Level-Specific Guidelines

### ERROR Level

Use for critical failures that require immediate attention:

* Unhandled exceptions and system errors
* Integration failures that break business processes
* Data corruption or loss scenarios
* Security violations or authentication failures
* System resource exhaustion (CPU, memory, governor limits)

### WARNING Level

Use for issues that may need attention but aren't critical:

* Deprecated feature usage
* Performance degradation indicators
* Business rule violations that don't break the process
* Retry scenarios and temporary failures
* Approaching governor limits

### INFO Level

Use for important business events and milestones:

* Record creation, updates, and deletions
* Process completion and major workflow steps
* User actions and business transactions
* Integration success and data synchronization
* Scheduled job execution and completion

### DEBUG Level

Use for detailed debugging information:

* Method entry and exit points
* Variable values and state changes
* Decision points in business logic
* Query results and data transformations
* Performance timing information

### FINE/FINER/FINEST Levels

Use for progressively more detailed debugging:

* **FINE**: Loop iterations, conditional branches, minor state transitions
* **FINER**: Individual record processing, detailed stack analysis
* **FINEST**: Character-level operations, memory details, micro-optimizations

## Environment-Specific Recommendations

### Development Environment

* **Default Level**: DEBUG or FINE
* **Purpose**: Comprehensive debugging and development support
* **Considerations**: Higher verbosity helps with development and testing

### Staging Environment

* **Default Level**: INFO
* **Purpose**: Simulate production behavior while maintaining debugging capability
* **Considerations**: Balance between debugging needs and production-like performance

### Production Environment

* **Default Level**: INFO or WARNING
* **Purpose**: Focus on business events and actual problems
* **Considerations**: Minimize performance impact while maintaining visibility

### Troubleshooting Mode

* **Temporary Level**: DEBUG or FINE
* **Purpose**: Detailed investigation of specific issues
* **Considerations**: Use metadata to elevate levels for specific areas temporarily

## Performance Considerations

* Higher log levels (FINE, FINER, FINEST) can impact performance
* String concatenation and object serialization in logs should be minimized
* Consider using conditional logging for expensive operations
* Monitor log volume and adjust levels based on system performance

## Best Practices Summary

1. **Start Conservative**: Begin with INFO level in production and adjust based on monitoring needs
2. **Use Specific Rules**: Create targeted log level rules for different functional areas
3. **Monitor Volume**: Keep an eye on log volume and adjust levels accordingly
4. **Error Logging**: Always log errors at the ERROR level - these should never be filtered out
5. **Environment Tuning**: Use different configurations for development and production environments

By understanding and properly configuring log levels, you can maintain comprehensive visibility into your application's behavior while keeping log volumes manageable and focused on the information that matters most for your specific use case.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://triton.pharos.ai/pharos-triton/triton-best-practices/log-levels-and-usage.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
