This is the second part of the post. The first one is available here.

Uploading the server logs to Firebase.

This task proved to be very simple. I wanted to achieve the following

  1. Add a timestamp to the message.
  2. Upload the message to Firebase. Each of the users should have their instance of the log file.
  3. Print the message into the log.
  4. Erase the old messages every 10 minutes.
Without going much further into the details, here is the class I ended up using.
package com.spreys.udacity;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with Intellij IDEA
 * @author vspreys
 * Date: 18/04/15
 * Contact by: vlad@spreys.com
 */
public class Logger {
    private static final SimpleDateFormat TIMESTAMP_FORMAT 
         = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    private final DatabaseReference databaseReference;

    public Logger(String username) {
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        this.databaseReference = database
                                    .getReference("logs/" + username);
        startCleaner();
    }

    /**
     * Prints out message into the console with the current date/time
     * @param message message to be printed
     */
    public void println(String message){
        String timeStamp = TIMESTAMP_FORMAT.format(new Date());

        String messageWithTimestamp = timeStamp + ": " + message;

        //Print out the message
        System.out.println(messageWithTimestamp);

        //Update the database with the new message
        databaseReference.push().setValue(messageWithTimestamp);
    }

    private void startCleaner() {
        new Thread(new Runnable() {
            public void run() {
                do {
                    databaseReference.setValue(null);
                    println("The logs have been cleaned");

                    //Clean the logs every 10 minutes
                    waitFor(10 * 60);
                } while (true);
            }
        }).start();
    }

    private void waitFor(float seconds){
        try {
            Thread.sleep((int)(seconds * 1000)); 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
%d bloggers like this:

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Subscribe!