log4j日志在java控制台输出,简单实用
1、log4j输出有2中方式:第一种是将日志信息保存在一个文本当中;第二种是输出到控制台中。下面介绍第二种方式。
2、在控制台输出log4j日志信息,是开发项目中常用的也是比不可少的也是必须会的一个技术点。
3、2种log4j文件加载方式,以下代码可以直接运用在项目当中。理论东西就不多说了直接看代码。几个步骤就完成。
java QQ群:180258862
4、准备log4j-contrl.propertes 文件,其目录为src/log4j-contrl.propertes:
log4j.appender.encoding = UTF-8
log4j.rootLogger=INFO,CONSOLE,APPLOG,ERROR,ERRORLOG
#log4j.rootLogger=ERROR,ERRORLOG
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c %x - %m%n
log4j.appender.APPLOG=org.apache.log4j.DailyRollingFileAppender
log4j.appender.APPLOG.Append=true
log4j.appender.APPLOG.DatePattern='_'yyyyMMdd'.log'
log4j.appender.APPLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.APPLOG.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c %x - %m%n
log4j.appender.APPLOG.File=/data1/logs/tomcat/sync/AppAccessLog
log4j.appender.ADMINLOG=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ADMINLOG.Append=true
log4j.appender.ADMINLOG.DatePattern='_'yyyyMMdd'.log'
log4j.appender.ADMINLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.ADMINLOG.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c %x - %m%n
log4j.appender.ADMINLOG.File=/data1/logs/tomcat/sync/AdminAccessLog
log4j.appender.ERRORLOG=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ERRORLOG.Threshold=ERROR
log4j.appender.ERRORLOG.Append=true
log4j.appender.ERRORLOG.DatePattern='_'yyyyMMdd'.log'
log4j.appender.ERRORLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.ERRORLOG.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c %x - %m%n
log4j.appender.ERRORLOG.File=/data1/logs/tomcat/sync/AppErrorLog
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.logger.java.sql.ResultSet = DEBUG
5、创建一个servlet来启动日志文件,当启动服务器时进行加载并初始化日志文件:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* log4j控制台文件输出,初始化配置文件
* @author Administrator
*
*/
public class Log4jInit extends HttpServlet {
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
public void init() throws ServletException {
String prefix = getServletContext().getRealPath("/");
String file = getServletConfig().getInitParameter("log4j"); //是web.xml中的参数
if (file != null) {
PropertyConfigurator.configure(prefix + file);
}
Logger log = Logger.getLogger(Log4jInit.class);
log.info("Logg4j日志已经初始化。");
}
}
6、在web.xml中配置servlet并初始化该servelt文件:
<servlet>
<servlet-name>Log4jInit</servlet-name>
<servlet-class>com.java.log.Log4jInit</servlet-class>
<init-param>
<param-name>log4j</param-name>
<param-value>WEB-INF/classes/log4j-contrl.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Log4jInit</servlet-name>
<url-pattern>/log/logfj</url-pattern>
</servlet-mapping>
7、测试log4j日志(这里测试只能通过web形式访问在能输出日志,在main方法中貌似不行但是可以通过下面介绍的方法(序列9)可以):
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Log4j extends HttpServlet {
private static final transient Logger log = Logger.getLogger(Log4j .class);
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
log.info("记录日志信息,将在控制台输出");
log.error("可以记录错误信息,输出字体为控制");
out.flush();
out.close();
}
public void init() throws ServletException {
}
}
8、输出结果:
2013-05-01 14:08:55 INFO [http-9090-1] com.java.md.KeyMDF - 记录日志信息,将在控制台输出
2013-05-01 14:08:55 ERROR [http-9090-1] com.java.md.KeyMDF - 可以记录错误信息,输出字体为控制
9、第二种方式加载log4j-contrl.propertes文件:
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class TestLog4j {
private static final transient Logger log = Logger.getLogger(TestLog4j .class);
public static void main(String[] args)throws InvalidKeyException, IllegalBlockSizeException, NoSuchAlgorithmException, UnsupportedEncodingException, BadPaddingException, NoSuchPaddingException {
PropertyConfigurator.configure("src/log4j.properties");
log.info("记录日志信息,将在控制台输出");
log.error("可以记录错误信息,输出字体为控制");
}
}