logback官方文檔閱讀筆記(四)


前言


logback官方文檔html

本文關於官方文檔第三章:Logback configurationjava

本文的小標題英文直接從官方文檔複製,能夠直接在官方文檔中經過搜索馬上定位到對應的官方文檔中對應的小節。web

因第三章篇幅較長,會分爲幾份筆記。本章第二份筆記:

api

正文


logback的配置文件


Let us begin by discussing the initialization steps that logback follows to try to configure itself:oracle

  1. Logback tries to find a file called_logback-test.xml in the classpath.
  2. If no such file is found, logback tries to find a file called_logback.groovy in the classpath.
  3. If no such file is found, it checks for the file_logback.xml in the classpath..
  4. If no such file is found,service-provider loading facility (introduced in JDK 1.6) is used to resolve the implementation of com.qos.logback.classic.spi.Configurator interface by looking up the file_META-INF\services\ch.qos.logback.classic.spi.Configurator_in the class path. Its contents should specify the fully qualified class name of the desired Configurator implementation.
  5. If none of the above succeeds, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.

The last step is meant as last-ditch effort to provide a default (but very basic) logging functionality in the absence of a configuration file.app

If you are using Maven and if you place the_logback-test.xml_under the src/test/resources folder, Maven will ensure that it won't be included in the artifact produced. Thus, you can use a different configuration file, namely logback-test.xml during testing, and another file, namely, logback.xml , in production.ide

FAST START-UP t takes about 100 miliseconds for Joran to parse a given logback configuration file. To shave off those miliseconds at aplication start up, you can use the service-provider loading facility (item 4 above) to load your own custom Configurator class with BasicConfigrator serving as a good starting point.ui

這一段主要講了logback如何定位它的配置文件,在有多個可用的配置文件下不一樣配置文件的優先級。
最後講了如何加快帶有logback的軟件的啓動速度。但涉及的知識點在於service-provider loading facility,本文很少作討論。this


默認配置的狀況


Assuming the configuration files logback-test.xml or logback.xml are not present, logback will default to invoking BasicConfigurator which will set up a minimal configuration. This minimal configuration consists of a ConsoleAppender attached to the root logger. The output is formatted using a PatternLayoutEncoder set to the pattern %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n. Moreover, by default the root logger is assigned the DEBUG level.

logback的解耦


Except code that configures logback (if such code exists) client code does not need to depend on logback. Since SLF4J permits the use of any logging framework under its abstraction layer, it is easy to migrate large bodies of code from one logging framework to another.

除了配置logback的代碼外,客戶端代碼不須要依賴於logback。這是由於SLF4J做爲抽象層橫置在客戶代碼與日誌系統實現之間,客戶代碼只須要對SLF4J負責,只要是遵循SLF4J而實現的日誌系統,相互之間都能更換。url


默認配置的xml形式表述


<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

輸出logback內部準備信息


If warnings or errors occur during the parsing of the configuration file, logback will automatically print its internal status data on the console. Note that to avoid duplication, automatic status printing is disabled if the user explicitly registers a status listener (defined below).

In the absence of warnings or errors, if you still wish to inspect logback's internal status, then you can instruct logback to print status data by invoking the print() of the StatusPrinter class. The MyApp2 application shown below is identical to MyApp1 except for the addition of two lines of code for printing internal status data.

public static void main(String[] args) {
  // assume SLF4J is bound to logback in the current environment
  LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
  // print logback's internal status
  StatusPrinter.print(lc);
  ...
}

Instead of invoking StatusPrinter programmatically from your code, you can instruct the configuration file to dump status data, even in the absence of errors. To achieve this, you need to set the debug attribute of the configuration element, i.e. the top-most element in the configuration file, as shown below. Please note that this debug attribute relates only to the status data. It does not affect logback's configuration otherwise, in particular with respect to logger levels. (If you are asking, no, the root logger will not be set to DEBUG.)

截圖.jpg

Setting debug="true" within the <configuration> element will output status information, assuming that:

the configuration file is found
the configuration file is well-formed XML.
If any of these two conditions is not fulfilled, Joran cannot interpret the debug attribute since the configuration file cannot be read. If the configuration file is found but is malformed, then logback will detect the error condition and automatically print its internal status on the console. However, if the configuration file cannot be found, logback will not automatically print its status data, since this is not necessarily an error condition. Programmatically invoking StatusPrinter.print() as shown in the MyApp2 application above ensures that status information is printed in every case.

以後還有幾段文字與此有關,但我認爲意義不大,再也不復制。

四件事
第一,默認的,若是logback在啓動配置準備階段(這一階段在於解析配置文件)出現了錯誤或警告,纔會有輸出相關信息。
第二,若是設置了專門的內部信息監聽者,則第一的默認輸出不會有。
第三,能夠經過第二段所示方法要求輸出所有的或者也輸出說低於錯誤和警告級別的信息。
第四,經過修改配置文件中根元素<configure>,爲其添加debug="true",也能夠實現第三件事的效用。

以後一些原文沒有在複製粘貼過來,它們又講了在logback的配置文件糟糕的狀況下,該如何作以能繼續輸出信息。感受這一塊在實踐中的使用並很少,所以本文並不繼續深究。


