log4j2 使用详解

log4j升级了,新架构很不错,将安装步骤记录如下:

1、Log4j2的导入

首先到http://logging.apache.org/log4j/2.x/download.html 上下载最新的log4j2的jar包,然后再eclipse中加入log4j-api-2.0-beta2.jar和log4j-core-2.0-beta2.jar,需要注意的是不要将所有jar都导入工程造成不必要的混乱。

2、测试用例

log4j 2.0的使用非常简单,只要用LogManager的getLogger函数获取一个logger,就可以使用logger记录日志,代码如下:

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

public class HelloLog4j {

private static Logger logger = LogManager.getLogger("HelloLog4j");

public static void main(String[] args) {

 MyApplication myApplication = new MyApplication();

 logger.entry();

 logger.info("Hello, World!");

 myApplication.doIt();

    logger.error("Hello, World!");

    logger.exit();

}

}

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

public class MyApplication {

  static Logger logger = LogManager.getLogger(MyApplication.class.getName()); 

  

  public boolean doIt() { 

   logger.entry();  //Log entry to a method 

   logger.error("Did it again!");  //Log a message object with the ERROR level 

   logger.exit();  //Log exit from a method 

   return false; 

  } 

}

运行程序,输出结果为:

12:11:28.672 [main] ERROR MyApplication - Did it again!

12:11:28.672 [main] ERROR HelloLog4j - Hello, World!

注意到,输出的log都是在ERROR level上的,log4j定义了8个级别的log(除去OFF和ALL,可以说分为6个级别),优先级从高到低依次为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE、 ALL。如果将log level设置在某一个级别上,那么比此级别优先级高的log都能打印出来。例如,如果设置优先级为WARN,那么OFF、FATAL、ERROR、WARN 4个级别的log能正常输出,而INFO、DEBUG、TRACE、 ALL级别的log则会被忽略。从我们实验的结果可以看出,log4j默认的优先级为ERROR或者WARN(实际上是ERROR)。

3. 配置文件

log4j是apache的一个开源项目,在写这篇博客的时候已经发布了2.0的beta版本,首先需要注意的是,log4j 2.0与以往的1.x有一个明显的不同,其配置文件只能采用.xml, .json或者 .jsn。在默认情况下,系统选择configuration文件的优先级如下:(classpath为scr文件夹)classpath下名为 log4j-test.json 或者log4j-test.jsn文件classpath下名为 log4j2-test.xmlclasspath下名为 log4j.json 或者log4j.jsn文件classpath下名为 log4j2.xml必须注意.xml 文件的文件名为log4j2,这里让我纠结了一个下午,系统一直找不到配置文件,最后发现是文件名里面少了一个2。下面以log4j2.xml为例来介绍log4j的配置。

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

<configuration status="OFF">

 <appenders>

  <Console name="Console" target="SYSTEM_OUT">

   <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>

  </Console>

 </appenders>

 <loggers>

  <root level="trace">

   <appender-ref ref="Console"/>

  </root>

 </loggers>

</configuration>

首先介绍loggers标签,用于定义logger的lever和所采用的appender,其中appender-ref必须为先前定义的appenders的名称,例如,此处为Console。那么log就会以appender所定义的输出格式来输出log。root标签为log的默认输出形式,如果一个类的log没有在loggers中明确指定其输出lever与格式,那么就会采用root中定义的格式。例如以下定义:

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

<configuration status="OFF">

 <appenders>

  <Console name="Console" target="SYSTEM_OUT">

   <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>

  </Console>

 </appenders>

 <loggers>

  <logger name="com.relin.HelloLog4j" level="error" additivity="false">

   <appender-ref ref="Console"/>

  </logger>

  <root level="trace">

   <appender-ref ref="Console"/>

  </root>

 </loggers>

</configuration>

此时,HelloLog4j则会在error级别上输出log,而其他类则会在trace级别上输出log。需要注意的是 additivity选项,如果设置为true(默认值)则HelloLog4j的log会被打印两次,第二次打印是由于HelloLog4j同时也满足root里面定义的trace

4. 其他特征

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

<configuration status="error"> 

 <appenders> 

