Tuesday, January 14, 2014

Play Framework manual access log

Hi,

I needed access log in my Play Framework project but neither I had time for installing&integrating another webserver nor the following module supports X-Forwarded-For (from now on: XFF) IP:
http://www.playframework.com/modules/accesslog

So I wrote my own... The following methods generate the following output whether the client reaches your application directly (bypassing the loadbalancer) or using load balancer so that its real IP is given in header's XFF key value (of course if your loadbalancer supports that... In my case, it is F5-BigIP):

ACCESS LOG(BSM) - <IP> - <ComputerName> - Tue Jan 14 13:12:30 EET 2014

    public static void getAuth(String page)
    {  
        String direct_ip = Http.Request.current.get().remoteAddress;
        String xff_ip = null;
        if (Http.Request.current.get().headers.get("x-forwarded-for")!=null)
            xff_ip = Http.Request.current.get().headers.get("x-forwarded-for").toString();    

        String lookableIP = direct_ip;       
        if (xff_ip!=null)
        {
            xff_ip = xff_ip.substring(1,xff_ip.length()-1);            
            lookableIP = xff_ip;
        }       
        String computerName = nslookup(lookableIP);
        Date date = new Date();
        Logger.warn("ACCESS LOG("+page+") - " + lookableIP + " - " + computerName + " - " + date);       
   
    }
    private static String nslookup(String host)
    {
        try {
            InetAddress inetHost = InetAddress.getByName(host);
            return inetHost.getHostName();
            } catch(UnknownHostException ex) {
            return "N/A";
        }
    }


Note: Play Framework version: 1.2

Bye,

No comments:

Post a Comment