Mercurial Hosting > luan
view src/goodjava/webserver/handlers/LogHandler.java @ 1607:fa066aaa068c
nginx caching
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 30 Apr 2021 20:23:28 -0600 |
parents | 8a717f0b7f45 |
children | 94ea190714dd |
line wrap: on
line source
package goodjava.webserver.handlers; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import goodjava.logging.Logger; import goodjava.logger.Layout; import goodjava.logger.ListLayout; import goodjava.logger.DateLayout; import goodjava.logger.Layouts; import goodjava.logger.Appender; import goodjava.logger.ConsoleAppender; import goodjava.logger.DailyRollingFileAppender; import goodjava.logger.GoodLogger; import goodjava.logger.Level; import goodjava.io.IoUtils; import goodjava.webserver.Handler; import goodjava.webserver.Request; import goodjava.webserver.Response; public final class LogHandler implements Handler { private static final Layout layout = new ListLayout(new DateLayout("yyyy-MM-dd:HH:mm:ss")," ",Layouts.MESSAGE,"\n"); public static Logger consoleLogger() { Appender appender = new ConsoleAppender(layout,System.err); GoodLogger logger = new GoodLogger("HTTP"); logger.appender = appender; logger.level = Level.INFO; return logger; } public static Logger dirLogger(File dir,long deleteAfter) { if( dir.exists() && !dir.isDirectory() ) throw new RuntimeException("must be a directory"); try { IoUtils.mkdirs(dir); } catch(IOException e) { throw new RuntimeException(e); } DateFormat fmt = new SimpleDateFormat( "'" + dir + "/'yyyy_MM_dd'.log'" ); DailyRollingFileAppender appender = new DailyRollingFileAppender(layout,fmt); appender.deleteAfter = deleteAfter; GoodLogger logger = new GoodLogger("HTTP"); logger.appender = appender; logger.level = Level.INFO; return logger; } private final Handler handler; private final Logger logger; public LogHandler(Handler handler) { this(handler,consoleLogger()); } public LogHandler(Handler handler,Logger logger) { this.handler = handler; this.logger = logger; } public Response handle(Request request) { Response response = handler.handle(request); if( response == null ) return null; String ip = (String)request.headers.get("x-real-ip"); //String agent = (String)request.headers.get("user-agent"); logger.info( ip + " \"" + request.method + " " + request.path + "\" " + response.status.code + " " + response.body.length ); return response; } }