一个配置比较全的log4j.xml文件(一)
一个配置比较全的log4j.xml文件(一)
宝塔镇河妖 发表于4年前
一个配置比较全的log4j.xml文件(一)
  • 发表于 4年前
  • 阅读 77
  • 收藏 1
  • 点赞 1
  • 评论 0

移动开发云端新模式探索实践 >>>   

获取logger
Logger.getRootLogger() 获取根logger
Logger.getLogger(String name)获取子logger
Logger.getLogger(Class clazz)或
Logger.getLogger(clazz.getName())

设置日志级别(.setLevel(int,Exception))
Level.ALL打开所有日志
Level.DEBUG 用于调试
Level.INFO 用于运行过程
Level.WARN 用于潜在的错误
Level.ERROR 用于错误事件
Level.FATAL 用于严重错误时间
Level.OFF 关闭所有日志

输出端Appender(.addAppender(Appender).setAdditivity(boolean additive)是否覆盖)
org.apache.log4j.ConsoleAppender 输出到控制台
targer:
ConsoleAppender.SYSTEM_OUT(Default)
ConsoleAppender.SYSTEM_ERR
public ConsoleAppender(Layout)
public ConsoleAppender(Layout,String targer)
org.apache.log4j.FileAppender 输出到文件
public FileAppender(Layout,String fileName)
public FileAppender(Layout,String fileName,boolean append)是否覆盖
org.apache.log4j.DailyRollingFileAppender 输出到文件,每天一个新文件
org.apache.log4j.RollingFileAppender 输出到文件,自动新增改名
public RollingFileAppender(Layout,String fileName)
void setMaxBackupIndex(int index) 设置日志文件最大备份数
void setMaximumFileSize(long size) 设置日志文件最大尺寸
org.apache.log4j.WriterAppender 流格式输出到任意地方
org.apache.log4j.JDBCAppender 输出到数据库

日志格式化(Layout)
ConversionPattern参数的格式含义 

%c 输出日志信息所属的类的全名 
%d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy-MM-dd HH:mm:ss },输出类似:2002-10-18- 22:10:28 
%f 输出日志信息所属的类的类名 
%l 输出日志事件的发生位置,即输出日志信息的语句处于它所在的类的第几行 
%m 输出代码中指定的信息,如log(message)中的message 
%n 输出一个回车换行符,Windows平台为“rn”,Unix平台为“n” 
%p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL。如果是调用debug()输出的,则为DEBUG,依此类推 
%r 输出自应用启动到输出该日志信息所耗费的毫秒数 
%t 输出产生该日志事件的线程名

public PatternLayout() 使用默认设置DEFAULT_CONVERSION_PATTERN 只打印信息
public PatternLayout(String)使用自定义的pattern构造一个PatternLayout
void setConversionPattern(String) 设置日志格式
HTMLLayout
SimpleLayout


5.
1.BasicConfigurator.configure()
PatternLayout p = new PatternLayout("%p [%t] %c (%F:%L) - %m%n"); 
ConsoleAppender a = new ConsoleAppender(p,ConsoleAppender.SYSTEM_OUT); 
root.addAppender(a); 
rootLogger.setLevel(Level.DEBUG); 
2.PropertyConfigurator.configure("/help/example.properties")
String resource = "/help/example.properties";
URL configFileResource = Log4J.class.getResource(resource);
PropertyConfigurator.configure(configFileResource);
3.DOMConfigurator.configure("/help/example.xml")
xml declaration and dtd 

log4j:configuration 

+-- appender (name, class) 
| | 
| +-- param (name, value) 
| +-- layout (class) 
| | 
| +-- param (name, value) 
+-- logger (name, additivity) 
| | 
| +-- level (class, value) 
| | | 
| | +-- param (name, value) 
| +-- appender-ref (ref) 
+-- root 

+-- param (name, class) 
+-- level 
| | 
| +-- param (name, value) 
+-- appender-ref (ref)


0.log4j.properties模板
log4j.rootLogger=info,CONSOLE,RFILE,FILE,DB 设置级别和三个输出端
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= %4p [%t] (%F:%L) - %m%n

