相關技術和工具的使用:
這裡我們建立一個web工程為:struts2log4j,參見下面最終的工程結構:
# Root logger option log4j.rootLogger=ERROR, stdout, file # Redirect log messages to console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n # Redirect log messages to a log file, support rolling backup file. log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=${catalina.home}/logs/mystruts2app.log log4j.appender.file.MaxFileSize=5MB log4j.appender.file.MaxBackupIndex=10 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
package com.tw511.common.action; import org.apache.log4j.Logger; import com.opensymphony.xwork2.ActionSupport; public class WelcomeAction extends ActionSupport { private static final long serialVersionUID = 1L; //get log4j private static final Logger logger = Logger.getLogger(WelcomeAction.class); public String execute() throws Exception { // logs debug message if (logger.isDebugEnabled()) { logger.debug("execute()!"); } // logs exception logger.error("This is Error message", new Exception("Testing")); return SUCCESS; } }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="welcome" namespace="/" extends="struts-default"> <action name="welcome" class="com.tw511.common.action.WelcomeAction"> <result name="success">pages/success.jsp</result> </action> </package> </struts>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>Struts 2 Web Application</display-name> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>Struts 2 + Log4j integration example</h1> </body> </html>
在瀏覽器中開啟 URL : http://localhost:8888/struts2log4j/welcome
6.1 所有紀錄檔訊息將顯示在控制台中。
Figure : Eclipse 終端
6.2 此外,紀錄檔檔案將在Tomcat 的紀錄檔檔案夾中被建立。
圖片: C:\mystruts2app.log