log4j每个小时生成一个日志文件

log4j.properties

属性文件

log4j.logger.visitlog=INFO, VisitFile
log4j.logger.pushlog=INFO, PushFile

#visitLog
log4j.appender.VisitFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.VisitFile.encoding=UTF-8
log4j.appender.VisitFile.File=${catalina.home}/logTraffic/visitlog
log4j.appender.VisitFile.DatePattern='.'yyyy-MM-dd_HH'.csv'
log4j.appender.VisitFile.layout=org.apache.log4j.PatternLayout
log4j.appender.VisitFile.layout.ConversionPattern=%m%n

#pushLog
log4j.appender.PushFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.PushFile.encoding=UTF-8
log4j.appender.PushFile.File=${catalina.home}/logTraffic/pushlog
log4j.appender.PushFile.DatePattern='.'yyyy-MM-dd_HH'.csv'
log4j.appender.PushFile.layout=org.apache.log4j.PatternLayout
log4j.appender.PushFile.layout.ConversionPattern=%m%n

对需要打印的对象类做处理

public class RequestMessage {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private String ip = ""; // ip地址
    @Override
    public String toString() {
        return new ReflectionToStringBuilder(this, ToStringStyle.SIMPLE_STYLE).setExcludeFieldNames(new String[] {"logger"}).toString();
    }
}

记录日志如下

public final class LogEventDispatcher implements EventHandler<LogEvent> {

	private Logger visitLog = LoggerFactory.getLogger("com.qc.socket.scheduler.LogEventDispatcher.visitLog");

	@Override
	public void handle(LogEvent event) {
		RequestMessage requestMessage = event.getRequestMessage();
		switch (event.getType()) {
		case C_FILE:
			visitLog.info(requestMessage.toString());
			break;
		}
	}
}

OK

你可能感兴趣的:(log4j)