Mercurial Hosting > luan
view src/goodjava/webserver/handlers/LogHandler.java @ 1689:af22d6c120e4
improve http/serve.luan
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sun, 12 Jun 2022 18:48:01 -0600 |
parents | 94ea190714dd |
children | 8b3ad1fb219f |
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.rawPath + "\" " + response.status.code + " " + response.body.length ); return response; } }