内容:
一,Log4J配置文件的学习
二,Log4J数据库
三,Log4J封装
一,Log4J配置文件学习:
Log4j支持两种配置文件格式,一种是XML格式的文件,一种是Java特性文件(键=值).
下面我们首先介绍使用Java特性文件做为配置文件的方法:
分析一个配置文件log4j.properties
log4j.rootCategory=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
说明:
①log4j.rootCategory = [ level ] , appenderName, appenderName,
其中,level 是日志记录的优先级,分为OFF,FATAL,ERROR,WA R N,INFO,DEBUG,
ALL或者您定义的级别.Log4j建议只使用四个级别,优先级从高到低分别是ERROR,
WA R N,INFO,DEBUG.通过在这里定义的级别,您可以控制到应用程序中相应级别的日
志信息的开关.比如在这里定义了INFO级别,则应用程序中所有DEBUG级别的日志信息
将不被打印出来.appenderName就是指定日志信息输出到哪个地方.您可以同时指定多个
输出目的地. ②配置日志信息输出目的地Appender,其语法为
log4j.appender.appenderName = fully.qualified.name.of.appender.class
log4j.appender.appenderName.option1 = value1
log4j.appender.appenderName.option = valueN
其中,Log4j提供的appender有以下几种:
org.apache.log4j.ConsoleAppender(控制台),
org.apache.log4j.FileAppender(文件),
org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件),
org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件),
org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
③配置日志信息的格式(布局),其语法为:
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1 = value1
log4j.appender.appenderName.layout.option = valueN
其中,Log4j提供的layout有以下几种:
org.apache.log4j.HTMLLayout(以HTML表格形式布局),
org.apache.log4j.PatternLayout(可以灵活地指定布局模式),
org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串),
org.apache.log4j.TTCCLayout(包含日志产生的时间,线程,类别等等信息)
④Log4J采用类似C语言中的printf函数的打印格式格式化日志信息,打印参数如下:
%m 输出代码中指定的消息
%p 输出优先级,即DEBUG,INFO,WA R N,ERROR,FATAL
%r 输出自应用启动到输出该log信息耗费的毫秒数
%c 输出所属的类目,通常就是所在类的全名
%t 输出产生该日志事件的线程名
%n 输出一个回车换行符,Windows平台为"rn",Unix平台为"n"
%d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,
比如:%d{yyy MMM dd HH:mm:ss,SSS},输出类似:2002年10月18日 22:10:28,921
%l 输出日志事件的发生位置,包括类目名,发生的线程,以及在代码中的行数.
对上面log4j.properties配置文件的一个应用;
package log4j;
import org.apache.log4j.*;
// How to use log4j
public class TestLogging {
// Initialize a logging category. Here, we get THE ROOT CATEGORY
//static Category cat = Category.getRoot();
// Or, get a custom category
static Category cat = Category.getInstance(TestLogging.class.getName());
// From here on, log away! Methods are: cat.debug(your_message_string),
// cat.info(...), cat.warn(...), cat.error(...), cat.fatal(...)
public static void main(String args[]) {
// Try a few logging methods
PropertyConfigurator.configure ( "log4j.properties" ) ;
cat.debug("Start of main()");
cat.info("Just testing a log message with priority set to INFO");
cat.warn("Just testing a log message with priority set to WARN");
cat.error("Just testing a log message with priority set to ERROR");
cat.fatal("Just testing a log message with priority set to FATAL");
// Alternate but INCONVENIENT form
cat.log(Priority.DEBUG, "Calling init()");
new TestLogging().init();
}
public void init() {
java.util.Properties prop = System.getProperties();
java.util.Enumeration enum = prop.propertyNames();
cat.info("***System Environment As Seen By Java***");
cat.debug("***Format: PROPERTY = VALUE***");
while (enum.hasMoreElements()) {
String key = (String) enum.nextElement();
cat.info(key + " = " + System.getProperty(key));
}
}
}
xml格式的log4j配置文件概述
xml格式的log4j配置文件需要使用 org.apache.log4j.html.DOMConfigurator.configure()方法来
读入.对xml文件的语法定义可以在log4j的发布包中找到:org/apache/log4j/xml /log4j.dtd.
Xml的一个配置文件:sample1.xml
说明:
①xml配置文件的头部包括两个部分:xml声明和dtd声明.头部的格式如下:
②log4j:configuration (root element)
xmlns:log4j [#FIXED attribute]: 定义log4j的名字空间,取定值"http://jakarta.apache.org/log4j/"
appender [* child] : 一个appender子元素定义一个日志输出目的地
logger [* child] : 一个logger子元素定义一个日志写出器
root [ child] : root子元素定义了root logger
源代码:
package exampleslog4j.xml;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.log4j.Category;
import java.net.*;
public class XMLSample {
static Category cat = Category.getInstance(XMLSample.class.getName());
public
static
void main(String argv[]) {
if(argv.length == 1)
init(argv[0]);
else
Usage("Wrong number of arguments.");
sample();
}
static
void Usage(String msg) {
System.err.println(msg);
System.err.println( "Usage: java " + XMLSample.class.getName() +
"configFile");
System.exit(1);
}
static
void init(String configFile) {
DOMConfigurator.configure(configFile);
}
static
void sample() {
int i = -1;
Category root = Category.getRoot();
cat.debug("Message " + ++i);
cat.warn ("Message " + ++i);
cat.error("Message " + ++i);
Exception e = new Exception("Just testing");
cat.debug("Message " + ++i, e);
}
}
执行后的效果:
2004-05-24 22:07:28,352 DEBUG [main] xml.XMLSample (XMLSample.java:55) - Message 0
2004-05-24 22:07:28,352 WARN [main] xml.XMLSample (XMLSample.java:56) - Message 1
24 22:07:28,362 ERROR [main] xml.XMLSample (XMLSample.java:57) - Message 2
2004-05-24 22:07:28,362 DEBUG [main] xml.XMLSample (XMLSample.java:59) - Message 3
java.lang.Exception: Just testing
at exampleslog4j.xml.XMLSample.sample(XMLSample.java:58)
at exampleslog4j.xml.XMLSample.main(XMLSample.java:36)
二,Log4J对数据库的操作:
其目的就是把日志信息写入数据库以方便开发人员和测试人员查询.
下面是写入数据库的配置文件:log4j.properties
log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DATABASE.URL=jdbc:oracle:thin:@192.168.0.1:1521:siemen
log4j.appender.DATABASE.driver= oracle.jdbc.driver.OracleDriver
log4j.appender.DATABASE.user=system
log4j.appender.DATABASE.password=css12345
log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES ('[framework] %d
- %c -%-4r [%t] %-5p %c %x - %m%n')
log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t]
%-5p %c %x - %m%n
log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A1.File=SampleMessages.log4j
log4j.appender.A1.DatePattern=yyyyMMdd-HH'.log4j'
log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayout
对其应用的源文件:
package database.servlet;
import java.io.File;
import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Vector;
import java.sql.Driver;
import java.sql.DriverManager;
// import servlet packages
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
// import log4j packages
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class SetupServlet extends HttpServlet{
public void init(ServletConfig config) throws ServletException{
super.init(config);
// first thing to do, is to set up the Driver that we might be using
// in case of JDBCAppender
try{
//Driver d =(Driver)(Class.forName("org.gjt.mm.mysql.Driver").newInstance());
Driver d = (Driver)(Class.forName("oracle.jdbc.driver.OracleDriver").newInstance());
DriverManager.registerDriver(d);
//加载JDBC驱动程序,当准备将日志记录到数据库的时候可以使用
}catch(Exception e){ System.err.println(e); }
// next load up the properties
//启动时从web.xml中获得配置文件的信息
String props = config.getInitParameter("props");
if(props == null || props.length() == 0 ||
!(new File(props)).isFile()){
System.err.println(
"ERROR: Cannot read the configuration file. " +
"Please check the path of the config init param in web.xml");
throw new ServletException();
}
}
public void destroy(){
super.destroy();
}
}
三,Log4J的封装:
配置文件:log4j.properties
log4j.rootLogger=DEBUG, A2, A1
log4j.appender.A2=org.apache.log4j.RollingFileAppender
log4j.appender.A2.File=C:developlogerror.log
log4j.appender.A2.Append=true
log4j.appender.R.MaxFileSize=10000KB
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
4 关于log4j的文章---粗略看了一遍,不错!
log4j.appender.A2.layout.ConversionPattern=[%-5p][%t] %d{yyyy-MM-dd
HH:mm:ss,SSS} message:%m%n
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
#Pattern to output the caller's file name and line number.
#log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Print the date in ISO 8601 format
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p - %m%n
EncapsulationLog4J.java //Log4j的实现类
package com.cn.lx;
/**
*
Title:
*
Description:
*
Copyright: Copyright © 2004 lixiang
*
Company:http://www.css.com.cn/
* @author lixiang
* @version 1.0
*/
import org.apache.log4j.*;
import java.io.*;
import java.util.*;
/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class EncapsulationLog4J
{
public static final String PROFILE = "log4j.properties";
/**
* Holds singleton instance
*/
private static EncapsulationLog4J impl;
static
{
impl = new EncapsulationLog4J();
}
private Logger log4j;
/**
* prevents instantiation
*/
private EncapsulationLog4J()
{
log4j = LogManager.getLogger(EncapsulationLog4J.class);
try
{
Properties pro = new Properties();
InputStream is = getClass().getResourceAsStream(PROFILE);
pro.load(is);
PropertyConfigurator.configure(pro);
}
catch(IOException e)
{
BasicConfigurator.configure();
e.printStackTrace();
}
}
public void log(String level,Object msg)
{
log(level,msg,null);
}
public void log(String level,Throwable e)
{
log(level,null,e);
}
public void log(String level,Object msg,java.lang.Throwable e)
{
if(log4j != null)
{
log4j.log((Priority)Level.toLevel(level),msg,e);
}
}
/**
* Singleton Pattern
*/
static public EncapsulationLog4J getInstance()
{
return impl;
}
}
Log.java //记录Log使用类
package com.cn.lx;
/**
*
Title:
*
Description:
*
Copyright: Copyright © 2004 lixiang
*
Company: http://www.css.com.cn/
* @author lixiang
* @version 1.0
*/
public class Log
{
private static EncapsulationLog4J log = EncapsulationLog4J.getInstance();
/**
*
*/
public Log()
{
//super();
}
public static void logError(String msg)
{
log.log("ERROR",msg);
}
public static void logError(Throwable e)
{
log.log("ERROR",null,e);
}
public static void logWarn(String msg)
{
log.log("WARN",msg);
}
public static void logWarn(Throwable e)
{
log.log("WARN",null,e);
}
public static void logInfo(String msg)
{
log.log("INFO",msg);
}
public static void logInfo(Throwable e)
{
log.log("INFO",null,e);
}
public static void logDebug(String msg)
{
log.log("DEBUG",msg);
}
public static void logDebug(Throwable e)
{
log.log("DEBUG",null,e);
}
}
TestLog.java //调用Log类
package com.cn.lx;
public class TestLog{
public static void main(String[] args) {
Log test = new Log();
test.logDebug("DEBUG");
test.logInfo("INFO");
test.logWarn("WARN");
test.logError("ERROR");
try
{
int i = Integer.parseInt("lixiang");
}catch(Exception e)
{
test.logDebug(e.toString());
test.logInfo(e.toString());
test.logWarn(e.toString());
test.logError(e.toString());
}
}
}
执行后的日志信息:
2004-05-26 21:16:16,474 [main] DEBUG - DEBUG
2004-05-26 21:16:16,484 [main] INFO - INFO
2004-05-26 21:16:16,484 [main] WARN - WARN
2004-05-26 21:16:16,484 [main] ERROR - ERROR
需要什么来搜一搜吧 so.bitsCN.com
2004-05-26 21:16:16,484 [main] DEBUG - java.lang.NumberFormatException: For input string:
"lixiang"
2004-05-26 21:16:16,484 [main] INFO - java.lang.NumberFormatException: For input string:
"lixiang"
2004-05-26 21:16:16,484 [main] WARN - java.lang.NumberFormatException: For input string:
"lixiang"
2004-05-26 21:16:16,484 [main] ERROR - java.lang.NumberFormatException: For input string:
font-siz