Delete Debug Log In Salesforce Programmatically

Requirement

To delete debug logs programmatically in Salesforce, you can use the Salesforce Tooling API as simple Apex DML is not supported on this. Specifically, the ApexLog object represents the debug logs, and you can delete them by querying this object and then using the API to delete the logs.

Apex Code

<code>
//DeleteDebugLogUsingTooling.deleteDebugLogs();
public class DeleteDebugLogUsingTooling {
    private static final String TOOLING_API_ENDPOINT = '/services/data/v58.0/tooling/query/?q=SELECT+Id+FROM+ApexLog';
      
    public static void deleteDebugLogs() {
        
        for (ApexLog logRecord : [SELECT Id FROM ApexLog LIMIT 50]) {
            
            deleteDebugLog(logRecord.Id);
        }
    }
    
    public static void deleteDebugLog(String logId) {
        HttpRequest req = new HttpRequest();
        Http http = new Http();
        
        // Get the session ID
        String sessionId = UserInfo.getSessionId();
        
        // Set up the request for deletion
        req.setEndpoint(Url.getOrgDomainURL() + '/services/data/v58.0/tooling/sobjects/ApexLog/' + logId);
        req.setMethod('DELETE');
        req.setHeader('Authorization', 'Bearer ' + sessionId);
        req.setHeader('Content-Type', 'application/json');
        
        // Send the delete request
        HttpResponse res = http.send(req);
        
        if (res.getStatusCode() == 204) {
            System.debug('Deleted debug log with Id: ' + logId);
        } else {
            System.debug('Failed to delete debug log. Status: ' + res.getStatusCode() + ', Log Id: ' + logId);
        }
    }
}
</code>