原文链接:https://www.jianshu.com/p/eb4ac2571c94?tdsourcetag=s_pctim_aiomsg
1、先创建个maven项目,在我们项目的pom文件中导入log4j的依赖:
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency>
2、在resources目录下创建log4j.properties文件
### 设置### log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制台 ### 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 = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n ### 输出DEBUG 级别以上的日志到日志文件 ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = /home/duqi/logs/debug.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 输出ERROR 级别以上的日志到日志文件 ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =/home/admin/logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n log4j.logger.freemarker.cache=ERROR log4j.logger.freemarker.beans=ERROR
如果日志文件没有设置路径的话,那么日志文件会输出到工程目录下。
3、测试代码实例
import org.apache.log4j.*; public class Demo { private static Logger logger = Logger.getLogger(vincent_player_framt.class); public static void main(String[] args) throws Exception { // debug级别的信息 logger.debug("This is debug message."); // info级别的信息 logger.info("This is info message."); // error级别的信息 logger.error("This is error message."); } }