Best practices for monitoring Scheduled Apex and Batch Apex?

We have multiple Apex jobs running, both from Schedulable and Batchable code. While an attentive SA could examine the Apex Jobs list to check that everything is OK, it seems a better idea to have explicit notification of errors (and more detailed error information).

We’ve tried a number of approaches to this in the past, but are now thinking of creating standard Document objects to log into (as that can be done from both Schedulable and Batchable code with no new dependency introduced) that follow a naming pattern and then having one Schedulable that merges these once a day into a single notification email.

But before making this change I’m interested to know if anyone has a better idea they are willing to share?

Answer

I occasionally use something that I got from the Dev 501 class workbook. They have an Error Log custom object where they store error information. I have implemented this in a few different orgs and it works well to alert me of any issues with scheduled and batch classes. I even used in it a few controller classes for high volume VF pages.

Error Log custom object with just one custom field, Trace__c, although you could break it out into different, more specific fields if you like.

So in my apex I create a new Error Log object in my catch statements to records specific error information.

try{
    //Some DML statement
} catch (Exception e) {         
    Error_Log__c log = new Error_Log__c();
    log.trace__c = 'Type: ' + e.getTypeName() + '\n' + 'Cause: ' + e.getCause() + '\n' + 'Message: ' 
    + e.getMessage() + '\n' + 'Line #: ' + e.getLineNumber() + '\n' + e.getStackTraceString() + '\n'
    + 'Some Custom Variable Information From Class: ' + myClassVariable;
    insert log;         
}

I then set up a workflow on the error log object to email me whenever a new error log is created. As you can see you can add different information based on what class you are using it in. Its fairly flexible and pretty simple.

The one drawback would be that you are using a custom object for this and storing the error data, so you might want to monitor this object and periodically delete old error logs. I have a batch class that runs monthly and deletes anything over 30 days old.

The advantage to this method is you only get alerted when there are issues. I have a lot of scheduled classes, so I originally sent an email on the job completion, but with so many classes, some running every night, I didn’t need to get an email just to tell me it worked fine. This will only email me when something goes wrong.

Don’t know if this is exactly what you were looking for, but hopefully this helps.

Attribution
Source : Link , Question Author : Keith C , Answer Author : Chris Duncombe

Leave a Comment