---
title: "Log4j示例"
author: "cjc"
date: "2008-04-20T14:48:00Z"
tags: []
slug: "log4j"
draft: false
lastmod: "2008-04-20T14:48:00Z"
id: 298646
url: "https://cjc.iteye.com/blog/298646"
---

&lt;!-- ========================== 自定义输出格式说明================================ --&gt;  
 &lt;!-- %p 输出优先级，即DEBUG，INFO，WARN，ERROR，FATAL --&gt;  
 &lt;!-- #%r 输出自应用启动到输出该log信息耗费的毫秒数  --&gt;  
 &lt;!-- #%c 输出所属的类目，通常就是所在类的全名 --&gt;  
 &lt;!-- #%t 输出产生该日志事件的线程名 --&gt;  
 &lt;!-- #%n 输出一个回车换行符，Windows平台为“\\r\\n”，Unix平台为“\\n” --&gt;  
 &lt;!-- #%d 输出日志时间点的日期或时间，默认格式为ISO8601，也可以在其后指定格式，比如：%d{yyy MMM dd HH:mm:ss,SSS}，输出类似：2002年10月18日 22：10：28，921  --&gt;  
 &lt;!-- #%l 输出日志事件的发生位置，包括类目名、发生的线程，以及在代码中的行数。举例：Testlog4.main(TestLog4.java:10)  --&gt;  
 &lt;!-- ========================================================================== --&gt;

配置文件可以是：.properties或者是.xml文件。具体怎么配置这里不做详细介绍，只是为了提供例子

第一种是.properties文件方法：

下面是初始化Log4j：

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)package org.cjj.config.properties;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import org.apache.log4j.PropertyConfigurator;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)public class Log4jPropertiesConfig  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    /\** \*//\**  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * @param args  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)     \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private static Log4jPropertiesConfig    instance;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    /\** \*//\**  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * 读取配置文件  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)     \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private Log4jPropertiesConfig()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        PropertyConfigurator.configure(Log4jPropertiesConfig.class.getResource("log4j.properties"));  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    /\** \*//\**  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * @return 单例模式  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)     \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public static synchronized Log4jPropertiesConfig initia()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        if (instance == null)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            return new Log4jPropertiesConfig();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return instance;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)

下面是配置文件：

##日志级别，以及日志类型名称  
#如果为log4j.rootLogger=WARN, 则意味着只有WARN,ERROR,FATAL  
#被输出，DEBUG,INFO将被屏蔽掉.  
log4j.rootLogger=INFO, A1, A2

\# A1 is set to be ConsoleAppender sending its output to System.out  
#log4j中Appender有几层如控制台、文件、GUI组件、甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等  
#ConsoleAppender输出到控制台  
log4j.appender.A1=org.apache.log4j.ConsoleAppender

\# A1 使用的输出布局，其中log4j提供4种布局. org.apache.log4j.HTMLLayout（以HTML表格形式布局）  
#org.apche.log4j.PatternLayout（可以灵活地指定布局模式），  
#org.apache.log4j.HTMLLayout（以HTML表格形式布局），  
#org.apache.log4j.SimpleLayout（包含日志信息的级别和信息字符串），  
#org.apache.log4j.TTCCLayout（包含日志产生的时间、线程、类别等等信息）  
log4j.appender.A1.layout=org.apache.log4j.PatternLayout

\# The conversion pattern consists of date in ISO8601 format, level,  
\# thread name, logger name truncated to its rightmost two components  
\# and left justified to 17 characters, location information consisting  
\# of file name (padded to 13 characters) and line number, nested  
\# diagnostic context, the and the application supplied message  
\## 输出格式  
#灵活定义输出格式 具体查看log4j javadoc org.apache.log4j.PatternLayout  
#d 时间 ....  
log4j.appender.A1.layout.ConversionPattern=%d %-5p \[%t] %-17c{2} (%13F:%L) %3x - %m%n

\# Appender A2 writes to the file "testlog".  
#A2 输出到文件 RollingFileAppender的扩展，可以提供一种日志的备份功能。  
log4j.appender.A2=org.apache.log4j.RollingFileAppender  
#日志文件的大小  
log4j.appender.A2.MaxFileSize=1MB  
\# 保存5个备份文件  
log4j.appender.A2.MaxBackupIndex=5  
log4j.appender.A2.layout=org.apache.log4j.TTCCLayout  
##设置File参数：日志输出文件名  
log4j.appender.A2.File=testlog.log

