[JAVA] Log4j 範例

摘要:[JAVA] Log4j 範例

簡易快速加入log4j 

其他較詳細的設定請上網查詢

於maven pom.xml 中加入log4j的dependency


<!-- log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

並於resource folder中加入log4j.properties

系統會自動去抓這隻參數檔

內容如下


# Root logger option
log4j.rootLogger=DEBUG, stdout, file
 
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
 
# Redirect log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
#outputs to Tomcat home
log4j.appender.file.File=${catalina.home}/logs/myapp.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

內容主要是log會輸出於console 跟 輸出檔案 

最後於class中宣告


package proj.aop;


import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class ServiceAspect {

	private static final Logger logger = Logger.getLogger(ServiceAspect.class);

	@Pointcut("execution(* proj.service.impl.*.*(..))")
	public void serviceLayerPointcut() {

	}

	@Around("serviceLayerPointcut()")
	public Object serviceBefore(ProceedingJoinPoint pjp) throws Throwable {
		logger.debug("serviceBefore!!!");
		Object[] args = pjp.getArgs();
		return pjp.proceed(args);
	}

}

大功告成