Specifying the location of the default configuration file as a system property


經過設置logback.configurationFile的系統變量,能夠修改logback定位(在此屬性被賦值的狀況下,其是最高優先級)的配置文件的路徑。
但其必需在logback的任何Logger被加載出來前修改。


Automatically reloading configuration file upon modification


<configuration scan="true"> 
  ... 
</configuration>

By default, the configuration file will be scanned for changes once every minute. You can specify a different scanning period by setting the scanPeriod attribute of the <configuration> element. Values can be specified in units of milliseconds, seconds, minutes or hours. Here is an example:

<configuration scan="true" scanPeriod="30 seconds" > 
  ...
</configuration>

If no unit of time is specified, then the unit of time is assumed to be milliseconds, which is usually inappropriate. If you change the default scanning period, do not forget to specify a time unit.

As it is easy to make errors while editing a configuration file, in case the latest version of the configuration file has XML syntax errors, it will fall back to a previous configuration file free of XML syntax errors.

我以前一直認爲是一旦修改配置文件則重載配置,這致使我幾回調整配置文件而不重啓應用,試圖看看本身設置後的配置文件帶給logback什麼變化。
但細讀這段話,其實logback不能馬上知道配置文件是否被修改了(也是,它歸根結底一個jar包,憑什麼能知道),它只是每隔一段時間去掃描比對,比對出有沒有被修改。

最後它說開啓掃描後自動,若是發現修改後的配置文件有問題,則會回退到最近的無問題的配置文件。


Enabling packaging data in stack traces


<configuration packagingData="true">
  ...
</configuration>

或者

LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
  lc.setPackagingDataEnabled(true);

開啓輸出packaging data數據。

何爲packaging data?

Packaging data consists of the name and version of the jar file whence the class of the stack trace line originated.

截圖.jpg


Viewing status messages


Logback collects its internal status data in a [StatusManager](http://logback.qos.ch/xref/ch/qos/logback/core/status/StatusManager.html) object, accessible via the LoggerContext.

Given a StatusManager you can access all the status data associated with a logback context.

老生常談如何查看logback內部配置過程當中的信息。
不過接下來開始整活了。

Logback-classic ships with a servlet called ViewStatusMessagesServlet. This servlet prints the contents of the StatusManager associated with the current LoggerContext as an HTML table.

To add this servlet to your web-application, add the following lines to its WEB-INF/web.xml file.

<servlet>
    <servlet-name>ViewStatusMessages</servlet-name>
    <servlet-class>ch.qos.logback.classic.ViewStatusMessagesServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>ViewStatusMessages</servlet-name>
    <url-pattern>/lbClassicStatus</url-pattern>
  </servlet-mapping>

The ViewStatusMessages servlet will be viewable at the URL http://host/yourWebapp/lbClas...

經過將ViewStatusMessagesServlet註冊,能夠直接訪問該組件從而以HTML的形式查看logback內部狀態信息。

Listening to status messages


說來講去,仍是一個將logback的內部狀態信息對外輸出的功能。

Stopping logback-classic


Stopping the context will close all appenders attached to loggers defined by the context and stop any active threads in an orderly way.

stop操做的效果。

LoggerContext loggerContext = (LoggerContext) 
LoggerFactory.getILoggerFactory();
loggerContext.stop();
<configuration debug="true">
   <!-- in the absence of the class attribute, assume 
   ch.qos.logback.core.hook.DefaultShutdownHook -->
   <shutdownHook/>
  .... 
</configuration>

Note that you may install a shutdown hook of your own making by setting the class attribute to correspond to your shutdown hook's class name.

非web應用的java程序stop的兩種方法。

The default shutdown hook, namely DefaultShutdownHook, will stop the logback context after a specified delay (0 by default). Stopping the context will allow up to 30 seconds for any log file compression tasks running in the background to finish. In standalone Java applications, adding a <shutdownHook/> directive to your configuration file is an easy way to ensure that any ongoing compression tasks are allowed to finish before JVM exit.

In applications within a Web server, webShutdownHook will be installed automatically making <shutdownHook/> directive quite redundant and unnecessary.
Logback-classic will automatically ask the web-server to install a LogbackServletContainerInitializer implementing the ServletContainerInitializer interface (available in servlet-api 3.x and later). This initializer will in turn install and instance of LogbackServletContextListener. This listener will stop the current logback-classic context when the web-app is stopped or reloaded.

web應用的java程序的stop方法

You may disable the automatic the installation of LogbackServletContextListener by setting a <context-param> named logbackDisableServletContainerInitializer in your web-application's web.xml file. Here is the relevant snippet.

<web-app>
    <context-param>
        <param-name>logbackDisableServletContainerInitializer</param-name>
        <param-value>true</param-value>
    </context-param>
    .... 
</web-app>

Note that logbackDisableServletContainerInitializer variable can also be set as a Java system property an OS environment variable. The most local setting has priority, i.e. web-app first, system property second and OS environment last.

對web程序的自動stop能夠關閉。雖然不知道爲何要關閉。

相關文章
相關標籤/搜索