maven中超简单方式使用日志系统

pom.xml中引入依赖

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.7</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

新建resources/log4j.properties

### set log levels ###
#log4j.rootLogger = DEBUG,E,I,stdout
log4j.rootLogger = E,stdout

### 输出到控制台  ###
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}] %n %5p %c:%L - %m%n%n


log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG


### 输出到日志文件 ###
log4j.appender.I = org.apache.log4j.DailyRollingFileAppender
log4j.appender.I.File = logs/info.log
log4j.appender.I.Append = true
log4j.appender.I.Threshold = INFO
log4j.appender.I.layout = org.apache.log4j.PatternLayout
log4j.appender.I.layout.ConversionPattern = [%-d{yyyy-MM-dd HH:mm:ss}] %n %5p %c:%L - %m%n%n

## 保存异常信息到单独文件  ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = 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}] %n %5p %c:%L - %m%n%n

log4j.logger.org.springframework=OFF
log4j.logger.com.opensymphony=OFF
log4j.logger.org.apache.struts2=OFF
log4j.logger.freemarker.cache=OFF
log4j.logger.freemarker.beans=OFF
log4j.logger.org.springframework.web.servlet.mvc.method.annotation=ON
log4j.logger.org.mybatis=OFF
log4j.logger.org.apache.ibatis=OFF
log4j.logger.org.apache.zookeeper=OFF
log4j.logger.com.alibaba.dubbo=OFF
log4j.logger.org.apache.shiro=OFF
log4j.logger.org.apache.commons.beanutils=OFF

在需要打印log的class中添加代码

private static Logger logger = LoggerFactory.getLogger(类名.class);

然后在需要打印log的地方使用代码

logger.debug("This is debug message");
logger.info("This is info message");
logger.warn("This is warn message");
logger.error("This is error message");

说明:
Appender:
org.apache.log4j.ConsoleAppender(控制台)
org.apache.log4j.FileAppender(文件)
org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件)
org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)

标签: none

评论已关闭