Saturday, November 9, 2013

Logging - creating a log record to log all messages once per transaction



In of of my other posts (link here) I explained how to log all events in one thread using a ThreadLocal. However the below simple strategy can be employed when you are sure that your request is executed by one single servlet without any filters and request dispatchers. This class in action can be seen in my other post(link here).

import java.io.PrintWriter; 
import java.io.StringWriter; 
import java.sql.Timestamp; 
import javax.servlet.http.HttpServletRequest;

public class AuditRecord {

        private final StringWriter sw;
        private final PrintWriter pw;

        public AuditRecord(HttpServletRequest request, String caller) {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            pw.print("[");
            pw.print(caller);
            pw.print("] ");
            pw.print(request.getLocalAddr());
            pw.print(' ');
            pw.println(new Timestamp(System.currentTimeMillis()));
        }

        public void append(String name, String value) {
            pw.print('\t');
            pw.print(name);
            pw.print('=');
            pw.println(value);
        }

        public void append(String message) {
            pw.print('\t');
            pw.println(message);
        }

        public void log() {
            pw.close();
            //log to a logger
            System.out.print(sw.toString());
        }

        public void append(String message, Exception e) {
            append(message);
            pw.println(e.getMessage());
            e.printStackTrace(pw);
        }
    } 

No comments:

Post a Comment