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.119395 augusthowarth 62.149.29.153 2021-01-13 16:58

Hey guys, I am Kyran Mckinney an expert in content writing. I love solving people’s problems and make them happy. That is what I have been doing for decades now. I have been writing since I was 12 years old and never knew it would turn out to be a full-time career. I have also been able to handle several assignments that involves writing. And I worked in three organizations as a volunteer to assist people.My passion has always been to help people succeed. And I go the extra mile to make t

no.118792 nameb8 178.159.37.69 2020-12-31 12:38

sildenafil neuraxpharm 50mg <a href="https://cheapgenericpills.com/">sildenafil tabletas</a> sildenafil clittoris https://cheapgenericpills.com/

no.118552 name7r 178.159.37.69 2020-12-29 12:25

does molina cover sildenafil <a href="https://upharmacy24.com/">sildenafil teva 20 mg price</a> best price for sildenafil 50 mg https://upharmacy24.com/

no.118479 nameuf 178.159.37.69 2020-12-28 18:58

sildenafil oral absorption <a href="https://tevaviagra.com/">sildenafil hydrocodone mixing</a> cost of sildenafil 20 mg https://tevaviagra.com/

no.118465 name09 178.159.37.69 2020-12-27 17:11

cheapest place to get sildenafil 50mg <a href="https://fortunegraphite.com/">sildenafil for women cream</a> will i get an erection using sildenafil 20 mg https://fortunegraphite.com/

no.118282 name9h 178.159.37.69 2020-12-26 07:12

over the counter similar to viagra <a href="https://judrxstore.com/">lowest prices on viagra</a> older man on viagra https://judrxstore.com/

no.118182 cbdr2 178.159.37.69 2020-07-28 05:24

do cbd edibles get you high? <a href="https://cbdediblescandy.com/CBD-Edibles-Store/grape-cbd-syrup-75-mg.html">what mg to to take of cbd gummies</a> cbd gummies eureka springs

no.118168 cbd0g 178.159.37.69 2020-07-27 20:37

pub med health benefits of cbd oil <a href="https://cannabisoil2018.com/oil-pulling-the-alternative-medcine-therapy-that-cures-many-diseases-4-virtually-free-thank-go/index.html">best benefits from cbd oil</a> benefits of cbd in olive oil

no.118155 cbdfa 178.159.37.69 2020-07-26 00:48

does cbd oil have any benefits <a href="https://wfieldsforpets.com/dog-daycare-videos.html">benefits of cbd oil in humans</a> cbd benefits for skin

no.118148 cbdcn 178.159.37.69 2020-07-25 09:28

cbd properties and benefits <a href="https://cbdoilcompanies.com/growing-cannabis-in-super-soil.html">cbd oil benefits sports</a> what cbd benefits

no.118143 cbd98 178.159.37.69 2020-07-25 06:17

4:1 cbd oil cats benefits <a href="https://cbdhempoilsale.us/cbd-oil-health-benefits.html">health benefits of pure cbd extract</a> 15 mg cbd honey sticks benefits

no.118140 arietta960 5.188.210.18 2020-07-24 15:00

[url=https://extraint.ru/catalog/torsher_noctambule]Настольная лампа Aqua Cil[/url] или [url=https://extraint.ru/catalog/stol_zhurnalnyj_375-t1]Стол письменный Alma 73036[/url] https://extraint.ru/catalog/page/29/

no.118130 hethertan 37.115.216.98 2020-07-22 11:59

Обратились в аптеку по рекомендации врача и не прогадали, препарат прекрасно действует! [url=https://india-express.net/shop/170/desc/cabalois40]cabozatinib[/url]

no.118081 cbdhx 178.159.37.69 2020-07-21 00:14

cbd oil cannabidiol benefits <a href="https://cannabidioloilsale.com/cbd-oil-for-sale.html">cbd oil benefits vapor</a> benefits of cbd oil on your skin

no.118069 thcia 178.159.37.77 2020-07-20 09:58

cbd online india <a href="https://cbdoilcompanies.com/">my health cbd book online</a> liquid sky cbd buy online

no.118061 thcax 178.159.37.77 2020-07-20 03:00

cbd gold capsules 10 pack <a href="https://cbdpillsforsale.org/">best cbd & cbg capsules</a> select cbd gel capsules

no.118055 cbd6t 178.159.37.69 2020-07-20 01:13

cbd provide medical benefits <a href="https://cannabisoil2018.com/">cbd massage lotion benefits</a> cbd benefits or uses

no.118045 thcwf 178.159.37.77 2020-07-19 22:25

is cbd oil good for dogs with collapsing trachea <a href="https://cannabidioloilfordogs.com/">reaspe for cbd dog trats</a> side effect of cbd oil on dogs

no.118044 cbdym 178.159.37.69 2020-07-19 22:21

buy viagra otc <a href="https://judproducts.com/generic/levitra_prices.htm">best place to buy viagra online no prescription</a> how to buy viagra online without getting ripped off

no.118034 thcrr 178.159.37.77 2020-07-19 20:02

will cbd calm a hyper dog <a href="https://wfieldsforpets.com/">human cbd oil for dog</a> cyxlosporin and cbd oil for dogs

no.118033 cbdd5 178.159.37.69 2020-07-19 19:57

places to buy viagra over the counter <a href="https://judpharmacy.com/importing.htm">buy best viagra online</a> is it legal to buy viagra online from canada

no.118025 thcv4 178.159.37.77 2020-07-19 08:48

the very best cbd for dogs <a href="https://cbdoilfordog.org/">cbd dog anxiety treats</a> dog cbd treatibles and

no.118005 cbdln 178.159.37.69 2020-07-17 03:19

buy generic viagra using paypal <a href="https://judproducts.com/">buy cheap viagra pills online</a> viagra india buy

no.117707 remo8785 5.188.210.18 2020-07-09 04:01

[url=https://www.victorinox.market/product/GR171113979]нож для чистки овощей victorinox[/url] или [url=https://www.victorinox.market/product/GR1711131046]купить чехол для ножа victorinox[/url] https://www.victorinox.market/product/VX200512133

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>

发表评论:

邮箱: