如何使用AOP Spring和log4j实现日志记录

时间:2018-04-25 07:03:00

标签: java log4j spring-aop

我创建了一些切入点表达式,以便 @Before @After 并使用 log4j 配置我的日志记录  如下

package com.loveTodo.springPractice.aspect;

import java.util.logging.Logger;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CRMLoggingAspect {
    //setup logger

    private Logger myLogger=Logger.getLogger(getClass().getName());

    // setup pointcut declaration
    @Pointcut("execution(* com.loveTodo.springPractice.controller.*.*(..))")
    private void forControllerPackage() {

    }
    // do the same for service  and dao 
    @Pointcut("execution(* com.loveTodo.springPractice.service.*.*(..))")
    private void forServicePackage() {

    }  
    @Pointcut("execution(* com.loveTodo.springPractice.dao.imp.*.*(..))")
    private void forDaoPackage() {

    }  
    @Pointcut("forControllerPackage() || forServicePackage() || forDaoPackage()")
    private void forAppFlow() {}

    //add @Before advice  
    @Before("forAppFlow()")
    public void before(JoinPoint theJointPoint)
    {
        //diaplay method we are calling
        String theMethod = theJointPoint.getSignature().toShortString();
        myLogger.info("====> in @Before: calling method " + theMethod);

        //display the argruements to the method


        //GET THE ARGUEMENTS
        Object[] args=theJointPoint.getArgs();

        //loop through and display args
        for(Object tempArg : args)
        {
            myLogger.info("===> arguments "+ tempArg);
        }
    }

    // add @AfterReturing Advice

    @AfterReturning(pointcut="forAppFlow()",  
            returning="theResult")
    public void afterReturing(JoinPoint theJointPoint, Object theResult) {

        //display method we RE RETURING FROM
        String theMethod = theJointPoint.getSignature().toShortString();
        myLogger.info("====> in @AfterReturing: from return method " + theMethod);

        //DISPLAY DATA RECIEVED

        myLogger.info("===> result : "+theResult);
    }   

}

此信息消息在控制台上打印,但不在我配置如下的日志文件中打印

的log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "http://jakarta.apache.org/log4j/dtd/log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
    debug="false">

    <appender name="RollingFile" class="org.apache.log4j.RollingFileAppender">
        <param name="File" value="../logs/restFulSpring.log" />  
        <param name="maxFileSize" value="5000KB" />         
        <param name="maxBackupIndex" value="40" />     
        <param name="Threshold" value="DEBUG" />
        <layout class="org.apache.log4j.PatternLayout">
            <!-- The default pattern: Date Priority [Category] Message\n -->
            <param name="ConversionPattern" value="%-5p %d %-5r  (%t:%c):%n      [%l] %n      %m%n%n" />
        </layout>
    </appender>    

    <category name="org">
        <priority value="INFO" />
    </category>

    <category name="org.springframework">
        <priority value="INFO" />
    </category>

    <!-- <category name="org.hibernate">
        <priority value="INFO" />
    </category> -->

    <category name="org.springframework.ws.soap.security.wss4j">
        <priority value="DEBUG" />
    </category>

    <category
        name="org.springframework.ws.soap.server.endpoint.interceptor.SoapEnvelopeLoggingInterceptor">
        <priority value="DEBUG" />
    </category>

    <category name="org.springframework.security">
        <priority value="DEBUG" />
    </category>

    <category name="org.simpliccity.sst">
        <priority value="DEBUG" />
    </category>


    <root>
        <appender-ref ref="RollingFile" />
    </root>

</log4j:configuration>

这是我的spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">    


     <!-- add AspectJ autoproxy support for AOP -->


    <aop:aspectj-autoproxy>
        <aop:include name="CRMLoggingAspect"/>
    </aop:aspectj-autoproxy>

    <bean id="CRMLoggingAspect" class="com.loveTodo.springPractice.aspect.CRMLoggingAspect"/>

    <!-- Add support for component scanning -->       
    <context:component-scan base-package="com.loveTodo.springPractice" >

  </context:component-scan>   

    <!-- Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/> 

    <!-- Define Spring MVC view resolver -->  
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />     
    </bean> 
<mvc:resources mapping="/resources/**" location="/resources/" /> 
    <!-- Step 1: Define Database DataSource / connection pool -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false" />
        <property name="user" value="root" />
        <property name="password" value="root" />   

        <!-- these are connection pool properties for C3P0 -->  
        <property name="minPoolSize" value="5" />  
        <property name="maxPoolSize" value="20" /> 
        <property name="maxIdleTime" value="30000" />   
    </bean>  

    <!-- Step 2: Setup Hibernate session factory --> 
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.loveTodo.springPractice.entity" />  
        <property name="hibernateProperties">  
           <props>  
              <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
              <prop key="hibernate.show_sql">true</prop>
           </props>
        </property>
   </bean>    
<tx:annotation-driven/>   
    <!-- Step 3: Setup Hibernate transaction manager -->
    <bean id="transactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <mvc:default-servlet-handler/>   

</beans>    

如何使用into .loglog4j在控制台上存储这些信息消息AOP文件。我尝试过上述方法。

有任何错误或我错过了任何配置吗?

有没有其他方法可以这样做?

1 个答案:

答案 0 :(得分:0)

替换(在CRMLoggingAspect.java中)

import java.util.logging.Logger;

import org.apache.log4j.Logger;