导jar包:log4j-1.2.16.jar
Log4JTest.java
package cn.itcast.log4j; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; /** * 测试log4j 使用 * * @author seawind * */ public class Log4JTest { // 创建记录器时,使用当前类 Class对象构造 private static final Logger LOG = Logger.getLogger(Log4JTest.class); public static void main(String[] args) { // 日志记录器必须有输出目标 BasicConfigurator.configure();// 输出到控制台 // 设置级别 LOG.setLevel(Level.INFO); // 写日志 LOG.debug("这是调试信息"); LOG.info("这是普通信息"); LOG.warn("这是警告信息"); LOG.error("这是错误信息"); } }
Log4JTest2.java
package cn.itcast.log4j; import org.apache.log4j.Logger; /** * 使用Log4J 配置文件 * * @author seawind * */ public class Log4JTest2 { // 创建日志记录器对象 private static final Logger LOG = Logger.getLogger(Log4JTest2.class); public static void main(String[] args) { // 自动加载 log4j.properties LOG.debug("配置文件输出 debug"); LOG.info("配置文件输出 info"); LOG.warn("配置文件输出 warn"); LOG.error("配置文件输出 error"); } }
log4j.properties
# Logger log4j.rootLogger = all, A1, A2 #Appender log4j.appender.A1 = org.apache.log4j.ConsoleAppender log4j.appender.A1.target = system.err #Layouts log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n log4j.appender.A2 = org.apache.log4j.FileAppender log4j.appender.A2.file = d:/mylog.log log4j.appender.A2.layout=org.apache.log4j.PatternLayout log4j.appender.A2.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# This is the configuring for logging displayed in the Application Server # TRACE DEBUG INFO WARN ERROR log4j.rootCategory=DEBUG, logfile,stdout #stdout configure log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern= %d %p [%c] - <%m>%n #logfile configure log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender log4j.appender.logfile.File=e:/logs/mybatis.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern= %d %p [%c] - <%m>%n # Changing the log level to DEBUG when debug log4j.logger.cn.itcast.mybatis.UserMapper=TRACE # Control logging for other open source packages log4j.logger.org.hibernate=ERROR
通常情况下,会导入commons-logging 包,该包中,提供了日志类接口,除了Log4J外,还可以使用别的日志技术