Full Control with TritonBuilder

With TritonBuilder, logging is no longer a tedious task but an art form. Embrace the power of structured logging and let TritonBuilder be your guide. Happy logging!

TritonBuilder: Your Logging Sidekick

Welcome to the world of TritonBuilder, the unsung hero of the Pharos Triton logging framework. Imagine a world where logging is not just a chore but a delightful experience. TritonBuilder is here to make that dream a reality, providing a fluent interface that transforms the mundane task of log creation into a seamless and enjoyable process.

Builder Perks: Why You'll Love It

Fluent Interface: The Art of Chaining

TritonBuilder is like a well-trained butler, allowing you to chain method calls effortlessly. Set your log attributes with the grace of a ballroom dancer, avoiding the confusion of tangled code. It's like having a conversation with your code—clear, concise, and to the point.

Customizable Attributes: Your Log, Your Way

Whether you're setting categories, types, areas, or levels, TritonBuilder has you covered. It's like a customizable pizza—choose your toppings (or attributes) and create the perfect log for your needs.

Integration with HTTP and REST: The Diplomat

TritonBuilder handles payloads from HTTP and REST requests/responses with the finesse of a seasoned diplomat. It ensures your integration logs are as smooth as a well-brewed cup of coffee.

Need to associate logs with related Salesforce objects? TritonBuilder is your matchmaker, making connections that matter.

Template Support: The Reusable Genius

Create reusable log templates for consistent logging. It's like having a wardrobe of perfectly tailored suits—always ready for any occasion.

Basic Usage

Creating a Simple Log

To create a basic log entry, instantiate a TritonBuilder and set the desired attributes:

TritonBuilder builder = new TritonBuilder();
builder.category(TritonTypes.Category.Apex)
       .type(TritonTypes.Type.Backend)
       .area(TritonTypes.Area.Community)
       .level(TritonTypes.Level.INFO)
       .summary('Sample Log Entry')
       .details('This is a detailed description of the log entry.')
       .build();

Setting Attributes

The TritonBuilder class provides methods to set various attributes:

  • Category: Represents the high-level classification of the log.

    builder.category(TritonTypes.Category.Apex);
  • Type: Provides a more specific classification.

    builder.type(TritonTypes.Type.Backend);
  • Area: Represents the functional area from a business perspective.

    builder.area(TritonTypes.Area.Community);
  • Level: Defines the severity of the log.

    builder.level(TritonTypes.Level.INFO);
  • Summary and Details: Provide a brief and detailed description of the log.

    builder.summary('Log Summary').details('Detailed log information');

Advanced Usage

Handling HTTP and REST Payloads

TritonBuilder can serialize HTTP and REST request/response objects for integration logs. It's like having a translator for your logs, ensuring nothing gets lost in translation.

HttpRequest request = new HttpRequest();
HttpResponse response = new HttpResponse();
builder.integrationPayload(request, response);

Logs can be associated with related Salesforce objects using their IDs. TritonBuilder is the bridge that connects your logs to the bigger picture that is your data. You can associate one or many ids (or strings that represent Ids).

Id relatedObjectId = Id.valueOf('001xx000003DGb2AAG');
builder.relatedObject(relatedObjectId);

Builder Templates

The setTemplate and fromTemplate methods in Triton.cls allow developers to create reusable log templates. This is particularly useful for scenarios where the same logging structure is used repeatedly, ensuring consistency and reducing code duplication. For example, say you're logging in a large class and want to re-use log category, type and functional area for every log you create. This is a perfect time to use a template.

Using Templates for Repeated Logging

For scenarios where the same logging structure is used repeatedly, TritonBuilder supports the creation of templates. It's like having a template for your favorite email—consistent and reliable.

Triton.instance.setTemplate(Triton.makeBuilder()
                               .category(TritonTypes.Category.Apex)
                               .type(TritonTypes.Type.Backend)
                               .area(TritonTypes.Area.Community)
                               .level(TritonTypes.Level.INFO));

// Use the template for logging
Triton.instance.log(Triton.instance.fromTemplate()
                                 .summary('Template Log')
                                 .details('Details from template log'));

Turn Builder into a Log with the Triton Class

log() Method

The log() method in Triton.cls is designed for immediate logging. It adds a log entry and flushes it to the database right away. It's the quick-draw cowboy of logging, ensuring your log is persisted immediately in critical scenarios.

Usage Example:

Triton.instance.log(Triton.makeBuilder()
                    .category(TritonTypes.Category.Apex)
                    .type(TritonTypes.Type.Backend)
                    .area(TritonTypes.Area.Community)
                    .summary('Immediate Log Entry')
                    .details('This log entry is flushed immediately.'));

addLog() Method

The addLog() method is used for buffered logging. It adds a log entry to the collection but does not immediately flush it to the database. It's the strategist, allowing you to batch multiple log entries and flush them together, optimizing performance.

Usage Example:

Triton.instance.addLog(Triton.makeBuilder()
                    .category(TritonTypes.Category.Apex)
                    .type(TritonTypes.Type.Backend)
                    .area(TritonTypes.Area.Community)
                    .summary('Buffered Log Entry')
                    .details('This log entry is buffered and not immediately flushed.'));

Templates IRL Example

Let's revisit ourLeadsBatchclass from the previous example and update it to utilize the setTemplateandfromTemplatemethods from theTritonclass. We'll create a log template with common parameters and reuse it throughout our batch process.

Updated LeadsBatch Class:

public class LeadsBatch implements Database.Batchable<sObject>, Database.Stateful {
    private String query = '';
    private Log logger = Triton.instance;
    private Integer iteration = 0;
    
    public LeadsBatch(String leadQuery) {
        this.query = leadQuery;
        logger.setTemplate(Triton.makeBuilder()
                            .type(TritonTypes.Type.LeadsBatch)
                            .area(TritonTypes.Area.LeadQualification));

        logger.addLog(logger.fromTemplate()
            .summary('LeadsBatch initialized')
            .details('LeadsBatch initialized with query: ' + query));
    }
    
    public Database.QueryLocator start(Database.BatchableContext bc) {
        logger.addLog(logger.fromTemplate()
            .summary('LeadsBatch starting')
            .details('Fetching query locator for query: ' + query));
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext bc, List<Lead> leads) {
        iteration++;
        logger.addLog(logger.fromTemplate()
            .summary('LeadsBatch executing iteration: ' + iteration)
            .details('Processing ' + leads.size() + ' in this iteration'));
        
        for (Lead l : leads) {
            try {
                LeadProcessingResult result = LeadService.getQualificationScore(l);
                if (result.isSuccess) {
                    l.Score__c = result.qualificationScore;
                } else {
                    logger.addLog(logger.fromTemplate()
                        .summary('LeadsBatch failed to obtain successful qualification score')
                        .details('Result returned for lead id ' + l.Id + Triton.SPACE_SEP + 'Result: ' + String.valueOf(result)));
                }
            } catch (Exception e) {
                logger.addError(TritonTypes.Area.LeadQualification, e);
            }
        }
        
        try {
            update leads;
        } catch (Exception e) {
            logger.addError(TritonTypes.Area.LeadQualification, e);
        }
    }

    public void finish(Database.BatchableContext bc) {
        logger.addLog(logger.fromTemplate()
            .summary('LeadsBatch finishing')
            .details('Iterations processed: ' + iteration));
        logger.flush();
        logger.stopTransaction();
    }
}

Benefits of Using Log Templates

  1. Consistency: By defining a template, you ensure that all log entries share a consistent structure, making it easier to analyze logs and identify patterns.

  2. Efficiency: Templates reduce the amount of code needed to create log entries. You only need to specify the unique details for each log, while the common parameters are automatically applied from the template.

  3. Maintainability: Changes to common log parameters can be made in one place (the template), rather than updating each log entry individually.

  4. Readability: Code becomes cleaner and more readable, as the repetitive parts of log creation are abstracted away.

Summary

  1. To Create a Log Template: Use the Triton.makeBuilder() method to create a log builder with common parameters. Set this builder as a template using logger.setTemplate().

    TritonBuilder logTemplate = Triton.makeBuilder()
        .type(TritonTypes.Type.LeadsBatch)
        .area(TritonTypes.Area.LeadQualification);
    logger.setTemplate(logTemplate);
  2. Use the Template for Logging: When creating a log entry, use logger.fromTemplate() to start with the template and then add specific details for that log entry.

    logger.addLog(logger.fromTemplate()
        .summary('LeadsBatch initialized')
        .details('LeadsBatch initialized with query: ' + query));

By adopting this approach, you can enhance the robustness and clarity of your logging strategy, making it easier to manage and analyze logs from your entire code base.


Last updated