log4j.appender.FILE=org.apache.log4j.FileAppender 
log4j.appender.FILE.File=/help/my.properties 目标文件
log4j.appender.FILE.Append=false 是否追加
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout 布局模式
log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss}:%p %c:%L - %m%n 格式化布局

log4j.appender.RFILE=org.apache.log4j.RollingFileAppender 
log4j.appender.RFILE.File=/help/my.properties 目标文件
log4j.appender.RFILE.MaxFileSize=1KB 最大长度
log4j.appender.RFILE.MaxBackupIndex=3 最多备份
log4j.appender.RFILE.layout=org.apache.log4j.PatternLayout 布局模式
log4j.appender.RFILE.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss}:%p %c:%L - %m%n 格式化布局

log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender 
log4j.appender.DB.URL=jdbc:oracle:thin:@127.0.0.1:1521:mumu URL
log4j.appender.DB.driver=oracle.jdbc.driver.OracleDriver 驱动
log4j.appender.DB.user=liulibo 用户名
log4j.appender.DB.password=liulibo 密码
log4j.appender.DB.layout=org.apache.log4j.PatternLayout 布局模式
log4j.appender.DB.layout.ConversionPattern=insert into log4j(createdate,thread,level_,class,message) values(\'%d\',\'%t\',\'%-5p\',\'%c\',\'%m\')

create table log4j(createdate varchar2(32),thread varchar2(32),level_ varchar2(32),class varchar2(32),message varchar2(32));

0.XML模板

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration> <appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd hh:mm:ss}:%p %t %c - %m%n"/> </layout> </appender> <appender name="RollingFileAppender" class="org.apache.log4j.RollingFileAppender"> <param name="Append" value="false"/> <param name="MaxFileSize" value="1KB"/> <param name="File" value="dom/my.log"/> <param name="MaxBackupIndex" value="3"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd hh:mm:ss}:%p %t %c - %m%n"/> </layout> </appender> <appender name="JDBCAppender" class="org.apache.log4j.jdbc.JDBCAppender"> <param name="URL" value="jdbc:oracle:thin:@127.0.0.1:1521:mumu"/> <param name="user" value="liulibo"/> <param name="password" value="liulibo"/> <param name="driver" value="oracle.jdbc.driver.OracleDriver"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="insert into log4j(createdate,thread,level_,class,message) values(\'%d\',\'%t\',\'%-5p\',\'%c\',\'%m\')"/> </layout> </appender> <root> <priority value ="debug" /> <appender-ref ref="ConsoleAppender"/> <appender-ref ref="RollingFileAppender"/> <appender-ref ref="JDBCAppender"/> </root> </log4j:configuration>

应用
web.xml


<context-param>
<param-name>props</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<listener>
<listener-class>cart.listener.SCServletContextListener</listener-class>
</listener>



初始化方法中添加



private void initLog4j(ServletContext context){
String prefix = context.getRealPath("/");
System.out.println("prefix:"+prefix);
String props = context.getInitParameter("props");
if(props != null) {
PropertyConfigurator.configure(prefix+props);
}
Logger logger = Logger.getLogger(SCServletContextListener.class); 
}



<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration threshold="debug"
xmlns:log4j='http://jakarta.apache.org/log4j/'>

<appender name="console.CONSOLE"
class="org.apache.log4j.ConsoleAppender">
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<!--
<param name="ConversionPattern" value="%d{HH:mm:ss}[%C.%M(%L)-%p] %m%n"/>
-->
<param name="ConversionPattern" value="%d{HH:mm:ss}[%C(%L)-%p] %m%n"/>
</layout>
</appender>

