Loggly.com Logging with Salesforce.com Apex

If you want to send log messages to Loggly.com you will need to implement their HTTP API interface. All that is required to send data to this interface is an HTTP POST to a url containing your API token with the log message in the body. Tags can be applied either in the URL after your token or using theĀ X-LOGGLY-TAG. Setting the Content-Type header is also required with value of text/plain.

Worth noting that you should keep your Apex Limits in mind in regards to number of callouts and possibly implement a different scheme depending on your volume. Don’t forget to add “https://logs-01.loggly.com” to your Salesforce.com>Setup>Security Controls>Remote Site Settings.

Apex Class LogglyService.cls

This class uses theĀ @future (callout=true) annotation to make an HTTP POST to Loggly.com

public abstract class LogglyService {

    // Use a future method to make a callout
    @future (callout=true)
    public static void log(String data, String[] tags) {
        // this should come from config somewhere
    	final String api_key = 'GET YOUR API KEY FROM SOMEWHERE';

        // objects to make the request
        HttpRequest request = new HttpRequest();
        HttpResponse response = new HttpResponse();
        Http http = new Http();

        // setup the request
        request.setEndpoint('https://logs-01.loggly.com/inputs/'+api_key);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'text/plain');

        // add tags in the header
        request.setHeader('X-LOGGLY-TAG', String.join(tags, ','));

        // put the log message in the body
        request.setBody(data);

        try {
            // send the request to Loggly
            response = http.send(request);
        } catch(System.CalloutException e) {
            System.debug('Loggly error: ' + e);
        }

        System.debug(response.toString());
    }
}

Anonymous Apex Logging

Post a sample message to Loggly.com using this anonymous apex.

List<String> tags = new List<String>{'testTag'};
LogglyService.log('Test Log Message', tags);

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *