Struts2初始化时,首先就会初始化log,看源码如下:
1 public void init(FilterConfig filterConfig) throws ServletException { 2 InitOperations init = new InitOperations(); 3 Dispatcher dispatcher = null; 4 try { 5 FilterHostConfig config = new FilterHostConfig(filterConfig); 6 init.initLogging(config);//初始化log 7 dispatcher = init.initDispatcher(config); 8 init.initStaticContentLoader(config, dispatcher); 9 10 prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher); 11 execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher); 12 this.excludedPatterns = init.buildExcludedPatternsList(dispatcher); 13 14 postInit(dispatcher, filterConfig); 15 } finally { 16 if (dispatcher != null) { 17 dispatcher.cleanUpAfterInit(); 18 } 19 init.cleanup(); 20 } 21 }
1 public void initLogging( HostConfig filterConfig ) { 2 String factoryName = filterConfig.getInitParameter("loggerFactory"); 3 if (factoryName != null) { 4 try { 5 Class cls = ClassLoaderUtil.loadClass(factoryName, this.getClass()); 6 LoggerFactory fac = (LoggerFactory) cls.newInstance();//必须是LoggerFactory的子类 7 LoggerFactory.setLoggerFactory(fac); 8 } catch ( InstantiationException e ) { 9 System.err.println("Unable to instantiate logger factory: " + factoryName + ", using default"); 10 e.printStackTrace(); 11 } catch ( IllegalAccessException e ) { 12 System.err.println("Unable to access logger factory: " + factoryName + ", using default"); 13 e.printStackTrace(); 14 } catch ( ClassNotFoundException e ) { 15 System.err.println("Unable to locate logger factory class: " + factoryName + ", using default"); 16 e.printStackTrace(); 17 } 18 } 19 }
在web.xml中可以配置此log:
1 <filter> 2 3 <filter-name>struts2</filter-name> 4 5 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 6 7 <init-param> 8 <param-name>loggerFactory</param-name> 9 <param-value>com.opensymphony.xwork2.util.logging.commons.CommonsLoggerFactory</param-value> 10 </init-param> 11 12 </filter>
具体使用方法:
1 public static void test01() { 2 Logger log = LoggerFactory.getLogger(Test.class); 3 //必须是#加上数字的形式 4 log.info("#0t#1e#2st#3#4#5#6#7#8#9#10", new String[]{"a","b","c","d","e","f","g","h","i","j","k"}); 5 log.error("#0t#1e#2st#3#4#5#6#7#8#9#10", new String[]{"a","b","c","d","e","f","g","h","i","j","k"}); 6 log.warn("#0t#1e#2st#3#4#5#6#7#8#9#10", new String[]{"a","b","c","d","e","f","g","h","i","j","k"}); 7 log.fatal("#0t#1e#2st#3#4#5#6#7#8#9#10", new String[]{"a","b","c","d","e","f","g","h","i","j","k"}); 8 }
输出如下:
8 26, 2014 12:57:44 午後 test.Test info
情報: atbecstdefghijb0
8 26, 2014 12:57:44 午後 test.Test error
SEVERE: atbecstdefghijb0
8 26, 2014 12:57:44 午後 test.Test warn
WARNING: atbecstdefghijb0
8 26, 2014 12:57:44 午後 test.Test fatal
SEVERE: atbecstdefghijb0
时间: 2024-10-17 08:14:56