\# Truncate 'test' if it aleady exists.  
log4j.appender.A2.Append=false

\# Appender A2 uses the PatternLayout.  
log4j.appender.A2.layout=org.apache.log4j.PatternLayout  
log4j.appender.A2.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} %-5r %-5p \[%t] %c{2} - %m%n

第二种是使用XML文件：

初始化Log4j：

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)package org.cjj.config.xml;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import org.apache.log4j.xml.DOMConfigurator;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)public class Log4jXMLConfig  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    /\** \*//\**  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * @param args  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)     \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private static Log4jXMLConfig    instance;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private Log4jXMLConfig()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        DOMConfigurator.configure(Log4jXMLConfig.class.getResource("log4j.xml"));  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public static synchronized Log4jXMLConfig initia()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        if (instance == null)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            return new Log4jXMLConfig();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return instance;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)

下面是配置文件：

&lt;?xml version="1.0" encoding="UTF-8" ?&gt;  
&lt;!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"&gt;  
&lt;log4j:configuration xmlns:log4j="[http://jakarta.apache.org/log4j/](http://jakarta.apache.org/log4j/)"&gt;

  &lt;!-- 输出到日志文件 --&gt;  
 &lt;appender name="filelog"  
  class="org.apache.log4j.RollingFileAppender"&gt;  
  &lt;!-- 设置File参数：日志输出文件名 --&gt;  
  &lt;!-- D:/LOG/com.log --&gt;  
  &lt;param name="File" value="out.log" /&gt;  
  &lt;!-- 设置是否在重新启动服务时，在原有日志的基础添加新日志 --&gt;  
  &lt;param name="Append" value="true" /&gt;  
  &lt;!-- 设置文件大小 --&gt;  
  &lt;param name="MaxFileSize" value="100KB" /&gt;  
  &lt;!-- 设置文件大小 --&gt;  
  &lt;param name="MaxBackupIndex" value="10" /&gt;  
  &lt;!-- 设置输出文件项目和格式 --&gt;  
  &lt;layout class="org.apache.log4j.PatternLayout"&gt;  
   &lt;param name="ConversionPattern" value="%p (%c:%L)- %m%n" /&gt;  
  &lt;/layout&gt;  
 &lt;/appender&gt;

 &lt;!-- 输出到控制台中 --&gt;  
 &lt;appender name="console" class="org.apache.log4j.ConsoleAppender"&gt;  
  &lt;layout class="org.apache.log4j.PatternLayout"&gt;  
   &lt;param name="ConversionPattern"  
    value="%-5p: %m%n" /&gt;  
   &lt;!-- "%-5p: \[%t] \[%c{3}.%M(%L)] | %m%n" --&gt;  
  &lt;/layout&gt;  
 &lt;/appender&gt;

 &lt;!-- 设置类名限制输出的通道 --&gt;  
 &lt;category name="com.test1" additivity="false"&gt;  
  &lt;level value="ERROR" /&gt;  
  &lt;appender-ref ref="console" /&gt;  
  &lt;appender-ref ref="filelog" /&gt;  
 &lt;/category&gt;

 &lt;!-- 设置类名限制输出的通道 --&gt;  
 &lt;category name="org.springframework" additivity="false"&gt;  
  &lt;level value="OFF" /&gt;  
  &lt;appender-ref ref="console" /&gt;  
  &lt;appender-ref ref="filelog" /&gt;  
 &lt;/category&gt;

    &lt;!-- 设置类名限制输出的通道 --&gt;  
 &lt;category name="org.cjj" additivity="false"&gt;  
  &lt;level value="INFO" /&gt;  
  &lt;appender-ref ref="console" /&gt;  
  &lt;appender-ref ref="filelog" /&gt;  
 &lt;/category&gt;

 &lt;!-- 设置接收所有输出的通道 --&gt;  
 &lt;root&gt;  
  &lt;level value="INFO" /&gt;  
  &lt;appender-ref ref="console" /&gt;  
  &lt;appender-ref ref="filelog" /&gt;  
 &lt;/root&gt;

&lt;/log4j:configuration&gt;

这个测试工程可以在下面下载：[下载](http://download.csdn.net/user/ice_spar/)（还有个方案读取XML文件时不需要模式（schema）验证,也在这个测试工程里面）