Struts 2 + Log4j統合の例

このチュートリアルでは、log4jフレームワークをStruts 2 Webアプリケーションと統合する方法を示します。 あなたがする必要があるのはただ
-
プロジェクトの依存関係として
log4j.jarを含めます -
log4j.propertiesファイルを作成し、クラスパスのルートに配置します。Mavenを使用して、
resourcesフォルダーに配置します。
使用される技術とツール:
-
Log4j 1.2.17
-
Struts 2.3.16.3
-
メーベン3
-
トムキャット6
-
Eclipseケプラー4.3
1. プロジェクトディレクトリ
最終的なプロジェクト構造を確認します。

2. プロジェクトの依存関係
Struts 2とlog4jの依存関係を宣言します。
pom.xml
4.0.0 com.example.common Struts2 war 1.0-SNAPSHOT Struts + Log4j Webapp http://maven.apache.org 1.7 2.3.16.3 1.2.17 org.apache.struts struts2-core ${struts.version} log4j log4j ${log4j.version} Struts2 org.apache.maven.plugins maven-eclipse-plugin 2.9 true false 2.0 org.apache.maven.plugins maven-compiler-plugin 2.3.2 ${jdk.version} ${jdk.version}
3. log4j.properties
log4jプロパティファイルを作成し、それをresourcesフォルダーに配置します。手順1を参照してください。
log4j.properties
# 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
4. Struts 2アクションとロギング
ページを返す簡単なアクション。log4jを使用してメッセージロギングを行う方法を示します。
WelcomeAction.java
package com.example.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;
}
}
5. Struts 2の構成
興味がある場合に備えて、Struts 2構成およびJSPページ。
struts.xml
pages/success.jsp
web.xml
Struts 2 Web Application struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /*
pages/success.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>Struts 2 + Log4j integration example
6. Demo
Struts 2 Webアプリケーションを実行し、ようこそアクションにアクセスします。

6.1すべてのログメッセージがコンソールに表示されます。

図:Eclipseコンソール
6.2さらに、Tomcatのlogsフォルダーにログファイルが作成されます。

Figure : D:pache-tomcat-6.0.37\logs\mystruts2app.log
ソースコードをダウンロード
ダウンロード–Log4jAndStruts2Example.zip(20 KB)