第一步:
导入jar包,maven项目可以直接添加
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
或在项目的lib下直接添加log4j-1.2.17.jar即可
第二步:
在需要打印信息的类里import org.apache.log4j.Logger;
第三步:
private static Logger logger = Logger.getLogger(类名.class); // 打印当前类日志
第四步:
在src目录下写一个log4j.properties文件
内容如下:
#logger
log4j.rootLogger=debug,appender1
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
第五步:
在需要打印信息的类里写
logger.info(" .................");
logger.debug(“”);
完成
以下为项目中用到的log4j.properites参考:
#log4j.rootLogger=DEBUG, A1, A2
log4j.rootLogger=DEBUG
log4j.logger.com.huidong=DEBUG, A1, A2, A4
# Available levels are DEBUG, INFO, WARN, ERROR, FATAL
#
# A1 is a ConsoleAppender
#
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-5p -[%c] (%F:%L) [%t] - %m%n
#
# A2 is a DailyRollingFileAppender
#
log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A2.file=../logs/web_user_xxhzx.log
log4j.appender.A2.datePattern='.'yyyy-MM-dd
log4j.appender.A2.Append=true
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%-5p %d{ISO8601} -[%c::%t(%F:%L)] - %m%n
log4j.appender.A2.Threshold = DEBUG
#
# A3 is a UDPAppender for sending logs as broadcast UDP packets
#
log4j.appender.A3=org.apache.log4j.net.UDPAppender
log4j.appender.A3.remoteHost=192.168.15.255
log4j.appender.A3.port=8881
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=%-5p %d{ISO8601} [%t] - %m%n
log4j.appender.A4=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A4.file=../logs/activate.log
log4j.appender.A4.datePattern='.'yyyy-MM-dd
log4j.appender.A4.Append=true
log4j.appender.A4.layout=org.apache.log4j.PatternLayout
log4j.appender.A4.layout.ConversionPattern=%m%n
log4j.appender.A4.Threshold = FATAL
#ideal config
# Ibatis Stuff
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, stdout
log4j.logger.java.sql.ResultSet=DEBUG, A1, A2
#
# The role is to print out the SQL statement in the console
#
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n