<!--控制台输出-->

  <Console name="Console" target="SYSTEM_OUT"> 

   <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/> 

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

  </Console> 

<!--文件输出-->

  <File name="log" fileName="target/test.log" append="false"> 

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

  </File> 

<!--归档文件输出-->

  <RollingFile name="RollingFile" fileName="logs/app.log" 

         filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz"> 

   <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/> 

   <SizeBasedTriggeringPolicy size="500 MB" /> 

  </RollingFile> 

 </appenders> 

 <loggers> 

  <root level="trace"> 

   <appender-ref ref="RollingFile"/> 

   <appender-ref ref="Console"/> 

  </root> 

 </loggers> 

</configuration>

注意:输出的日志文件默认存放在tomcat/bin目录下

扩展组件

1,ConsoleAppender

输出结果到System.out或是System.err。

2,FileAppender

输出结果到指定文件,同时可以指定输出数据的格式。append=“false”指定不追加到文件末尾

3,RollingFileAppender

自动追加日志信息到文件中,直至文件达到预定的大小,然后自动重新生成另外一个文件来记录之后的日志。

过滤标签

1,ThresholdFilter

用来过滤指定优先级的事件。

2,TimeFilter

设置start和end,来指定接收日志信息的时间区间。

最新评论:

no.117644 hethertan 5.248.164.76 2020-06-29 22:19

По совету Обратились сюда [url=https://india-express.net/shop/88/desc/rolimus]эверолимус 10 мг цена[/url]

no.117625 ta.m.ar.a.v.oli...k.o..v...a.. 91.121.88.225 2020-06-27 06:04

https://whitegodman.com https://deluxeshok.com https://firstonesh.com https://greencitymar.com https://spacestufok.com https://peoplefory.com https://catzillabro.com https://maestrodel.com https://weedbestpor.com

no.117624 r.pup.1as305 94.198.51.223 2020-06-27 04:13

Guys just made a web-site for me, look at the link: <a href=https://multymix.ru/>https://multymix.ru/</a> Tell me your prescriptions. Thanks!

no.117620 polymod123 134.249.127.121 2020-06-26 17:03

[url=https://anticancer24.ru/shop/460/desc/sofoxen-daclaxen]софосбувир +и даклатасвир екатеринбург[/url]

no.117544 h8059viav 178.158.22.37 2020-06-19 15:26

viagra price when will viagra be generic [url=https://trustedstoremjd.com/#]viagra for sale[/url] generic for viagra is there a generic for viagra <a href="https://trustedstoremjd.com/#&quot;&gt;canadian pharmacy generic viagra&lt;/a&gt; buy viagra online usa generic viagra without a doctor prescription

no.117525 r5790viau 103.83.174.95 2020-06-19 03:48

cialis 20 mg price cialis 5mg [url=https://wmmcialis.com/#]over the counter cialis[/url] cialis coupon walmart buy cialis <a href="https://topedstoreusa.com/#&quot;&gt;coupon for cialis&lt;/a&gt; cialis otc cialis 20mg

no.117524 bazil 176.106.242.148 2020-06-19 01:57

Putin - excel lessons - https://www.youtube.com/c/ExcelStore excel training excel courses excel lessons sql training sql courses sql lessons

no.117506 f8186viaj 178.158.37.72 2020-06-18 01:14

cialis professional cialis from canada [url=https://bwcialiskls.com/#]printable cialis coupon[/url] cialis coupon how much does cialis cost <a href="https://bwcialiskls.com/#&quot;&gt;when will cialis be generic&lt;/a&gt; cialis 20 mg price walmart discount cialis

no.117501 f5918viab 178.158.37.72 2020-06-18 00:16

cialis india price of cialis [url=https://bwcialiskls.com/#]coupon for cialis[/url] cialis on line where to buy cialis online <a href="https://bwcialiskls.com/#&quot;&gt;when does cialis go generic&lt;/a&gt; cialis discount cialis without prescription

no.117497 n5322viah 178.158.37.72 2020-06-17 23:43

buy generic cialis where to buy cialis [url=https://spcialisps.com/#]buy cialis[/url] canadian pharmacy cialis 20mg cialis coupon cvs <a href="https://spcialisps.com/#&quot;&gt;cialis 20mg&lt;/a&gt; cialis generic best price cialis for sale

no.117481 n1051viap 118.175.93.38 2020-06-17 21:09

cialis from india cialis coupons [url=https://bwcialiskls.com/#]cialis black[/url] cialis generic cialis manufacturer coupon 2019 <a href="https://topedstoreusa.com/#&quot;&gt;viagra cialis&lt;/a&gt; cialis canadian pharmacy cialis pills

no.117476 u8759viad 178.158.37.72 2020-06-17 19:33

cialis from canada over the counter cialis [url=https://wbmaastr.com/#]best place to buy cialis online reviews[/url] cialis 20 mg price walmart prices of cialis <a href="https://wbmaastr.com/#&quot;&gt;cialis walmart&lt;/a&gt; online cialis cialis otc

no.117472 k2516viaq 109.245.214.49 2020-06-17 19:06

cialis without a prescription buy generic cialis online [url=https://wbmaastr.com/#]generic for cialis[/url] online cialis cialis coupon cvs <a href="https://topedstoreusa.com/#&quot;&gt;where to buy cialis online&lt;/a&gt; buy generic cialis online is cialis generic

no.117428 g7934vial 77.237.15.60 2020-06-16 02:30

where can i buy viagra over the counter best over the counter viagra [url=https://gemedjie.com/#]generic name for viagra[/url] viagra prescription where can i buy viagra <a href="https://topedstoreusa.com/#&quot;&gt;buy generic viagra&lt;/a&gt; mail order viagra viagra discount

no.117391 brently1780 5.188.210.18 2020-06-11 05:58

[url=https://www.lukland.ru/catalog/hatches/metalhatches/cylkey/variant/1438]потайной напольный люк[/url] или [url=https://www.lukland.ru/catalog/hatches/metalhatches/softline-grankey-z/variant/1364]люк под плитку стальной[/url] https://www.lukland.ru/catalog/hatches/hatchesfortile/atlant/mosaic

no.117375 51 62.168.57.109 2020-06-08 21:02

Sign up for now https://hairypussypix.com/galleries/perfect-hairy-cunt-pictures.html - Perfect hairy cunt pictures and even more.

no.117347 alnka.nikolayeva.83 45.139.48.9 2020-06-04 12:06

[url=https://gasvleningrade.ru]купить гелий в баллоне для шариков спб[/url] - баллон с гелием портативный, баллон с гелием для шариков купить

no.117346 50 101.255.55.10 2020-06-04 11:23

Just click here https://hairypussypix.com/galleries/fat-hairy-pussy-photos.html - Fat hairy pussy photos and much more.

no.117335 cbd0g 178.159.37.69 2020-06-02 18:31

where can i buy viagra pills online <a href="https://judpharmacy.com/">where can i buy real viagra online</a> where can i buy viagra cheap

no.117334 cbddl 178.159.37.69 2020-06-02 18:23

viagra nz buy <a href="https://judpharmacy.com/">cheapest place to buy viagra online</a> viagra tablets buy

no.117333 polymod123 188.163.80.49 2020-06-02 13:05

[url=https://anticancer24.ru/shop/460/desc/sofoxen-daclaxen]софосбувир +и даклатасвир +в новосибирске[/url]

no.117319 arthurckarck 46.185.114.1 2020-05-30 11:29

[b] [url=https://velpanex.ru/shop/26/desc/lenvaxen10]Lenvaxen (Ленватиниб 10 мг) - Ленваксен (Lenvatinib 10 mg) - аналог Ленвима[/url] [/b] – это современный препарат, который часто назначают пациентам. Он подходит для лечения людей, которые страдают от местно-распространенной или метастатической карциномы щитовидной железы. Помимо этого, медикамент дает возможность бороться с распространенной почечно-клеточной карциномой. Разрешено применять это лекарство, если ранее пациент проходил лечение с

no.117317 robertagendick 46.185.114.1 2020-05-30 02:06

Оочень хороший препарат, побочек вообще небыло [url=https://india-express.net/shop/190/desc/dasatinib]закупка препарата дазатиниб вологодская область[/url]

no.117306 maricelamorley 195.154.61.127, 2020-05-28 04:46

bhutan dating sites https://bestsexdating.michaelkante.eu bhutan dating sites elite singles romania

no.117283 inbox325 62.210.79.40 2020-05-27 04:43

Beginning at 8$. Unbeateble Worth. 24H Shipping and delivery. 479 Writers Energetic. Strive our rapid essay producing provider. <a href=https://borderpaperforwriting134.blogspot.com/2019/10/law-question-essay-example-for-free.html>writing services</a> <a href=https://poemstowriteessayson121.blogspot.com/2019/10/the-biogas-production-worldwide.html>writing services</a>

no.117269 inbox135 62.210.79.40 2020-05-26 15:38

Have to have a British isles essay composing | Buy your educational assignment from our British Essay Author service | Get best rated composing with the most excellent price levels from Ph.D writers. <a href=https://collegeessaysforsale808.blogspot.com/2019/11/poverty-and-pollution-in-japan-europe.html>paper writer</a> <a href=https://themesforessaywriting983.blogspot.com/>paper writer</a>

no.117235 inbox411 62.210.79.40 2020-05-25 04:26

Will you be fed up with creating educational papers. Prefer to go ahead and take emotional stress from your assignments, welcome towards paradise of excellence. <a href=https://conceptpaperwriting915.blogspot.com/2019/10/codeswitching-from-english-essay.html>writing service</a> <a href=https://essaywritinghelponline820.blogspot.com/2019/10/benito-mussolini-research-paper-example_18.html>writing service</a>

no.117165 florine_monaco 191.209.21.52 2020-05-20 10:50

married dating service https://imgur.com/a/jLhqP62 married dating service names oof asian dating site

no.117157 annhoff679 5.188.84.150 2020-05-19 15:38

Добрались мы до места только минут через сорок. [url=https://meinbilligkredit.top/dolg_khoum_kredit_karta.php]долг хоум кредит карта[/url], [url=https://meinbilligkredit.top/rasschitat_kredit_v_gazprombanke.php]рассчитать кредит в газпромбанке[/url]. В место этого, мы убегаем от каких-то собак, сидим в каком-то клоповнике! [url=https://meinbilligkredit.t

no.117143 arthurckarck 46.185.114.1 2020-05-17 16:46

[b] [url=https://velpanex.ru/shop/26/desc/lenvaxen10]Lenvaxen (Ленватиниб 10 мг) - Ленваксен (Lenvatinib 10 mg) - аналог Ленвима[/url] [/b] – это современный препарат, который часто назначают пациентам. Он подходит для лечения людей, которые страдают от местно-распространенной или метастатической карциномы щитовидной железы. Помимо этого, медикамент дает возможность бороться с распространенной почечно-клеточной карциномой. Разрешено применять это лекарство, если ранее пациент проходил лечение с

no.117142 h1278vian 88.147.142.103 2020-05-17 15:38

cost of viagra buy viagra online cheap [url=https://kleoviagrahqb.com/#]viagra professional[/url] viagra online viagra online usa <a href="https://topedstoreusa.com/#&quot;&gt;cvs viagra&lt;/a&gt; generic for viagra buy viagra online cheap

no.117141 loreen_hildebrand 195.154.61.127, 2020-05-17 14:32

cat lovers dating website https://unepresidentepourleurope.eu cat lovers dating website cat lovers dating website

no.117121 robertagendick 37.115.209.59 2020-05-16 11:34

Оочень хороший препарат, побочек вообще небыло [url=https://india-express.net/shop/190/desc/dasatinib]дазатиниб мнн[/url]

no.117114 o5663viad 92.255.164.166 2020-05-16 07:31

viagra cheap online pharmacy viagra [url=https://kleoviagrahqb.com/#]viagra online canada[/url] viagra without a doctor prescription canada buy generic 100mg viagra online <a href="https://topedstoreusa.com/#&quot;&gt;100mg viagra&lt;/a&gt; generic name for viagra viagra price

no.117109 hethertan 37.115.200.181 2020-05-16 04:02

Хорошие специалисты и прекрасный севрис в этой онко аптеке [url=https://india-express.net/shop/191/desc/sunitinib]депигментация +при приеме сутента[/url]

no.117104 v6215viay 92.247.169.43 2020-05-15 23:08

viagra doses 200 mg canadian pharmacy viagra [url=https://kleoviagrahqb.com/#]over the counter viagra[/url] cheap viagra 100mg viagra over the counter <a href="https://topedstoreusa.com/#&quot;&gt;buy viagra online canada&lt;/a&gt; cheap viagra online canadian pharmacy best place to buy viagra online

no.117094 s5243viae 109.237.147.213 2020-05-15 11:12

viagra online usa viagra from canada [url=https://tjviagratj.com/#]over the counter viagra cvs[/url] viagra canada over the counter viagra cvs <a href="https://topedstoreusa.com/#&quot;&gt;generic viagra walmart&lt;/a&gt; goodrx viagra viagra pills

no.117093 mariaramble 5.248.165.46 2020-05-15 10:43

Добрый день Знакомые покупали Препараты [url=https://anticancer24.ru/shop/470/desc/dasanat-dasatinib-sprajsel]дазатиниб аспартат 10 конъюгат[/url]

no.117089 aurelioupfield unknown, 165.22 2020-05-15 08:20

legitimate russian dating agencies https://sikerkulcs.eu legitimate russian dating agencies best meeting app free

no.117084 chance.tobey 103.28.121.58 2020-05-15 02:57

senior online dating australia https://datingsextumblr.itopdeals.eu senior online dating australia senior online dating australia

no.117083 glindaspellman unknown, 165.22 2020-05-15 02:52

whole foods speed dating https://familylearning-flame.eu whole foods speed dating love sex and dating

no.117081 p9934viat 186.159.1.58 2020-05-15 01:06

online doctor prescription for viagra otc viagra [url=https://kleoviagrahqb.com/#]cheapest viagra online[/url] viagra online viagra <a href="https://topedstoreusa.com/#&quot;&gt;buy viagra&lt;/a&gt; amazon viagra discount viagra

no.117073 n3305viaz 186.200.4.34 2020-05-14 19:11

over the counter viagra cvs best place to buy viagra online [url=https://kleoviagrahqb.com/#]viagra canada[/url] over the counter viagra cvs is there a generic for viagra <a href="https://topedstoreusa.com/#&quot;&gt;viagra price comparison&lt;/a&gt; generic viagra online for sale generic viagra

no.117072 baileyboynton unknown, 157.24 2020-05-14 19:04

online captcha data entry jobs https://datingnonnational.website online captcha data entry jobs 70 pkus dating sites

no.117064 a769viax 70.60.132.34 2020-05-14 15:01

viagra cost buy viagra online [url=https://tjviagratj.com/#]cheapest viagra online[/url] buy generic 100mg viagra online buying viagra online <a href="https://topedstoreusa.com/#&quot;&gt;viagra prices&lt;/a&gt; can you buy viagra over the counter viagra online canadian pharmacy

no.117048 v4784viaz 95.31.137.73 2020-05-13 23:15

best over the counter viagra how much does viagra cost [url=https://tjviagratj.com/#]viagra online canada[/url] can you buy viagra over the counter viagra without prescription <a href="https://topedstoreusa.com/#&quot;&gt;generic viagra india&lt;/a&gt; buy viagra online usa where to buy viagra

no.117045 p4338viaz 92.62.73.73 2020-05-13 20:26

cheap viagra 100mg mexican viagra [url=https://kleoviagrahqb.com/#]over the counter viagra[/url] canadian viagra goodrx viagra <a href="https://topedstoreusa.com/#&quot;&gt;how much does viagra cost&lt;/a&gt; how much will generic viagra cost cheapest generic viagra

no.117014 royceagar 180.250.12.19 2020-05-11 05:15

single mom rules for dating https://datingactually.site single mom rules for dating asian online dating australia

no.116981 matthiasshore 79.137.112.61 2020-05-07 15:44

christian singles free online dating https://onpointdating.site christian singles free online dating Speed dating Downtown Los angeles

no.116979 niklaspartain 195.154.61.127, 2020-05-07 12:31

starter questions for online dating https://datingweblog.site starter questions for online dating sapiosexual online dating

发表评论:

邮箱: