Friday, June 6, 2014

Android remote logger - send logs to server

I want to show you simple implementation of remote logger for Android. This can be used for sendings logs from your app to server (backend).

public final class Logger {

    public static final String DISPATCHER_REPORT_URI = App.getDispatcherUri() + "/vidLog/report";

    private static final int CAPACITY = 10;
    private static final String APPLICATION_LOG_TAG = "YourApp";
    private static List<String> logs = new Vector<String>(CAPACITY);
   
    public synchronized static void r(String msg) {

        if (logs.size() + 1 > CAPACITY) {
            flushRemote();
        }

        logs.add(buildLog(msg));
    }

    public synchronized static void flushRemote() {
        final String formattedLogs = collectAndFormatLogs();

        Runnable sendLogs = new Runnable() {
            @Override
            public void run() {
                HttpHelper.doPostRequest(YOUR_SERVER_URI, "APP_LOG", formattedLogs);
            }
        };
        new Thread(sendLogs).start();

        logs.clear();
    }

    private static String collectAndFormatLogs() {
        String logsFormatted = "";
        for (String log : logs) {
            logsFormatted += log + "\n";
        }
        return logsFormatted;
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");

    private static String buildLog(String msg) {
        return sdf.format(new Date()) +
                " REMOTE " +
                APPLICATION_LOG_TAG + " " +
                msg;
    }

}
//Usage
Logger.r("first message");
Logger.r("second message");

//When CAPACITY is exceeded logs will be flushed automatically.
Logger.flushRemote();

2 comments:

  1. Could you please tell me what is "HttpHelper.doPostRequest", thanks.

    ReplyDelete
  2. It just do http post request, you can add your own http client implementation there.

    ReplyDelete