簡體   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