1 关于log4j的文章---粗略看了一遍,不错!
出处给忘了好像是下面这个:
http://dev2dev.bea.com.cn/bbs/servlet/d2dservlet/download/124-14026-77822-650/深入学习log4j.pdf
深入学习log4j
李翔
内容:
一,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平台为"/r/n",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
| |
3 关于log4j的文章---粗略看了一遍,不错!
2004-05-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:/develop/log/error.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
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:
"lixiang"
注:使用此方法封装log4j的操作,可以使记录日志变得更方便.唯一不足的是无法返回当
前类的相关信息.
最后说明:
关于对日志进行处理的技术有好多,如jdk 1.4 logging,avalon logkit,jakarta 的log4j
,jakarta的commons-logging等.做的最好的是commons-logging.下面对其做一介绍:
the jakarta commons logging (jcl) provides a log interface that is
intended to be both light-weight and independent of numerous logging
toolkits. it provides the middleware/tooling developer with a simple logging
abstraction, that allows the user (application developer) to plug in a specific
logging implementation.
the jakarta commons logging provides a log interface with
thin-wrapper implementations for other logging tools, including
log4j , avalon logkit , the avalon framework's logging
infrastructure, jdk 1.4, and an implementation of jdk 1.4 logging
apis (jsr-47) for pre-1.4 systems. the interface maps closely to
log4j and logkit.
闽公网安备 35060202000074号