view src/goodjava/webserver/handlers/LogHandler.java @ 1803:d1dd61e6dd84

backtick fix
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 07 May 2024 19:45:20 -0600
parents 8b3ad1fb219f
children
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 {
	public static int level = Level.INFO;
	public static 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;
		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;
		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;
	}
}