Spring AOP + Log4j records project logs and aoplog4j

Source: Internet
Author: User

Spring AOP + Log4j records project logs and aoplog4j

Reprinted please indicate the source: http://www.cnblogs.com/Joanna-Yan/p/6567672.html

Project log records are essential for project development and operation. With such records, you can control the system as a whole and trace any problems.

If you use the pure OOP idea for log processing, you will find that every logical part will always be mixed into the log processing code, which is a nondescribable design of the pure OOP idea. If the Log Type requirement changes, you need to modify the Java code in each logical unit. It will be a very tedious task to change the requirements. Therefore, log processing should be a separate part of the project. We should not consider log processing during system development. AOP allows us to focus more on project business coding without worrying about log issues.

First, we will briefly introduce AOP (Aspect Oriented Programming ):

AOP is a continuation of OOP and a programming method that disperses attention. It encapsulates "Attention" in the aspect to implement decoupling between callers and callers.

Decentralized attention: separates common requirement functions from irrelevant classes and allows multiple classes to share one behavior. Once the behavior changes, you do not have to modify many classes, you only need to modify this behavior.

Object-oriented is vertically structured, which makes the logical unit of the system clearer.

The aspect orientation is a cross-cutting structure, which extracts the aspect of the business logic layer. For example, if a plane is used to complete a function, this function is involved in every module. It is cut into the system like a knife and tofu, and can perform the same control on the system.

Doubt: The donet program can be run only when it is deployed on the server, but the Java program has multiple processes and must be deployed in the container before it can run? Why does J2EE need a J2EE container and a J2EE application system?

Answer: The J2EE container is actually a commonly used part of a general application system. Functions such as transactions, security, and database connection pools are separated to form a general framework. The Design and Development of these functional mechanisms are difficult, and the stability and speed of running at the same time are very important. It must be developed after a long time of debugging and operation experience, it gradually formed J2EE Container service products such as Tomcat, JBoss, and WebLogic. Simply put, the container in J2EE is to take out the things that are used in most software and become a product after a long time.

The J2EE system is divided into containers and application systems. We can see a method of decentralization.

Implementation process:

1. involved jar packages:

Spring. jar

Log4j-1.2.16.jar

Aspectjrt. jar

Aspectjweaver. jar

Commons-logging.jar

2. Log class for aspect orientation:

Import org. apache. log4j. logger; import org. aspectj. lang. joinPoint; import org. aspectj. lang. proceedingJoinPoint; public class LogAspect {Logger logger = Logger. getLogger (LogAspect. class); String logStr = null;/*** pre-notification: A notification executed before a connection point, but this notification cannot prevent execution before the connection point * @ param jp connection point: A line in the Program Execution Process is */public void doBefore (JoinPoint jp) {logStr = jp. getTarget (). getClass (). getName () + "class" + jp. getSignature (). the getName () + "method starts to execute ***** * Start ******* "; logger.info (logger);}/*** surround notification: notifications that enclose a connection point, you can customize the behavior before and after the method is called, or you can choose not to execute. * Similar to the doFilter method of the Filter in the Servlet specification in the web. * @ Param pjp connection point in the current process * @ return */public Object doAround (ProceedingJoinPoint pjp) {long Time = System. currentTimeMillis (); Object result = null; try {result = pjp. proceed ();} catch (Throwable e) {e. printStackTrace (); logStr = "method:" + pjp. getTarget (). getClass () + ". "+ pjp. getSignature (). getName () + "()"; logStr = logStr + "error message: [" + e + "]"; logger.info (logStr) ;}return result ;} /*** post notification * @ param jp */public void doAfter (JoinPoint jp) {logStr = jp. getTarget (). getClass (). getName () + "class" + jp. getSignature (). getName () + "End of method execution ******* End ******"; logger.info (logStr );}}

3. Configure AOP logs in the spring configuration file ApplicationContext. xml

<! -- AOP logs --> <bean id = "logAspect" class = "yan. joanna. log. logAspect "> </bean> <aop: config> <aop: aspect id =" aspect "ref =" logAspect "> <! -- Logs the methods. The set get method in the action is blocked here --> <aop: pointcut id = "logService" expression = "(execution (* yan. joanna. *. *. *(..))) and (! Execution (* yan. joanna. action. *. set * (..) and (! Execution (* yan. joanna. action. *. get *(..))) "/> <aop: before pointcut-ref =" logService "method =" doBefore "/> <aop: after pointcut-ref = "logService" method = "doAfter"/> <aop: around pointcut-ref = "logService" method = "doAround"/> </aop: aspect> </aop: config> <! -- Configure Action --> <bean id = "UserAction" class = "yan. joanna. action. userAction "scope =" prototype "> <property name =" userDAO "ref =" UserDAO "> </property> <property name =" maindeviceDAO "ref =" MaindeviceDAO "> </ property> <property name = "amountDAO" ref = "AmountDAO"> </property> <property name = "deviceUsingDAO" ref = "DeviceUsingDAO"> </property> </bean>

