Common Apex Usage Patters
This articles details of some of the more common logging patterns.
Last updated
This articles details of some of the more common logging patterns.
Last updated
Now that you're familiar with the , let's take a look at an example of apex logging. There are a number of ways to do logging ranging, from straightforward to very complex. We'll start with the basics and gradually move on to more advanced patterns and use cases.
In this scenario we'll take a look at a simple code snippet that performs a DML statement. The DML statement is wrapped into a try/catch block, where any potential exceptions can be handled. This scenario can take place anywhere: triggers, LWC Apex controllers, or even custom rest methods.
Let's take a closer look at this snippet. There are a few take aways in the code above:
The use of debug() and error() methods. These simply provide a shorthand for creating log records with different categories, and different log levels. Note that different parameters are provided to debug() and error() methods.
The use of a finally{} construct. This ensures that stopTransaction() is the last method that executes in any event.
Let's now assume that there is an exception raised during the DML operation. This will result in the following log records created:
A parent debug log generated on line (3)
A child debug log generated on line (10)
A child Apex error log generated on line (19)
The use of start/stopTransaction(). This initiates a new transaction context within Pharos and ensures that all subsequent logs are grouped under a single umbrellaβmore specifically, under the first log generated in the sequence. See the log structure .
Note the use of Type and Area values. You can check out the .
An issue record will also automatically get created for this log. Issues, by default, are only created for error logs. Debug and other log categories such as Event or Warning do not generate issues by default. This behavior is customizable in the