<appender name="file.text.SYSFILE"
class="org.apache.log4j.RollingFileAppender">
<param name="threshold" value="error" />
<param name="file" value="/juyee.log" />
<param name="maxFileSize" value="2MB" />
<param name="maxBackupIndex" value="5" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%-d{yyyy-MM-dd HH:mm:ss.SSS} [%p]-[%c] %m%n" />
</layout>
</appender>
<appender name="file.text.DATE_FILE"
class="org.apache.log4j.DailyRollingFileAppender">
<param name="threshold" value="debug" />
<param name="file" value="/juyee.log" />
<param name="append" value="true" />
<param name="datePattern" value="'.'yyyy-MM-dd" />
<!-- each hour
<param name="DatePattern" value="'.'yyyy-MM-dd-HH"/>
-->
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c] %m%n" />
</layout>
</appender>
<appender name="file.text.APPFILE"
class="org.apache.log4j.RollingFileAppender">
<param name="threshold" value="error" />
<param name="file" value="${webapp.root}/WEB-INF/logs/juyee.log" />
<param name="maxFileSize" value="1024KB" />
<param name="maxBackupIndex" value="5" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d %-5p %c - %m [%t] (%F:%L)%n" />
</layout>
</appender>
<appender name="file.html.HTML"
class="org.apache.log4j.RollingFileAppender">
<param name="threshold" value="error" />
<param name="file" value="/juyee-log.html" />
<param name="maxFileSize" value="1024KB" />
<param name="maxBackupIndex" value="5" />
<param name="append" value="true" />
<layout class="org.apache.log4j.HTMLLayout" />
</appender>
<appender name="file.xml.XML"
class="org.apache.log4j.RollingFileAppender">
<param name="threshold" value="error" />
<param name="file" value="/juyee-log.xml" />
<param name="maxFileSize" value="1024KB" />
<param name="maxBackupIndex" value="5" />
<param name="append" value="true" />
<layout class="org.apache.log4j.xml.XMLLayout" />
</appender>

<appender name="mail.MAIL" class="org.apache.log4j.net.SMTPAppender">
<param name="threshold" value="debug"/>
<!--
<param name="threshold" value="fatal"/>
-->
<param name="BufferSize" value="10"/>
<param name="From" value="yangguanjun@justonetech.com"/>
<param name="SMTPHost" value="www.justonetech.com"/>
<param name="Subject" value="juyee-log4jMessage"/>
<param name="To" value="yangguanjun@justonetech.com"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss.SSS} [%p]-[%c] %m%n" />
</layout>
</appender>

<appender name="remote.CHAINSAW"
class="org.apache.log4j.net.SocketAppender">
<param name="threshold" value="fatal" />
<param name="remoteHost" value="localhost" />
<param name="port" value="4445" />
<param name="locationInfo" value="true" />
</appender>

<category name="com.juyee" additivity="true">
<priority value="info" />
<appender-ref ref="console.CONSOLE" />
<!--
<appender-ref ref="file.text.DATE_FILE" />
-->
</category>

<category name="com.co" additivity="true">
<priority value="debug" />
<appender-ref ref="console.CONSOLE" />
<appender-ref ref="file.text.DATE_FILE" />
</category>

<category name="org" additivity="true">
<priority value="WARN" />
<appender-ref ref="console.CONSOLE" />
<!--
<appender-ref ref="file.text.DATE_FILE" />
-->
</category>

<root>
<!--
<level value="trace" />
<level value="debug" />
<level value="info" />
<level value="warn" />
<level value="error" />
<level value="fatal" />
<appender-ref ref="console.CONSOLE" />
<appender-ref ref="file.text.DATE_FILE"/>
-->
</root>
</log4j:configuration>



配置输出多个log文件


log4j 有两种配置方法,大家熟知的是properties文件但是最近的项目实施中,每次去用户那里装系统,都要苦恼于log文件放在不同位置,要改property文件就要重打jar包,麻烦的紧。而如果采用xml配置的方法,直接放在WEB-INFO下,要修改路径,很方便。查了些资料,终于把系统的log4j改成在xml中配置啦。


附:log4j的API http://logging.apache.org/log4j/docs/api/index.html
log4i.xml 文件


<?xml version="1.0" encoding="GB2312" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="FILE"
class="org.apache.log4j.RollingFileAppender">
<!-- 设置通道file和输出方式:org.apache.log4j.RollingFileAppender -->
<param name="File" value="D:/zhaotj/all.output.log" /><!-- 设置File参数:日志输出文件名 -->
<param name="Append" value="true" /><!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 -->
<param name="MaxBackupIndex" value="10" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%p (%c:%L)- %m%n" /><!-- 设置输出文件项目和格式 -->
</layout>
</appender>

<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<!-- 设置监视器输出方式 -->
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%-4r [%t] %-5p %c %x - %m%n" />
</layout>
<!--滤镜设置输出的级别-->
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="info" />
<param name="levelMax" value="info" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>

<root><!-- 设置接收所有输出的通道 -->
<priority value="info" />
<appender-ref ref="FILE" /><!-- 与前面的通道id相对应 -->
<appender-ref ref="STDOUT" />
</root>

</log4j:configuration>



建好xml文件后 要写一个servlet类继承actionservlet,当工程初始化时自动加载xml配置文件



package com.asiainfo;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.struts.action.ActionServlet;

public class ExtendedActionServlet extends ActionServlet {
private Log log = LogFactory.getLog(this.getClass().getName());

public ExtendedActionServlet() {}

public void init() throws ServletException {
log.info(
"Initializing, My MyActionServlet init this System's Const Variable");
String prefix = this.getServletConfig().getServletContext().getRealPath(
"/");//读取项目的路径
String file = this.getServletConfig().getInitParameter("log4j");
//读取log4j相对路径
String filePath = prefix + file;
DOMConfigurator.configure(filePath);//加载.xml文件 
log.info("Initializing, end My Init");
super.init();//应用了struts,此方法不能省,ActionServlet覆盖了的此方法中有很多重要操作
}
}



我们可以看到 在此类中 用了相对路径来加载xml的方法,首先通过prefix 读取了项目的路径然后再通过读取web.xml中的log4j变量,获得log4j.xml的相对路径 两者结合 就是他的绝对路径拉
最后在web.xml中配置action信息 就可以实现加载啦


web.xml


<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
com.asiainfo.ExtendedActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>

<!-- tsExtend -->
<init-param>
<param-name>config/tsextend</param-name><!--设备检测子模块-->
<param-value>
/WEB-INF/tsextend/struts-config.xml
</param-value>
</init-param>
<init-param>
<param-name>log4j</param-name><!--log4j.xml的路径-->
<param-value>
/WEB-INF/log4j.xml
</param-value>
</init-param>
<init-param>
<param-name>info</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup><!--设置当工程初始时便执行-->
</servlet>

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>



依据各个级别的日志输出到不同文件

log4j支持这个功能,不过不能再使用Properties配置,必须使用XML

建一个log4j.xml

<?xml version= "1.0 " encoding= "UTF-8 "?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd ">
<log4j:configuration xmlns:log4j= "http://jakarta.apache.org/log4j/ ">
<appender name= "STDOUT " class= "org.apache.log4j.ConsoleAppender ">
<layout class= "org.apache.log4j.PatternLayout "/>
</appender>
<appender name= "DEBUG " class= "org.apache.log4j.RollingFileAppender ">
<param name= "File " value= "debug.log "/>
<param name= "Append " value= "true "/>
<param name= "MaxFileSize " value= "500KB "/>
<param name= "MaxBackupIndex " value= "2 "/>
<layout class= "org.apache.log4j.PatternLayout "/>
<filter class= "org.apache.log4j.varia.LevelRangeFilter ">
<param name= "LevelMax " value= "DEBUG " />
<param name= "LevelMin " value= "DEBUG " />
</filter>
</appender>
<appender name= "INFO " class= "org.apache.log4j.RollingFileAppender ">
<param name= "File " value= "info.log "/>
<param name= "Append " value= "true "/>
<param name= "MaxFileSize " value= "500KB "/>
<param name= "MaxBackupIndex " value= "2 "/>
<layout class= "org.apache.log4j.PatternLayout "/>
<filter class= "org.apache.log4j.varia.LevelRangeFilter ">
<param name= "LevelMax " value= "INFO " />
<param name= "LevelMin " value= "INFO " />
</filter>
</appender>
<root>
<appender-ref ref= "STDOUT "/>
<appender-ref ref= "DEBUG "/>
<appender-ref ref= "INFO "/>
</root>
</log4j:configuration>



