繁体   English   中英

使用AOP和Log4J实现日志记录

[英]Implement logging with AOP and Log4J

我尝试使用方面将自动日志记录添加到使用Java EE和Spring(core + mvc + security ...)开发的Web应用程序中。 依赖关系由maven管理,应用程序服务器是Glassfish服务器。 方面部分似乎可以正常工作,但日志文件没有获取我通过方面发送的日志。

我在web.xml中设置日志记录配置,并添加了以下内容:

<listener id="myLogger">
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

该属性文件如下(它之所以起作用,是因为在我的系统文件夹中很好地创建了日志文件):

# Root logger option
log4j.rootLogger=INFO, file
log4j.rootLogger=WARN, file
log4j.rootLogger=ERROR, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\Users\\chaese\\Documents\\Dev\\LogsMEANS\\logging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

我还配置了一个方面(使用AspectJ),以便在调用以“ get”开头的函数的情况下记录所有信息。 这是这方面的课程:

import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class PropertyChangeTracker {

private Logger logger = Logger.getLogger(PropertyChangeTracker.getClass());

@Before("execution(String get*(..))")
public void trackCalls(){
    logger.info("controller called !!");
}
}

Aspect-config.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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context.xsd">

<bean id="propertyChangeTracker" class="services.aspects.PropertyChangeTracker">   </bean>

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

我在调试模式下对此进行了测试,并且调用“ trackCalls”方法没有任何麻烦,但是没有任何信息记录到日志文件中。 我感觉我的应用程序中有两种不同的记录器,而PropertyChangeTracker类使用的不是我想要的一种。您知道我在哪里设置了错误吗?

在此先感谢您的帮助!

我不确定,但是您的log4j配置看起来值得怀疑。 尝试仅在log4j.properties中添加log4j.rootLogger = INFO文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM