How to log status of a completed Batch Job Status

While we are processing bulk records in a batch Apex, we may need to know the status or want to keep log of completed batch.
For example – one batch job is scheduled at night 4.00 AM, and every day we need to track whether current job status, whether It was success or failure.

One way is to check the log at SetUp | Administration Setup | Monitoring | Apex jobs.

But we can get same thing in Apex , within Finish method of batch class. and then we can log the same in a Custom Object or we can send it via Email to Admin user or any other user.

please find the below sample code , which send status via Email


global void finish(Database.BatchableContext BC){
   // Get the ID of the AsyncApexJob representing this batch job
   // from Database.BatchableContext.
   // Query the AsyncApexJob object to retrieve the current job's information.
   AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
      TotalJobItems, CreatedBy.Email,ExtendedStatus,JobType,ApexClassId,MethodName,
      FROM AsyncApexJob WHERE Id =
      :BC.getJobId()];
   // Send an email to the Apex job's submitter notifying of job completion.
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   String[] toAddresses = new String[] {a.CreatedBy.Email};
   mail.setToAddresses(toAddresses);
   mail.setSubject('Batch Class Status ' + a.Status);
   mail.setPlainTextBody
   ('The batch Apex job processed ' + a.TotalJobItems +
   ' batches with '+ a.NumberOfErrors + ' failures.'+
   '\n' + ' Apex Class:' + a.ApexClassId);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); }

Leave a comment