博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Log4j总结
阅读量:4588 次
发布时间:2019-06-09

本文共 12369 字,大约阅读时间需要 41 分钟。

、Basic Knoledge

 1.Common conception

Apache log4j is a -based utility. It was originally written by Ceki Gülcü and is now a project of the . log4j is one of several .

Gülcü has since started the and Logback projects, with the intention of offering a successor to log4j.

The log4j team has created a successor to log4j with version number , which is currently in beta release. log4j 2.0 was developed with a focus on the problems of log4j 1.2, 1.3, java.util.logging and logback, and addresses issues which appeared in those frameworks. In addition, log4j 2.0 offers a plugin architecture which makes it more extensible than its predecessor. log4j 2.0 is not backwards compatible with 1.x versions, although an "adapter" is available.

 There are three ways to configure log4j: with a , with an file and through Java code. Within either you can define three main components: Loggers, Appenders and Layouts. Configuring logging via a file has the advantage of turning logging on or off without modifying the application that uses log4j. The application can be allowed to run with logging off until there's a problem, for example, and then logging can be turned back on simply by modifying the configuration file.

Loggers are logical log file names. They are the names that are known to the Java application. Each logger is independently configurable as to what level of logging (FATAL, ERROR, etc.) it currently logs. In early versions of log4j, these were called category and priority, but now they're called logger and level, respectively.

The actual outputs are done by Appenders. There are numerous Appenders available, with descriptive names, such as FileAppender, ConsoleAppender, SocketAppender, SyslogAppender, NTEventLogAppender and even SMTPAppender. Multiple Appenders can be attached to any Logger, so it's possible to log the same information to multiple outputs; for example to a file locally and to a listener on another computer.

Appenders use Layouts to format log entries. A popular way to format one-line-at-a-time log files is PatternLayout, which uses a pattern string, much like the / function . There are also HTMLLayout and XMLLayout formatters for use when or XML formats are more convenient, respectively.

To debug a misbehaving configuration use the Java VM property -Dlog4j.debug which will output to . To find out where a log4j.properties was loaded from inspect getClass().getResource("/log4j.properties") or getClass().getResource("/log4j.xml").

There is also an implicit "unconfigured" configuration of log4j, that of a log4j-instrumented Java application which lacks any log4j configuration. This prints to stdout a warning that the program is unconfigured, and the URL to the log4j web site where details on the warning and configuration may be found. As well as printing this warning, an unconfigured log4j application does not print messages at INFO, DEBUG or TRACE levels -and possibly not higher level messages.

Explain on <root>

Near the bottom of the log4j.xml file, look for the following entry:

    
      
      
  

Assigning a value to root ensures that any log appenders that do not have a level explicitly assigned inherit the root level (in this case, INFO). For example, by default, the FILE appender does not have a threshold level assigned and so it assumes the root’s.

The possible log levels used by log4j are DEBUG, INFO, WARN, ERROR, and FATAL, as defined in the org.apache.log4j.Level class. Inattention to the proper use of these settings can be costly in terms of performance.

A good rule of thumb is to use INFO or DEBUG only when debugging a particular problem.

Any appender included in the root that does have a level threshold set, should set that threshold to ERROR, WARN, or FATAL unless you are debugging something.

The performance hit with high log levels has less to do with verbosity of messages than with the simple fact that console and file logging, in log4j, involve synchronous writes. An AsyncAppender class is available, but its use does not guarantee better performance. The issues are well-known and are Apache log4j issues, not Identity Manager issues.

The default of INFO in the User Application’s log config file (above) is satisfactory for many environments, but where performance is critical, you should consider changing the above jboss-log4j.xml entry to:

      
      
 

In other words, remove CONSOLE and set the log level to ERROR. For a fully tested/debugged production setup, there is no need to log at the INFO level, nor any need to leave CONSOLE logging enabled. The performance payoff of turning these off can be significant.

For more information on log4j, consult the documentation available at http://logging.apache.org/log4j/docs.

For more information on the use of Novell Identity Audit with Identity Manager, consult the Novell Identity Manager: Administration Guide.

 2. log4j有三种主要组件:logger、appender and layout

 3.Log4j提供的appender有以下几种:
  org.apache.log4j.ConsoleAppender(控制台)
  org.apache.log4j.FileAppender(文件)
  org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
  org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件)
  org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
 4.Log4j提供的layout有以下几种:
  org.apache.log4j.HTMLLayout(以HTML表格形式布局)
  org.apache.log4j.PatternLayout(可以灵活地指定布局模式)
  org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串)
  org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)
 5.Log4j提供的几种输出格式:
  %M:Used to output the method name where the logging request was issued.
  %m:Used to output the application supplied message associated with the logging event.
  %l:Used to output location information of the caller which generated the logging event
  %L:Used to output the line number from where the logging request was issued.
  %p:Used to output the priority of the logging event.
  %n:Outputs the platform dependent line separator character or characters.
   %r:Used to output the number of milliseconds elapsed since the start of the application until the creation of the logging event.
  %F:Used to output the file name where the logging request was issued.
  %d:Used to output the date of the logging event.
  %c:Used to output the category of the logging event
  %C:Used to output the fully qualified class name of the caller issuing the logging request
 6.如果是对于效率要求比较高的话,要在log.debug()之前加上log.isDebugEnabled()进行判断,这样能够大大减少执行时间
  7.对于各个appenders,共有的属性是layout(一般设置为org.apache.log4j.PatternLayout),Threshold(Log的级别)
  (1)ConsoleAppender:Target(System.out和System.err)
  (2)FileAppender:File(定义输出的文件名),Append(定义是否为追加)
  (3)DailyRollingFileAppender(除FileAppender属性外):MaxFileSize(最大文件大小),MaxBackupIndex()

 

二、Configuration Example

Step 1: add jars of log4j, for example in pom.xml:

<!-- Logging part -->

                   <dependency>

                            <groupId>log4j</groupId>

                            <artifactId>log4j</artifactId>

                            <version>1.2.16</version>

                   </dependency>

                   <dependency>

                            <groupId>log4j</groupId>

                            <artifactId>apache-log4j-extras</artifactId>

                            <version>1.1</version>

                   </dependency>

                   <dependency>

                            <groupId>org.slf4j</groupId>

                            <artifactId>slf4j-api</artifactId>

                            <version>1.6.1</version>

                   </dependency>

                   <dependency>

                            <groupId>org.slf4j</groupId>

                            <artifactId>slf4j-log4j12</artifactId>

                            <version>1.6.1</version>

                   </dependency>

 

Step 2: specify the location of log4j configuration, for example in web.xml:

……

  <context-param> 

       <param-name>log4jConfigLocation</param-name> 

    <param-value>classpath:log4j.xml</param-value> 

  </context-param> 

  <context-param> 

    <param-name>log4jRefreshInterval</param-name> 

    <param-value>60000</param-value> 

  </context-param> 

  <listener> 

       <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 

  </listener>

<listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

……

 

 

Step 3: under java/resources, add log4j.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

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

<!--  an appender is an output destination, such as the console or a file;

        names of appenders are arbitrarily chosen            -->

<!-- 1.  输出到控制台中  -->

         <appender name="console" class="org.apache.log4j.ConsoleAppender">

                  <param name="Target" value="System.out"/>

                   <layout class="org.apache.log4j.PatternLayout">

                            <param name="ConversionPattern" value="%d [%t] %-5p -%c{1} - %m%n"/>

                   </layout>

         </appender>

<!-- 2  输出到日志文件 每天一个日志  -->

         <appender name="fileAppenderDefault" class="org.apache.log4j.DailyRollingFileAppender">

                   <param name="File"

                            value="/data/Logs/Dev/sso/${jvm.process.name}/sso.log" />

                   <param name="Append" value="true" />

                   <param name="encoding" value="UTF-8" />

                   <layout class="org.apache.log4j.PatternLayout">

                            <param name="ConversionPattern" value="%d [%t] %-5p -%c{1} - %m%n" />

                   </layout>

         </appender>

<!--  3 输出到日志文件,2和3根据需要选择一种  -->    

    <appender name="filelog_appender"    

         class="org.apache.log4j.RollingFileAppender">    

         <!-- 设置File参数:日志输出文件名 -->    

         <param name="File" value="log/testlog4jxml_all.log" />    

         <!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 -->    

         <param name="Append" value="true" />    

         <!-- 设置文件大小 -->    

         <param name="MaxFileSize" value="1MB" />    

         <!-- 设置文件备份 -->    

         <param name="MaxBackupIndex" value="10000" />    

         <!-- 设置输出文件项目和格式 -->    

        <layout class="org.apache.log4j.PatternLayout">    

        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p (%c:%L)- %m%n"/>             </layout>    

      </appender>

<!--  4 配置mybatis的log  -->    

         <appender name="mybatis_sql" class="org.apache.log4j.DailyRollingFileAppender">

                   <param name="File"

                            value="/data/Logs/Dev/sso/${jvm.process.name}/mybatis_sql.log" />

                   <param name="Append" value="true" />

                   <param name="encoding" value="UTF-8" />

                   <layout class="org.apache.log4j.PatternLayout">

                            <param name="ConversionPattern" value="%d [%t] %-5p -%c{1} - %m%n" />

                   </layout>

         </appender>

<appender name="fileAppenderApiMcnRunningWater" class="org.apache.log4j.rolling.RollingFileAppender"

          <rollingPolicy 

             class="org.apache.log4j.rolling.TimeBasedRollingPolicy"

             <param name="FileNamePattern" 

             value="/data/Logs/Dev/sso/${jvm.process.name}/sso-RunningWater.log.%d{yyyy-MM-dd}" /> 

          </rollingPolicy> 

          <layout class="org.apache.log4j.PatternLayout"

               <param name="ConversionPattern"  value="%d{yyyy-MM-dd HH:mm:ss}\t%m%n" /> 

          </layout> 

     </appender>

<!--通过<logger></logger>的定义可以将各个包中的类日志输出到不同的日志文件中:

Category is deprecated and should be avoided, used Logger,which is a subclass of Categroty, instead-->

<!-- loggers of category 'org.springframework' will only log messages of level "info" or higher;

        if you retrieve Loggers by using the class name (e.g. Logger.getLogger(AClass.class))
        and if AClass is part of the org.springframework package, it will belong to this category   -->

    <logger name="RUNNING_WATER_LOGGER" additivity="false">

        <level value="info"/>

        <appender-ref ref="fileAppenderApiMcnRunningWater"/>

    </logger>

         <logger name="com.ibatis" additivity="false">

                   <level value="debug" />

                   <appender-ref ref="mybatis_sql"/>

         </logger>

         <logger name="com.ibatis.common.jdbc.SimpleDataSource"

                   additivity="false">

                   <level value="debug" />

                   <appender-ref ref="mybatis_sql"/>

         </logger>

         <logger name="com.ibatis.common.jdbc.ScriptRunner" additivity="false">

                   <level value="debug" />

                   <appender-ref ref="mybatis_sql"/>

         </logger>

         <logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate"

                   additivity="false">

                   <level value="debug" />

                   <appender-ref ref="mybatis_sql"/>

         </logger>

         <logger name="java.sql.Connection" additivity="false">

                   <level value="debug" />

                   <appender-ref ref="mybatis_sql"/>

         </logger>

         <logger name="java.sql.Statement" additivity="false">

                   <level value="debug" />

                   <appender-ref ref="mybatis_sql"/>

         </logger>

         <logger name="java.sql.PreparedStatement" additivity="false">

                   <level value="debug" />

                   <appender-ref ref="mybatis_sql"/>

         </logger>

         <logger name="java.sql.ResultSet" additivity="false">

                   <level value="debug" />

                   <appender-ref ref="mybatis_sql"/>

         </logger>

         <logger name="org.apache">

                   <level value="debug" />

         </logger>

         <logger name="org.springframework">

                   <level value="debug" />

         </logger>

         <logger name="net.sourceforge">

                   <level value="error" />

         </logger>

<!--

           all log messages of level "debug" or higher will be logged, unless defined otherwise
           all log messages will be logged to the appender "stdout", unless defined otherwise
       -->

         <root>

                   <priority value="debug" />

<!--通过<configuration to be used--> 

                   <appender-ref ref="fileAppenderDefault" />

         </root>

</log4j:configuration>

 

转载于:https://www.cnblogs.com/fushine/p/3418052.html

你可能感兴趣的文章
nginx动静分离小示例
查看>>
nginx socket转发设置
查看>>
centos samba搭建
查看>>
Android Studio 错误: 非法字符: '\ufeff'
查看>>
并发编程--一堆锁,GIL,同步异步,Event事件
查看>>
svn配置
查看>>
解决SQLite database is locked
查看>>
Javascript中this关键字
查看>>
微信静默授权
查看>>
Spring MVC框架初步讲解
查看>>
关于dl dt dd 文字过长换行在移动端显示对齐的探讨总结
查看>>
C#线程安全打开/保存文件对话框
查看>>
201555334 实验一:Java开发环境的熟悉 总结
查看>>
docker系列 --- 命令详解
查看>>
观察者模式 -- 设计模式系列文章(二)
查看>>
MySql学习14-----数据备份和恢复
查看>>
页面小标签
查看>>
卷积分
查看>>
Asp.Net MVC Filter权限过滤使用说明
查看>>
一次群体code review
查看>>