在上一篇中,通过一个简单的例子,得以管中窥豹,了解了Mina的基本编写方法。在MinaTimeServer演示程序中,我们添加了两个过滤器,一个是日志过滤器LoggingFilter,一个是文本编解码过滤器。前者实现日志信息的自动处理,后者实现对按行读写的文本数据的编码和解码。
其中LoggingFilter默认的是slf4j,它是一个日志Facade,实际并不实现真正的日志处理功能,它在程序运行时自动判断classpath中加载的日志组件,比如:log4j/Logback/JUL等,确定之后调用真正的日志组件实现真正的日志处理操作。这一点对于组件式的程序,很明显是非常灵活的,因为你并不知道用户的实际环境中使用的是log4j还是JUL,或者是Logback等,但是为了实现自动识别,slf4j默认了log配置文件的加载位置,让我觉得十分不便。
我自己的所有系统中,都使用是log4j(他的替代产品Logback已经出来了,据说性能更强),我一般喜欢把所有配置文件包括log4j.properties都放在conf目录下,以便管理。因此,对于slf4j中需要把log4j.properties放在src文件夹下非常不习惯,对于以后管理也容易引起混乱。所以,我希望能直接实现自己的log4j过滤器,按以前的方式使用。我们观察一下LoggingFilter过滤器的源代码,如下所示:
public class LoggingFilter extends IoFilterAdapter{...}
LoggingFilter继承自IoFilterAdapter,它是java模型中的适配器模式,是对接口IoFilter的包装。我们可以模仿LoggingFilter,实现自己的Log4jFilter类:
import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.mina.core.filterchain.IoFilterAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.core.write.WriteRequest; import org.apache.mina.filter.logging.LogLevel; import org.slf4j.helpers.MessageFormatter; public class Log4jFilter extends IoFilterAdapter { /** The logger name */ private final String name; /** The logger */ private final Logger logger; /** The log level for the exceptionCaught event. Default to WARN. */ private LogLevel exceptionCaughtLevel = LogLevel.WARN; /** The log level for the messageSent event. Default to INFO. */ private LogLevel messageSentLevel = LogLevel.INFO; /** The log level for the messageReceived event. Default to INFO. */ private LogLevel messageReceivedLevel = LogLevel.INFO; /** The log level for the sessionCreated event. Default to INFO. */ private LogLevel sessionCreatedLevel = LogLevel.INFO; /** The log level for the sessionOpened event. Default to INFO. */ private LogLevel sessionOpenedLevel = LogLevel.INFO; /** The log level for the sessionIdle event. Default to INFO. */ private LogLevel sessionIdleLevel = LogLevel.INFO; /** The log level for the sessionClosed event. Default to INFO. */ private LogLevel sessionClosedLevel = LogLevel.INFO; /** * Default Constructor. */ public Log4jFilter(Logger logger) { this.logger=logger; this.name=logger.getName(); } /** * @return The logger's name */ public String getName() { return name; } /** * Log if the logger and the current event log level are compatible. We log * a message and an exception. * * @param eventLevel the event log level as requested by the user * @param message the message to log * @param cause the exception cause to log */ private void log(LogLevel eventLevel, String message, Throwable cause) { if (eventLevel == LogLevel.TRACE) { logger.trace(message, cause); } else if (eventLevel.getLevel() > LogLevel.INFO.getLevel()) { logger.info(message, cause); } else if (eventLevel.getLevel() > LogLevel.WARN.getLevel()) { logger.warn(message, cause); } else if (eventLevel.getLevel() > LogLevel.ERROR.getLevel()) { logger.error(message, cause); } } /** * Log if the logger and the current event log level are compatible. We log * a formated message and its parameters. * * @param eventLevel the event log level as requested by the user * @param message the formated message to log * @param param the parameter injected into the message */ private void log(LogLevel eventLevel, String message, Object param) { String msgStr = MessageFormatter.format(message, param); if (eventLevel == LogLevel.TRACE) { logger.log(name, Level.TRACE, msgStr, null); } else if (eventLevel.getLevel() > LogLevel.INFO.getLevel()) { logger.log(name, Level.INFO, msgStr, null); } else if (eventLevel.getLevel() > LogLevel.WARN.getLevel()) { logger.log(name, Level.WARN, msgStr, null); } else if (eventLevel.getLevel() > LogLevel.ERROR.getLevel()) { logger.log(name, Level.ERROR, msgStr, null); } } /** * Log if the logger and the current event log level are compatible. We log * a simple message. * * @param eventLevel the event log level as requested by the user * @param message the message to log */ private void log(LogLevel eventLevel, String message) { if (eventLevel == LogLevel.TRACE) { logger.trace(message); } else if (eventLevel.getLevel() > LogLevel.INFO.getLevel()) { logger.info(message); } else if (eventLevel.getLevel() > LogLevel.WARN.getLevel()) { logger.warn(message); } else if (eventLevel.getLevel() > LogLevel.ERROR.getLevel()) { logger.error(message); } } @Override public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception { log(exceptionCaughtLevel, "EXCEPTION :", cause); nextFilter.exceptionCaught(session, cause); } @Override public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { log(messageReceivedLevel, "RECEIVED: {}", message ); nextFilter.messageReceived(session, message); } @Override public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { log(messageSentLevel, "SENT: {}", writeRequest.getMessage() ); nextFilter.messageSent(session, writeRequest); } @Override public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception { log(sessionCreatedLevel, "CREATED"); nextFilter.sessionCreated(session); } @Override public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception { log(sessionOpenedLevel, "OPENED"); nextFilter.sessionOpened(session); } @Override public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception { log(sessionIdleLevel, "IDLE"); nextFilter.sessionIdle(session, status); } @Override public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { log(sessionClosedLevel, "CLOSED"); nextFilter.sessionClosed(session); } /** * Set the LogLevel for the ExceptionCaught event. * * @param level The LogLevel to set */ public void setExceptionCaughtLoglevel(LogLevel level) { exceptionCaughtLevel = level; } /** * Get the LogLevel for the ExceptionCaught event. * * @return The LogLevel for the ExceptionCaught eventType */ public LogLevel getExceptionCaughtLoglevel() { return exceptionCaughtLevel; } /** * Set the LogLevel for the MessageReceived event. * * @param level The LogLevel to set */ public void setMessageReceivedLoglevel(LogLevel level) { messageReceivedLevel = level; } /** * Get the LogLevel for the MessageReceived event. * * @return The LogLevel for the MessageReceived eventType */ public LogLevel getMessageReceivedLoglevel() { return messageReceivedLevel; } /** * Set the LogLevel for the MessageSent event. * * @param level The LogLevel to set */ public void setMessageSentLoglevel(LogLevel level) { messageSentLevel = level; } /** * Get the LogLevel for the MessageSent event. * * @return The LogLevel for the MessageSent eventType */ public LogLevel getMessageSentLoglevel() { return messageSentLevel; } /** * Set the LogLevel for the SessionCreated event. * * @param level The LogLevel to set */ public void setSessionCreatedLoglevel(LogLevel level) { sessionCreatedLevel = level; } /** * Get the LogLevel for the SessionCreated event. * * @return The LogLevel for the SessionCreated eventType */ public LogLevel getSessionCreatedLoglevel() { return sessionCreatedLevel; } /** * Set the LogLevel for the SessionOpened event. * * @param level The LogLevel to set */ public void setSessionOpenedLoglevel(LogLevel level) { sessionOpenedLevel = level; } /** * Get the LogLevel for the SessionOpened event. * * @return The LogLevel for the SessionOpened eventType */ public LogLevel getSessionOpenedLoglevel() { return sessionOpenedLevel; } /** * Set the LogLevel for the SessionIdle event. * * @param level The LogLevel to set */ public void setSessionIdleLoglevel(LogLevel level) { sessionIdleLevel = level; } /** * Get the LogLevel for the SessionIdle event. * * @return The LogLevel for the SessionIdle eventType */ public LogLevel getSessionIdleLoglevel() { return sessionIdleLevel; } /** * Set the LogLevel for the SessionClosed event. * * @param level The LogLevel to set */ public void setSessionClosedLoglevel(LogLevel level) { sessionClosedLevel = level; } /** * Get the LogLevel for the SessionClosed event. * * @return The LogLevel for the SessionClosed eventType */ public LogLevel getSessionClosedLoglevel() { return sessionClosedLevel; } }
其实代码很类似,在MinaTimeServer中使用Log4jFilter使使看:
package com.gftech.mytool.mina; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.Date; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; public class MinaTimeServer { private static final int PORT = 2500; // static Logger logger = LoggerFactory.getLogger(MinaTimeServer.class); static Logger logger = Logger.getLogger(MinaTimeServer.class); public static void main(String[] args) throws IOException { PropertyConfigurator.configure("conf//log4j.properties"); IoAcceptor acceptor = new NioSocketAcceptor(); // LoggingFilter lf = new LoggingFilter("testLog"); Log4jFilter lf = new Log4jFilter(logger); acceptor.getFilterChain().addLast("logger", lf); acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("GBK")))); acceptor.setHandler(new TimeServerHandler()); acceptor.getSessionConfig().setReadBufferSize(10); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); acceptor.bind(new InetSocketAddress(PORT)); System.out.println("start server ..."); } } class TimeServerHandler extends IoHandlerAdapter { // static Logger logger = LoggerFactory.getLogger(TimeServerHandler.class); static Logger logger = Logger.getLogger(TimeServerHandler.class); @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { cause.printStackTrace(); } @Override public void messageReceived(IoSession session, Object message) throws Exception { String str = message.toString(); if (str.trim().equalsIgnoreCase("quit")) { session.close(true); return; } logger.debug("Rec:" + str); Date date = new Date(); session.write(date.toString()); logger.debug("Message written..."); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { logger.debug("IDLE " + session.getIdleCount(status)); } }
把配置文件按照自己的习惯放到conf目录下,就可以正常使用了。
需要注意的是,增加了自己的Log4jFilter之后,只能在您自己的代码中实现logger.debug()之类的调用时产生的日志记录才是正常的,即按配置文件中的要求老老实实进行日志记录。对于Mina代码中用到的logger调用,因为还是用的默认的slf4j,找不到src目录下的log4j.properties,所以产生的日志将无法正确显示和记录。除非您自己的将mina源代码中的logger全部改成log4j的logger,这是个小小的遗憾,鱼和熊掌不能兼得呀。
下一篇中,我们将介绍,如何编写自己的编解码过滤器。