标签:
package com.cn21.yao.service; import org.apache.log4j.Logger; public class UserService { //方法一: //public static final Logger logger = Logger.getLogger("test");//会去找log4j.properties中的log4j.logger.test //方法二: public static final Logger logger = Logger.getLogger(UserService.class);
//此时在log4j.properties中log4j.logger.com.cn21.yao.service = WARN, file可以不要,用log4j.rootLogger=WARN, file代替 public void add() { /*//设置日志保存的目录为项目的log目录 String url = UserService.class.getClassLoader().getResource("").getPath(); url = url.replace("bin/", "log/"); System.setProperty("LOG_DIR", url);*/ /** * 可以为日志设置不同的级别,在Log4j中 * debug < info < warn < error < fatal */ logger.debug("添加用户信息"); logger.info("添加用户信息"); logger.warn("添加用户信息"); logger.error("添加用户信息"); logger.fatal("添加用户信息"); } }
package com.cn21.yao.dao; import org.apache.log4j.Logger; public class UserDao { public static final Logger logger = Logger.getLogger(UserDao.class); public void add() { /** * 可以为日志设置不同的级别,在Log4j中 * debug < info < warn < error < fatal */ logger.debug("添加用户信息"); logger.info("添加用户信息"); logger.warn("添加用户信息"); logger.error("添加用户信息"); logger.fatal("添加用户信息"); } }
log4j.properties
# Root logger option(out--->the way to output,it can be whatever you want,but be consistent with the content below) #log4j.rootLogger=DEBUG, out, file 输出日志 log4j.rootLogger=DEBUG, out # Direct log messages to stdout log4j.appender.out=org.apache.log4j.ConsoleAppender #控制台方式显示 log4j.appender.out.Target=System.out log4j.appender.out.layout=org.apache.log4j.PatternLayout log4j.appender.out.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1}:%L - %m%n #方式1. #log4j.logger.test = WARN, file, out #方式2. log4j.logger.com.cn21.yao.service = WARN, file # Direct log messages to a log file #方式1. #log4j.appender.file=org.apache.log4j.RollingFileAppender #方式2. log4j.appender.file=org.apache.log4j.DailyRollingFileAppender #Redirect to Tomcat logs folder #log4j.appender.file.File=${catalina.home}/logs/logging.log #方式1.采用绝对路径保存在本地 #log4j.appender.file.File=F:\\user.log #方式2.采用相对路径保存 log4j.appender.file.File=${LOG_DIR}user.log #方式2.针对DailyRollingFileAppender log4j.appender.file.datePattern=‘.‘yyyy-MM-dd-HH #1.针对RollingFileAppender #log4j.appender.file.MaxFileSize=10MB #1.针对RollingFIleAppender #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
测试:
package test; import org.junit.Test; import com.cn21.yao.dao.UserDao; import com.cn21.yao.service.UserService; public class MyTest { @Test public void consoleLog() { UserDao ud = new UserDao(); ud.add(); } @Test public void fileLog() { //设置日志保存的目录为项目的log目录 String url = UserService.class.getClassLoader().getResource("").getPath(); url = url.replace("bin/", "log/"); System.out.println("url:"+url); System.setProperty("LOG_DIR", url); UserService us = new UserService(); us.add(); } }
标签:
原文地址:http://www.cnblogs.com/ysch/p/4232058.html