The implementation of log management under STRUTS+SPRING+LOG4J framework

Source: Internet
Author: User
Tags aop log log string back log4j
Configuration of log4j
The specific configuration of the log4j log file is described separately because its configuration will directly determine how the log is generated, where it is stored, and how it is exported.
Establish log4j.properties under/src. The contents are as follows:
# here defines the log configuration root logger, where the following info,console,file represents the priority of the log record, followed by a hint, warning, file
Log4j.rootlogger=info,console,file
# This is where the log output is defined, such as a console (console), file (files), new files based on the number of days or file sizes,
Sent as a stream to other places, using the form of output to the console, which is the Web server
Log4j.appender.console=org.apache.log4j.consoleappender
# here defines a new file when the file size reaches the specified size (10M), stored under D disk, named Wgems.txt
Log4j.appender.file=org.apache.log4j.rollingfileappender
Log4j.appender.file.file=d:\\wgems.txt
log4j.appender.file.maxfilesize=10mb
Log4j.appender.file.maxbackupindex=7
# below defines the format of the console log output, LOG4J provides 4 output formats, such as HTML style, freeform style, including log level and information
Styles and styles that contain information such as log time, threads, categories, and so on. This article uses the free designation style.
Log4j.appender.console.layout=org.apache.log4j.patternlayout
# What needs to be explained here is the meaning of several symbols in the log Information format:
-X: Left-aligned when X information is output
%M the message specified in the output code
% p output priority, i.e. Debug,info,warn,error,fatal
%r output the number of milliseconds it takes to boot to output the log information
The class to which the%c output belongs, usually the full name of the class in which it is located
%t output The name of the thread that generated the log event
%n output a carriage return line feed, Windows platform "RN", Unix platform "n"
%d output log point-in-time date or time, the default format is ISO8601, or you can specify a format after it, such as:%d{yyyy MMM DD HH:mm:ss,
SSS}, Output is similar: October 18, 2002 22:10:28,921
%l the location where the output log event occurs, including the class name, the thread that occurred, and the number of lines in the code.
log4j.appender.console.layout.conversionpattern=%-4r[%t]%-5p%c%l%x-%m%n
# The following defines the output format of the log file on the hard disk when the specified size is reached
Log4j.appender.file.layout=org.apache.log4j.patternlayout

log4j.appender.file.layout.conversionpattern=%p-%m%l%n


Struts and Spring Framework Integration
1 Consolidated configuration of Struts

The main way for struts to work with spring is to let struts know that spring exists so that spring manages related components, avoiding
Direct authoring of dependencies on components is established.
First, create a new configuration file named Applicationcontext.xml in/webroot/web-inf/directory, and in the/webroot/lib/directory
Add spring's core package as well as the log4j log pack with the name: Commons-logging.jar,spring.jar.
Then add a paragraph at the end of the/webroot/web-inf/web.xml file:

<!--spring configuration-->
   <listener>
     <listener-class> org.springframework.web.context.contextloaderlistener</listener-class>
   </listener>  
  < context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value> Classpath:/spring.xml</param-value>
  </context-param>

Finally, let struts ' action be inherited Org.springframework.web.struts.ActionSupport, import the package Spring-struts-3.2.0.jar
This class is the implementation of the action abstract class of struts, which can be used to obtain an instance of ApplicationContext, and then further obtain the spring container

The managed bean instance. The specific code implementation looks like this:

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import Org.springframework.web.context.WebApplicationContext;
Import Org.springframework.web.struts.DispatchActionSupport;
  public class Clxxbjaction extends dispatchactionsupport{public
    Actionforward execute () {
      Webapplicationcontext context =getwebapplicationcontext ();
	In the future, the logging operation
      Clxxbjbean Clxxbjbean = (Clxxbjbean) context.getbean ("Clxxbjbean") is woven each time the method specified by the Clxxbjbean is used.
  

2 Spring's consolidated configuration
In the spring configuration applicationcontext.xml file configures the bean to be managed by spring and configures the log interceptor.
This article is an example of a material management module in the management system:
First define the proxy bean file (which encapsulates the business logic processing of material management)
<bean id= "Clxxbjbean" class= "Cl.model.clxxbjBean"/>
Next, define the log interceptor as follows:
<. --Configure Log Interceptor (Advice)-->
<bean name= "Logger" class= AOP. Logginginterceptor "/>
<. --Slice configuration device (Aspect)-->
<bean id= "Advisor_log"


class= "Org.springframework.aop.support.RegexpMethodPointcutAdvisor" >
<. -This indicates that the specific implementation of the day record operation is done by the class named Logger
<property name= "Advice" ref= "logger" ></property>
<. -This means that as soon as the method name is del (delete), add (add), update (end) method is woven into the advices during execution, which is the logging operation in this article
<property name= "Patterns" >
<list>
<value>.*del</value>
<value>.*add</value>
<value>.*update</value>
</list>
</property>
</bean>
<. --Configure Interceptor Agent-->
<bean name= "Loggingautoproxy" class= "Org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" >
<. This defines the class that is being represented, that is, the previously defined Clxxbjbean
<property name= "Beannames" >
<list>
<value>clxxbjBean</value>
</list>
</property>
<. -Here defines the common interception object Advisor_log for all of the represented classes mentioned above, this aspect is already defined in the preceding
<property name= "Interceptornames" >
<list>
<value>advisor_log</value>
</list>
</property>

</bean>


  Implementation of the log management class
by separating the log management module from the normal business logic module, we will take a separate class to implement this work, and then weave the logging operation after the specified method
executes , the specific code looks like this:

The ...//code omits public class Logginginterceptor implements afterreturningadvice{//This defines a database connection object Controldbbean controldb=new C
	Ontroldbbean (); String text= "";
	Log info string to write Log//get log name Log log=logfactory.getlog ("Wgems"); Here the 4 parameters of the method represent the return value of the target method, the method instance, the parameter object array, and the target object public void Afterreturning (object Returnvalue,method method,object []args,
		Object target) throws Throwable try{System.out.println ("into AOP log Management");
		Oraclecachedrowset Ocrs=null;
		Gets the current time of the database system Ocrs=controldb.querysqltorowset ("Select To_char (sysdate, ' yyyy-mm-dd hh24:mi:ss ') dd from dual");
		Ocrs.next ();
		String Db_date=ocrs.getobject ("DD"). toString ();
		Ocrs.close (); If the method instance name contains the add string, that is, the add operation is performed if (Method.getname (). IndexOf ("Add").
			=-1) {//Call log class, and at the level of information prompted the specific data added and specific time log.info (db_date+ "added a row of new material data" + "\ n");
			Log.info ("added data is:");
                         for (int i=0;i<args.length;i++) {text+=args[i].tostring () + "\ T";
			} log.info (text+ "\ n"); Text= ""; Log information string back to bit}//If the method instance name contains an update string, which is to perform the update operation ...//code omitted///If the method instance name contains a del string, that is, the deletion is performed ... the code omits}catch (Exception e) {System.out.println ("Log write error.
     "+e.getmessage ());
 }
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.