代码中DOMConfigurator.configure( "log4j.xml ");


这样就可以在log.debug和log.info时分别打印到不同文件中,如果你还需要更多的文件,可以复制多几次appender就可以了
(1). 输出方式appender一般有5种: 

org.apache.log4j.RollingFileAppender(滚动文件,自动记录最新日志) 
org.apache.log4j.ConsoleAppender (控制台) 
org.apache.log4j.FileAppender (文件) 
org.apache.log4j.DailyRollingFileAppender (每天产生一个日志文件) 
org.apache.log4j.WriterAppender (将日志信息以流格式发送到任意指定的地方) 



(2). 日记记录的优先级priority,优先级由高到低分为 
OFF ,FATAL ,ERROR ,WARN ,INFO ,DEBUG ,ALL。 
Log4j建议只使用FATAL ,ERROR ,WARN ,INFO ,DEBUG这五个级别。 



(3). 格式说明layout中的参数都以%开始,后面不同的参数代表不同的格式化信息(参数按字母表顺序列出): 
%c 输出所属类的全名,可在修改为 %d{Num} ,Num类名输出的维(如:"org.apache.elathen.ClassName",%C{2}将输出elathen.ClassName) 
%d 输出日志时间其格式为 %d{yyyy-MM-dd HH:mm:ss,SSS},可指定格式 如 %d{HH:mm:ss} 
%l 输出日志事件发生位置,包括类目名、发生线程,在代码中的行数 
%n 换行符 
%m 输出代码指定信息,如info(“message”),输出message 
%p 输出优先级,即 FATAL ,ERROR 等 
%r 输出从启动到显示该log信息所耗费的毫秒数 

%t 输出产生该日志事件的线程名


使用log4j.xml控制台打印输出ibatis的sql语句的方法

<appender name="IBatis" class="org.apache.log4j.ConsoleAppender">
       <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern"
         value="%-4r [%t] %-5p %c %x - %m%n" />
       </layout>
       <filter class="org.apache.log4j.varia.LevelRangeFilter">
        <param name="LevelMin" value="DEBUG" />
        <param name="LevelMax" value="DEBUG" />
       </filter>
    </appender>
<logger name="com.ibatis" additivity="true">
   <level value="DEBUG" />
    </logger>
    <logger name="java.sql.Connection" additivity="true">
       <level value="DEBUG" />
    </logger>
<!--
    <logger name="java.sql.Statement" additivity="true">
       <level value="DEBUG" />
    </logger>
 -->
    <logger name="java.sql.PreparedStatement" additivity="true">
       <level value="DEBUG" />
       <appender-ref ref="IBatis" />
    </logger>
    <logger name="java.sql.ResultSet" additivity="true">
       <level value="DEBUG" />
       <appender-ref ref="IBatis" />
    </logger>


++++++++++++++++++++++++++++++++++

以上都是转载,贴出我自己的log4j加载配置:


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * log4j MDC Filter
 *
 * User: Alec Fan
 * @version 1.0
 * @since 12-4-27 下午4:56
 */
public class Log4jMDCServletFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Log4jMDC.put(Log4jMDC.LOG4J_MDC_REQUEST_URI, httpServletRequest.getRequestURI());
        chain.doFilter(request, response);
    }


    public void destroy() {
        Log4jMDC.remove(Log4jMDC.LOG4J_MDC_REQUEST_URI);
    }
}



web.xml



<filter>
        <filter-name>log4jFilter</filter-name>
        <filter-class>com.xxxx.common.log4j.Log4jMDCServletFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>log4jFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>



我还是比较推崇这种方式的










标签: log4j
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 6
博文 20
码字总数 4970
×
宝塔镇河妖
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: