log4j1.2到2学习笔记

 

Log4j三大组件:loggers\appenders\layouts

package org.apache.log4j;
 
  public class Logger {
 
    // Creation & retrieval methods:
    public static Logger getRootLogger();
    public static Logger getLogger(String name);
 
    // printing methods:
    public void trace(Object message);
    public void debug(Object message);
    public void info(Object message);
    public void warn(Object message);
    public void error(Object message);
    public void fatal(Object message);
 
    // generic printing method:
    public void log(Level l, Object message);
}

Loggers may be assigned levels. The set ofpossible levels, that is:

TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL

 DEBUG < INFO < WARN <ERROR < FATAL.

 

In log4j speak, an output destination is called an appender.

Currently, appenders exist for the consolefiles, GUIcomponents,remote socket servers, JMSNT Event Loggers, and remoteUNIX Syslog daemons. It is also possible to log asynchronously.

这句好就是说:appenders就是日志的存在方式。

 

Each enabled logging request for a given logger will be forwardedto all the appenders in that logger as well as the appenders higher in thehierarchy

 

The invocation of the BasicConfigurator.configure method creates a rather simple log4j setup. This method ishardwired to add to the root logger aConsoleAppender. The output will be formatted using a PatternLayout set to the pattern "%-4r [%t] %-5p %c %x - %m%n".

Note that by default, the rootlogger is assigned to Level.DEBUG.

 

Log4j hasthe ability to automatically configure itself during initialization. When Log4jstarts it will locate all the ConfigurationFactory plugins and arrange then inweighted order from highest to lowest. As delivered, Log4j contains threeConfigurationFactory implementations: one for JSON, one for YAML, and one forXML.

 

Configuration with XML

The configuration element in the XML file accepts several attributes:

Attribute Name

Description

advertiser

(Optional) The Advertiser plugin name which will be used to advertise individual FileAppender or SocketAppender configurations. The only Advertiser plugin provided is 'multicastdns".

dest

Either "err", which will send output to stderr, or a file path or URL.

monitorInterval

The minimum amount of time, in seconds, that must elapse before the file configuration is checked for changes.

name

The name of the configuration.

packages

A comma separated list of package names to search for plugins. Plugins are only loaded once per classloader so changing this value may not have any effect upon reconfiguration.

schema

Identifies the location for the classloader to located the XML Schema to use to validate the configuration. Only valid when strict is set to true. If not set no schema validation will take place.

shutdownHook

Specifies whether or not Log4j should automatically shutdown when the JVM shuts down. The shutdown hook is enabled by default but may be disabled by setting this attribute to "disable"

status

The level of internal Log4j events that should be logged to the console. Valid values for this attribute are "trace", "debug", "info", "warn", "error" and "fatal". Log4j will log details about initialization, rollover and other internal actions to the status logger. Settingstatus="trace" is one of the first tools available to you if you need to troubleshoot log4j.

strict

Enables the use of the strict XML format. Not supported in JSON configurations.

verbose

Enables diagnostic information while loading plugins.

 

 

ALoggerConfig is configured using the logger element. The logger element must have a name attribute specified,will usually have a level attribute specified and may also have an additivityattribute specified. The level may be configured with one of TRACE, DEBUG,INFO, WARN, ERROR, ALL or OFF. If no level is specified it will default toERROR. The additivity attribute may be assigned a value of true or false. Ifthe attribute is omitted the default value of false will be used.

 

 

in fact , threshold's level should be larger or equals rootlogger's level.
usually, thresold can be used to define some special appender's filter log level.
eg:
there are two appenders: console and file,and the level is warn, if you just only want the error message be written to file, so you can use "file.threshold=error" to filter out the "warn" message.

 

 

 

Log4j2.1

<?xmlversion="1.0"encoding="UTF-8"?>

<!-- status : The level ofinternal Log4j events that should be logged to the console -->

<configuration>

 <!-- <Properties>

   <Property name="name1" value="ss"/>

 </Properties> -->

 

 

 <appenders> 

    <!--这个输出控制台的配置-->

    <Consolename="Stdout"target="SYSTEM_OUT">

         <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch-->

         <ThresholdFilterlevel="debug"onMatch="ACCEPT"onMismatch="DENY"/>

         <!--这个都知道是输出日志的格式-->

         <PatternLayoutpattern="%d{yyyy-MM-ddHH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>

    </Console>

    

    <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->

    <Filename="file"fileName="D:/logs/test.log"append="true">

         <PatternLayoutpattern="%d{HH:mm:ss.SSS}%-5level %class{36} %L %M - %msg%xEx%n"/>

    </File>

       

    <!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->

    <RollingFilename="RollingFile"fileName="D:/logs/app.log"append="true"

                 filePattern="log/%d{yyyy-MM-dd}-%i.log">

         <ThresholdFilterlevel="error"onMatch="ACCEPT"onMismatch="DENY"/>

         <PatternLayoutpattern="%d{yyyy-MM-ddHH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>

         <SizeBasedTriggeringPolicysize="50MB"/>

    </RollingFile>

    

 </appenders> 

 

 <!-- 定义了logger,并引用appender -->

 <loggers> 

    <!--建立一个默认的rootlogger-->

    <rootlevel="debug">

        <appender-refref="file"/>

        <appender-refref="Stdout"/>

    </root>

   

    <!-- additivity=false 可以防止com.fuiou的日志打印两遍,因为rootdebug大于loggerinfo -->

    <loggername="com.fuiou"level="info"additivity="false">

        <appender-refref="Stdout"/>

   </logger>

 </loggers> 

 

</configuration> 

 

 

 

Log4j1.2

# self define logger

log4j.logger.FuaoLogger = INFO, A4

 

# rootLogger

log4j.rootLogger = INFO, A4

log4j.category.com.test= DEBUG, CONSOLE

log4j.category.com.ibatis = INFO

 

# CONSOLE Appender

log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout

log4j.appender.CONSOLE.layout.ConversionPattern =%d{yyyy-MM-dd HH:mm:ss} %l %-4r [%t] %-5p %c %x - %m%n

 

# Daily Rolling File Appender

log4j.appender.A4 = org.apache.log4j.DailyRollingFileAppender

log4j.appender.A4.File = log/log4j_daily.log

log4j.appender.A4.DatePattern = '.'yyyyMMdd

log4j.appender.A4.Append = true

log4j.appender.A4.Threshold = DEBUG ##输出DEBUG级别以上的日志

log4j.appender.A4.layout = org.apache.log4j.PatternLayout

log4j.appender.A4.layout.ConversionPattern= %d{yyyy-MM-ddHH:mm:ss} %l %-4r [%t] %-5p %-16c %x - %m%n

 

# SQL logger level

log4j.logger.java.sql.Connection = DEBUG, CONSOLE

log4j.logger.java.sql.Statement = DEBUG, CONSOLE

log4j.logger.java.sql.PreparedStatement= DEBUG, CONSOLE

log4j.logger.java.sql.ResultSet = INFO, CONSOLE

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值