Pharos Triton
  • 🔱About Pharos Triton
  • 🏁Installing Pharos Triton
  • Apex Logging Basics
  • Common Apex Usage Patters
    • Batch Logging
    • Integration Logs
    • Apex Rest Logging
    • Full Control with TritonBuilder
  • Beyond Apex
    • LWC
    • 🔄LWC Transaction Management
    • ⚡LWC and Apex
    • 💾Platform Cache for Transactions
    • Flows
    • 〰️LWC, Apex and Flows
  • 📖Methods Reference
    • 📔Apex
      • Triton
      • TritonBuilder
      • TritonTypes
      • TritonLwc
        • ComponentLog
        • Component
        • Error
        • RuntimeInfo
      • TritonFlow
        • FlowLog
      • TritonHelper
        • PostProcessingControlsBuilder
      • LogBuilder
    • LWC
      • Triton
      • TritonBuilder
      • TritonUtils
  • Help and Support
Powered by GitBook
On this page
  • LWC Component
  • LWC Controller
  • Apex Controller
  • The Result
  1. Beyond Apex

LWC and Apex

In this article we'll describe the process for logging in LWC in conjunction with Apex. We will examine how Triton associates two different types of logs together under a single umbrella.

Logging across LWC and Apex can be very helpful in both troubleshooting and profiling. The most common scenario is to track your component's UI logs and link these together with Apex action calls on the back end. This approach will allow you to see all LWC and Apex logs under the same transaction.

We'll assume that the start of our user flow originates from a button click (an LWC action) and then continues on the back end in Apex. Our goal is to link together the two types of logs. Let's begin with the LWC side.

LWC Component

Let's place a button in our component that will start the main execution and logging from a click event.

logDemo.html
<template>
    ....
    
    <lightning-button 
        variant="brand" 
        label="DML Error" 
        title="DML Error" 
        onclick={handleClick} 
        class="slds-m-left_x-small">
    </lightning-button>
    
    ....
</template>

LWC Controller

Now, let's take a look at our LWC controller and create our first log.

logDemo.js
// Our apex action that will perform some logging
import apexActionThatGeneratesDMLError from '@salesforce/apex/LogDemoController.apexActionThatGeneratesDMLError';
// Triton logger component
import Triton, { AREA, TYPE } from 'c/triton';

export default class LogDemo extends LightningElement {
    triton;
    startTime;
    
    connectedCallback() {
        this.triton = new Triton();
    }
    
    handleClick() {
        this.startTime = performance.now();
        this.executeScenario();
    }
    
    async executeScenario() {
        // Log the start of our execution
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('LWC action (from js) - DML Error')
                .details('LWC action (from js) - DML Error - Execution Start')
                .duration(performance.now() - this.startTime)
        );

        try {
            // Invoke our Apex action passing in the transaction Id 
            // for the apex controller to re-use
            await apexActionThatGeneratesDMLError({
                transactionId: this.triton.transactionId
            });
        } catch (error) {
            // Log this exception
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}    

The executeScenario() method above will generate two LWC logs: one debug and one error log (if the Apex action fails). Note that we are passing our generated transaction Id back to the Apex controller to use for back-end logging.

Apex Controller

Next, let's look at our Apex controller. The action that we're calling from LWC is also doing some debug and error logging with the provided transaction Id.

LogDemoController.cls
public with sharing class LogDemoController {

//this method will use our logger to create a new transaction Id
@AuraEnabled
public static String getTransactionId() {
	return Triton.instance.startTransaction();
}

@AuraEnabled
public static void apexActionThatGeneratesDMLError(String transactionId) {
	//letting our logger know to re-use an existing transaction Id
	Triton.instance.resumeTransaction(transactionId);
	Triton.instance.debug(TritonTypes.Type.Backend, /* type */
			TritonTypes.Area.Community, /* functional area */
			'LWC controller (apex) - DML Error', /* summary */
			'LWC controller (apex) - DML Error - Apex Execution Start' /* details */
	);
	
	try {
		ContentVersion contentVersion = new ContentVersion();
		contentVersion.ContentLocation = 'Apex Error';
		contentVersion.Title = 'Apex Error';
		contentVersion.PathOnClient = 'ApexError.pdf';
		//this insert statement will generate a DMLException
		insert contentVersion;
	} catch (Exception e) {
		//let's log this exception
		Triton.instance.error(TritonTypes.Area.Community, e);
	}
}
....

}

Similar to our LWC controller, executing this action will result in a debug and an error log created.

The Result

Altogether, both LWC and Apex executions will generate the following log structure in a single transaction:

  • Parent LWC Debug Log from executeScenario()

    1. Child Apex Debug Log from our apexActionThatGeneratesDMLError() action

    2. Child Apex Error Log from our try/catch block inside the Apex action

    3. Child LWC Error Log from the LWC error handler (if an error occurs)

All logs within the same transaction are automatically linked together using the transaction ID. The transaction management is handled automatically by the Triton framework, including caching and auto-flushing of logs.

While this example demonstrates passing the transaction ID directly through method parameters, there's another powerful approach using Salesforce Platform Cache. This alternative method is particularly useful for complex scenarios involving multiple components or when direct parameter passing isn't practical. We'll explore platform caching in detail in the next article.

PreviousLWC Transaction ManagementNextPlatform Cache for Transactions

Last updated 3 months ago

⚡