log4j2的詳細使用及問題解決[總結]

來源:互聯網
上載者:User

log4j2相對於log4j 1.x有了脫胎換骨的變化,其官網宣稱的優勢有多線程下10幾倍於log4j 1.x和logback的高輸送量、可配置的審計型日誌、基於外掛程式架構的各種靈活配置等。如果已經掌握log4j 1.x,使用log4j2還是非常簡單的。

先看一個樣本 1 基礎配置

普通Java項目手動添加jar包

問題:

糾正一下:本人親自在搭建項目的時候,發現如果項目中只有這兩個jar,是顯示不正常的,需要加上log4j2的實現

另外一個比較重要的地方就是,有些日誌無法使用log4j2完全接管整個系統的日誌,可能是由於其他的依賴包依賴帶著log4j的包,導致會出現下面的現象:

log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

解決方案是:將log4j 1.x給排除掉,使用

<exclusion>
<artifactId>log4j</artifactId>
<groupId>log4j</groupId>
</exclusion>

[html]  view plain  copy  print ? 糾正前 log4j-api-2.5.jar   log4j-core-2.5.jar 糾正後 <dependency>
<groupId>org.apache.logging.log4j</groupId>  -->添加後也支援log4j以前的使用方式
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
糾正後支援的使用方式有:  Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);  log4j2的專屬方式
Logger logger = LoggerFactory.getLogger(EchoFilter.class);      log4j的使用方式

Maven項目pom.xml

[html]  view plain  copy  print ? <dependencies>       <dependency>           <groupId>org.apache.logging.log4j</groupId>           <artifactId>log4j-api</artifactId>           <version>2.5</version>       </dependency>       <dependency>           <groupId>org.apache.logging.log4j</groupId>           <artifactId>log4j-core</artifactId>           <version>2.5</version>       </dependency>   </dependencies>   測試代碼

[html]  view plain  copy  print ? public static void main(String[] args) {       Logger logger = LogManager

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.