001: package dinamica;
002:
003: import java.io.*;
004: import javax.servlet.*;
005: import javax.servlet.http.*;
006:
007: /**
008: *
009: * Servlet filter to generate a performance log
010: * according to the configured filter map and
011: * the init parameter "limit". A value of 0 will
012: * log all requests, a value > 0 will log only those request
013: * whose execution takes more than "limit" milliseconds.
014: *
015: * <br>
016: * Creation date: 5/jan/2004<br>
017: * Last Update: 5/jan/2004<br>
018: * (c) 2003 Martin Cordova<br>
019: * This code is released under the LGPL license<br>
020: * @author Martin Cordova
021: *
022: */
023:
024: public class PerformanceFilter implements Filter {
025:
026: //filter configuration object
027: private FilterConfig _config = null;
028:
029: //log threshold (log requests that take more than N milliseconds)
030: private int _limit = 0;
031:
032: /**
033: * init filter
034: **/
035: public void init(FilterConfig config) throws ServletException {
036:
037: _config = config;
038:
039: //load "limit" config parameter
040: String l = _config.getInitParameter("limit");
041: if (l != null)
042: _limit = Integer.parseInt(l);
043:
044: }
045:
046: /**
047: * clean up
048: **/
049: public void destroy() {
050: _config = null;
051: }
052:
053: /**
054: * Filter main method
055: */
056: public void doFilter(ServletRequest request,
057: ServletResponse response, FilterChain next)
058:
059: throws IOException, ServletException
060:
061: {
062:
063: long t1 = 0;
064: long t2 = 0;
065:
066: t1 = System.currentTimeMillis();
067:
068: HttpServletRequest req = (HttpServletRequest) request;
069:
070: //measure performance
071: try {
072:
073: t1 = System.currentTimeMillis();
074: next.doFilter(request, response);
075: t2 = System.currentTimeMillis();
076: long tt = t2 - t1;
077:
078: //save log if necessary
079: if (tt > _limit) {
080: saveLog(req, tt);
081: }
082:
083: }
084:
085: catch (Throwable e) {
086: throw new ServletException(e);
087: }
088:
089: }
090:
091: /**
092: * Save performance record to output device (file, database table, etc.)
093: * @param req HTTP Servlet Request to extract useful information
094: * @param t Elapsed time in milliseconds
095: * @throws Throwable
096: */
097: void saveLog(HttpServletRequest req, long t) throws Throwable {
098: String d = StringUtil.formatDate(new java.util.Date(),
099: "yyyy-MM-dd HH:mm:ss");
100: String uri = req.getRequestURI();
101: String tt = String.valueOf(t);
102: String ip = req.getRemoteAddr();
103: String method = req.getMethod();
104:
105: String msg = d + "\t" + uri + "\t" + method + "\t" + ip + "\t"
106: + tt;
107:
108: String file = _config.getInitParameter("path");
109:
110: StringUtil.saveMessage(file, msg);
111: }
112:
113: }
|