log4j2


化石原创文章,转载请注明来源并保留原文链接


使用properties配置log4j2

1、配置文件(使用properties文件)

a) 放置log4j.properties到工程的根目录
b) 代码里指定该log4j.properties文件

String currentDirectory = System.getProperty("user.dir");
System.setProperty("log4j.configurationFile", currentDirectory + File.separator + "log4j.properties");

log4j.properties文件内容:

 status=warn
 name=properties_configuration
 #Give directory path where log files should get stored
 property.basePath=f:\/log\
 appenders=console, rolling
 #ConsoleAppender will print logs on console
 appender.console.type=Console
 appender.console.name=consoleLogger
 appender.console.target=SYSTEM_OUT
 appender.console.layout.type=PatternLayout
 #Specify the pattern of the logs
 appender.console.layout.pattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n
 #RollingFileAppender will print logs in file which can be rotated based on time or size
 appender.rolling.type=RollingFile
 appender.rolling.name=fileLogger
 appender.rolling.fileName=${basePath}app.log
 appender.rolling.filePattern=${basePath}app_%d{yyyyMMdd}.log.gz
 appender.rolling.layout.type=PatternLayout
 appender.rolling.layout.pattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n
 appender.rolling.policies.type=Policies
 #Rotate log file each day and keep 30 days worth
 appender.rolling.policies.time.type=TimeBasedTriggeringPolicy
 appender.rolling.policies.time.interval=1
 appender.rolling.policies.time.modulate=true
 appender.rolling.strategy.type=DefaultRolloverStrategy
 appender.rolling.strategy.delete.type=Delete
 appender.rolling.strategy.delete.basePath=${basePath}
 appender.rolling.strategy.delete.maxDepth=1
 appender.rolling.strategy.delete.ifLastModified.type=IfLastModified
 #Delete files older than 30 days
 appender.rolling.strategy.delete.ifLastModified.age=30d
 #Configure root logger for logging error logs in classes which are in package other than above specified package
 #level: ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
 rootLogger.level=all
 rootLogger.additivity=false
 rootLogger.appenderRef.rolling.ref=fileLogger
 rootLogger.appenderRef.console.ref=consoleLogger

2、代码得到logger句柄

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Logger logger = LogManager.getLogger(name);

3、具体使用

logger.debug(info);
logger.info(info);
logger.warn(info);
logger.error(info);
logger.trace(info);
logger.fatal(info);

使用上面的配置和方法,可以在文件(按上面log4j.properties的配置,在f:/log/app.log中)里和intellij的Console里输出debug、info、warn、error、trace、fatal信息。如果要控制输出的信息,可以在log4.properties文件的最后的部分改动:

rootLogger.level = xxx,比如 rootLogger.level = debug

注:

1、上面的例子代码中因为我们指定的代码是主程序的class的名字,在log4j.properties文件中找不到该名字的logger,所以log4j2会使用rootLogger这个默认的logger。

2、PatternLayout的手册在:

https://logging.apache.org/log4j/2.x/manual/layouts.html


化石原创文章,转载请注明来源并保留原文链接


发表评论

电子邮件地址不会被公开。 必填项已用*标注