4. Main configuration of the log4j. properties file of log4j

log4j.rootLogger = info, stdout, Rlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern = %p %d{yyyy-MM-dd HH:mm:ssS} || %c{1} || %m%nlog4j.appender.R=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.R.File=d:/UTrainFileLib/logs/utrain.loglog4j.appender.R.Append=truelog4j.appender.R.layout=org.apache.log4j.PatternLayout  log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] [%t] (%F\:%L) ->%m %nlog4j.appender.R.Threshold=INFOlog4j.appender.R.DatePattern='.'yyyy-MM-dd

5. At the initial stage of development or operation, we may want to print some business logic, parameter values, and control its printing level.

import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class JYLog {    private static final Log log = LogFactory.getLog(JYLog.class);        public static void printLog(String msg){        if(log.isInfoEnabled()){            log.info(msg);        }    }        public static void errorLog(String msg,Exception e){        log.error(msg, e);    }        public static void errorLog(String msg){        log.error(msg);    }}

6. Print business logs. For example, the logon method in UserAction:

/*** Login * @ throws IOException */public void login () throws IOException {HttpServletRequest req = ServletActionContext. getRequest (); HttpServletResponse resp = ServletActionContext. getResponse (); req. setCharacterEncoding ("UTF-8"); resp. setCharacterEncoding ("UTF-8"); String tel = req. getParameter ("tel"); JYLog. printLog ("login ()-Logon-Timestamp-" + new Timestamp (System. currentTimeMillis () + "; tel-" + tel); Print Writer out = resp. getWriter (); JSONObject json = new JSONObject (); JSONObject dataJson = new JSONObject (); String message = ""; int errorcode = 0; if (! "". Equals (tel) {User user = userDAO. findByAccount (tel); if (user = null) {userDAO. save (new User (tel, new Timestamp (System. currentTimeMillis (), new Timestamp (System. currentTimeMillis (), 1); user = userDAO. findByAccount (tel); amountDAO. save (new Amount (user, 100,0);} else {userDAO. updateLoginTime (user);} dataJson. put ("id", user. getId (); dataJson. put ("account", user. getAccount (); dataJson. put ("type", user. getType (); message = "Logon successful"; errorcode = 0;} else {message = "invalid mobile phone number"; errorcode = 10002;} json. put ("data", dataJson); json. put ("message", message); json. put ("errorcode", errorcode); out. print (json); out. flush (); out. close (); JYLog. printLog ("login ()-Logon-json-" + json. toString ());}

7. The content of the log Printing file is partially displayed:

[Yan. joanna. log. JYLog]-[INFO] [http-bio-59500-exec-56] (JYLog. java: 11)-> login ()-login-Timestamp-2017-04-01 08:10:08. 972; tel-15515123456 08:10:08 [yan. joanna. log. logAspect]-[INFO] [http-bio-59500-exec-56] (LogAspect. java: 14)-> org. apache. log4j. logger @ 10fb78e 08:10:08 [yan. joanna. log. logAspect]-[INFO] [http-bio-59500-exec-56] (LogAspect. java: 34)-> yan. joanna. dao. the findByAccount method of the UserDAO class is executed ******** End ****** 08:10:08 [yan. joanna. log. logAspect]-[INFO] [http-bio-59500-exec-56] (LogAspect. java: 14)-> org. apache. log4j. logger @ 10fb78e 08:10:08 [yan. joanna. log. logAspect]-[INFO] [http-bio-59500-exec-56] (LogAspect. java: 34)-> yan. joanna. dao. the execution of the updateLoginTime method of the UserDAO class ends at ******** End ****** 08:10:09 [yan. joanna. log. JYLog]-[INFO] [http-bio-59500-exec-56] (JYLog. java: 11)-> login ()-Logon-json-{"data": {"id": 68, "account": "15515123456", "type ": 1}, "message": "Logon successful", "errorcode": 0} 08:10:09 [yan. joanna. log. logAspect]-[INFO] [http-bio-59500-exec-56] (LogAspect. java: 34)-> yan. joanna. action. *** End ******

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.