Logback--logback applications in projects (Web or Java) __web

Source: Internet
Author: User
Tags documentation log4j
PrefaceSome time ago, the team in the framework of the STRUTS2 switch to SPRINGMVC, to do a system system, while some common components extracted, independent, team members proposed to use the Logback log, because the previous basic components used by the log4j, the logback are not familiar with, So I learned a little logback, learning process, found the right Chinese information is less, combined with their own projects, share the Logback in the project application and their own problems encountered. To think back to the process of using Logback, the official document is the most accurate and most complete learning resources, although it is in English, just at this time in the translation of an English book, can calm down to see the official documents, to solve some of the problems encountered in the project. The logback used in the project is configured as follows: Its files have been placed on GitHub, address: https://github.com/wangdongsong/java/blob/master/src/main/java/com/wds/ Java/base/web/log/logback.xml
<?xml version= "1.0" encoding= "UTF-8"?> <!--Note: 1, log level and file logging using hierarchical records, level and log file name, the different levels of log information recorded in different log files for example: E The rror level is recorded to Log_error_xxx.log or Log_error.log (the file is the log file for the current record), and Log_error_xxx.log is the archive log, the log file is recorded by date, and if the log file size is equal to or greater than 2M in the same day,
	The same is true for 0, 1, 2 ... order names, such as log-level-2013-12-21.0.log other levels of logging. 2. If the file path is developed, tested, run the project in Eclipse, then go to Eclipse's installation path to find the logs folder to the relative path.
		/logs. If deployed to Tomcat, then in the logs file under Tomcat 3, Appender fileerror corresponding to the error level, the file name in log-error-xxx.log form Filewarn corresponding warn level,
		The filename is named in Log-warn-xxx.log FileInfo corresponding to the info level, the filename is named Log-info-xxx.log, Filedebug corresponds to the debug level, and the filename is named Log-debug-xxx.log StdOut log information to control, to facilitate development testing using--> <configuration> <!--run in Eclipse, go to Eclipse's installation directory for log files, Tomcat, Please find--> <property name= "Log_path value=" under the Tomcat directory. /logs "/> <!--logger, date scrolling record--> <appender name=" Fileerror "class=" Appender > <!--the path and filename of the log file being logged--> <file>${LOG_PATH}/log_error.log</file> <!--logThe logger's scrolling strategy, recorded by date, by size--> <rollingpolicy class= "Ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <
   			!--the path of the archived log file, for example, today is the 2013-12-21 log, and the currently written log file path is specified for the file node, which can be set to a different path than the file specified file path, thereby placing the current log file or archive log file in a different directory. The 2013-12-21 log file is specified by Filenamepattern. %D{YYYY-MM-DD} Specifies the date format,%i the specified index--> <filenamepattern>${log_path}/log-error-%d{yyyy-mm-dd}.%i.log</ Filenamepattern> <!--In addition to logging, the log file is configured to be no more than 2M, and if more than 2M, the log file starts with index 0, naming the log file, such as Log-error-2013-12-21.0.log--&
   			Gt <timebasedfilenamingandtriggeringpolicy class= "Ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP" > <ma
   		Xfilesize>2mb</maxfilesize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <!--Append method log--> <append>true</append> <!--log file format--> <encoder class= "Ch.qos.logback . classic.encoder.PatternLayoutEncoder "> <pattern>%-5p [%d]%c:%l-%m%n</pattern> <charset>utf -8</charset> </encoder> <!--This log file records only the error level--> <filter class= "ch.qos.logback.classic.filter.Le Velfilter "> <level>error</level> <onMatch>ACCEPT</onMatch> <onmismatch>deny </onMismatch> </filter> </appender> <appender name= "Filewarn" class= "Ch.qos.logback.core.rolli Ng. Rollingfileappender "> <file>${LOG_PATH}/log_warn.log</file> <rollingpolicy class=" Ch.qos.logback.core.rolling.TimeBasedRollingPolicy "> <filenamepattern>${log_path}/log-warn-%d{ yyyy-mm-dd}.%i.log</filenamepattern> <timebasedfilenamingandtriggeringpolicy class= " Ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP "> <maxFileSize>2MB</maxFileSize> </ti mebasedfilenamingandtriggeringpolicy> </rollingPolicy> <append>true</append> <encoder CLA ss= "Ch.qos.logback.classic.encoder.PatternLayoutEncoder" > <pattern>%-5p [%d]%c:%l-%m%n</pattern> <charset>utf-8</charset> </encoder> <!--This log file is only recorded Record WARN level, do not record log greater than WARN level--> <filter class= "Ch.qos.logback.classic.filter.LevelFilter" > <level>warn </level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter&gt
	; </appender> <appender name= "FILEINFO" class= "Ch.qos.logback.core.rolling.RollingFileAppender" > < file>${log_path}/log_info.log</file> <rollingpolicy class= " Ch.qos.logback.core.rolling.TimeBasedRollingPolicy "> <filenamepattern>${log_path}/log-info-%d{ yyyy-mm-dd}.%i.log</filenamepattern> <timebasedfilenamingandtriggeringpolicy class= " Ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP "> <maxFileSize>2MB</maxFileSize> </ti mebasedfilenamingandtriggeringpolicy> </rollingPolicy> <append>true</append> <encoder class= "Ch.qos.logback.classic.encoder.PatternLayoutEncoder" > <pattern>%-5p [%d]%c:%l-%m%n</ Pattern> <charset>utf-8</charset> </encoder> <!--This log file records only the info level and does not record logs greater than the info level--> &L T;filter class= "Ch.qos.logback.classic.filter.LevelFilter" > <level>INFO</level> <onMatch> accept</onmatch> <onMismatch>DENY</onMismatch> </filter> </appender> <app Ender name= "Filedebug" class= "Ch.qos.logback.core.rolling.RollingFileAppender" > <file>${log_path}/log_ debug.log</file> <rollingpolicy class= "Ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <fil Enamepattern>${log_path}/log-debug-%d{yyyy-mm-dd}.%i.log</filenamepattern> < Timebasedfilenamingandtriggeringpolicy class= "Ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP" > <maxfil Esize>2mb</maxfilesize> </timebasedfilenamingandtriggeringpolicy> </rollingPolicy> <append>true</append> <encoder class= "CH.QOS.LOGBACK.CLASSIC.E Ncoder. Patternlayoutencoder "> <pattern>%-5p [%d]%c:%l-%m%n</pattern> <charset>utf-8</charset&gt
		; </encoder> <!--This log file records only the debug level and does not record logs larger than the debug level--> <filter class= " Ch.qos.logback.classic.filter.LevelFilter "> <level>DEBUG</level> <onmatch>accept</ onmatch> <onMismatch>DENY</onMismatch> </filter> </appender> <appender name= "s Tdout "class=" Ch.qos.logback.core.ConsoleAppender "> <Target>System.out</Target> <encoder> ;p attern>%-5p [%d]%c:%l-%m%n</pattern> <charset>utf-8</charset> </encoder> <!-- Log appender is for development use, configuring only the bottom level, the console output log level is greater than or equal to this level of log information--> <filter class= "
	Ch.qos.logback.classic.filter.ThresholdFilter "> <level>DEBUG</level> </filter></appender> <!--To configure logging levels for individual packages, if the level of root is greater than this level, the application scenario is also output at this level: the production environment typically does not set the log level to trace or debug, but for verbose logging of SQL statements, You can set the hibernate level to debug so that a Hibernate debug level log appears in the log file, while other packages output logs at the level of root--> <logger name= " Org.hibernate.SQL "level=" Debug "/> <logger name=" Org.hibernate.jdbc "level=" Debug "/> <logger" name= "
		Org.springframework "level=" DEBUG/> <!--production environment, configure this level to the appropriate level, too many names log files or affect program performance--> <root level= "INFO" >
		<appender-ref ref= "Filedebug"/> <appender-ref ref= "FILEINFO"/> <appender-ref "ref=" FILEWARN <appender-ref ref= "Fileerror"/> <!--production environment will please stdout remove--> <appender-ref ref= "stdout"/> </root&gt
; </configuration>


Logback

Logback is a log component developed by the founder of Log4j to replace log4j. Logback's architecture design is universal enough to be suitable for different environments, and currently logback is divided into three modules: Lobback-core,logback-classic and logback-access.

The core module is the foundation of the other two modules, the classic is the core extension, the log4j is a huge improvement version. The logback-classic itself implements the SL4J API, so it is easy to switch between Logback and other log systems, such as log4j, JDK1.4 in Java.util.logging (June). The third module, access, integrates the servlet container, providing the ability to access logs through HTTP, and if you know access can access its stand-alone document http://logback.qos.ch/access.html.

The Logback logging level has trace, debug, info, warn, error, and reference to the official documentation (http://logback.qos.ch/manual/architecture.html) for the base level.ConfigurationLogback can be configured either programmatically or in XML, groovy format, and users who originally used log4j can convert log4j.properties to logback.xml files through the property converter. When I use this converter, I can convert the success, but in the Web-app log output a little problem, and then write their own logback.xml file, Logback read the configuration or property file steps: Logback tries to find Logback.groovy files under the classpath. If Logback.groovy is not found, locate the Logback-test.xml file under the classpath. If the Logback-test.xml file is not found, you will find the Logback.xml file under the Classpath (this is the way you use it, placing the Logback.xml configuration file under the Classpath). If none is found, Logback uses Basicconfigurator to start the default configuration, which outputs the log to control. The 4th step, which means using the default configuration, provides the default (most basic) logging capabilities. If you use Maven, you can place the Logback-test.xml configuration file under the Src/test/resources folder, so You can use the Logback-test.xml configuration while testing, and use Logback.xml in the product, which I also use for wood. My usage is in Web-app, the Logback.xml file is placed under the Src/main/resources path, and in Java-app, the file is placed under Src/main/java, as shown in the following figure:
WEB-APP directory structure diagram:
Directory structure diagram for Java engineering:
AppenderLogback Log Appender must implement the Ch.qos.logback.core.Appender interface, commonly used in Consoleappender, Fileappender and Rollingfileappender, The class diagram is as follows:

There are two types of appender used in the project: Consoleappender and Rollingfileappender consoleappender: Mainly output log information to control, in the log file above, StdOut's append is Consoleappender rollingfileappender: scrolling logs by date, For example, Rollingfileappender logs to a Log.txt file, and once the conditions set are met, log information is logged to another file, which inherits Fileappender. The two important components that interact with Rollingfileappender are: Rollingpolicy and Triggeringpolicy. The former is responsible for rolling the god Horse, the latter is responsible for the God horse when rolling. Any time use, Rollingfileappender must have Rollingfileappender and Triggeringpolicy configuration, But if its rollingpolicy also implements the Triggeringpolicy interface, just specify the former. This point needs to note: The author in use, ignore this, resulting in log scrolling unsuccessful. The specific properties are as follows: (in the case of the project used) file: Inherits from Fileappender, specifies the log file name. Append: Inherits from Fileappender, true, the log is appended to the end of the log file, False deletes the log file that already exists, and defaults to true. Encoder:encoder, specifying log format and encodingRollingpolicy Timebaserollingpolicy may be the most commonly used scrolling strategy, which is based on time, such as days or months, while this class implements both the Rollingpolicy interface and the Triggeringpolicy interface. Only this class is used in the Rollingfileappender, the rollingpolicy is used in the project, the date format is specified by%d{yyyy-mm-dd}, and%i is the index. Specific configuration can refer to the above configuration file. Rollingpolicy also has this other attribute, which can refer to the official documentation, not used in the project, such as the maximum historical period. Logback also provides Fixedwindowrollingpolicy, which is not used and can be referenced by official documents. In addition, we can also decide on the time and size of the rolling strategy, which is used in the project, the project using the configuration file visible above, the following is the official provision of the configuration file:

< configuration> <appender name= "rolling" class= "Ch.qos.logback.core.rolling.RollingFileAppender" > <file >mylog.txt</file> <rollingpolicy class= "Ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > < !--rollover daily--> <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern> <timeb Asedfilenamingandtriggeringpolicy class= "Ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP" > <!- -or whenever the file size reaches 100MB--> <maxFileSize>100MB</maxFileSize> </timebased filenamingandtriggeringpolicy> </rollingPolicy> <encoder> <PATTERN>%MSG%N</PATTERN&G
    T </encoder> </appender> <root level= "DEBUG" > <appender-ref ref= "rolling"/> </ROOT&G

T </configuration> 

TriggeringpolicySizebasedtriggeringpolicy: Controls the current file size and, if the log file is larger than the specified size, triggers scrolling, which is specified by the MaxFileSize property, which can be in kilobytes, MB, and GB, and the following configuration file (provided by the official Not used in project):
<configuration>
  <appender name= "FILE" class= "Ch.qos.logback.core.rolling.RollingFileAppender" >
    <file>test.log</file>
    <rollingpolicy class= " Ch.qos.logback.core.rolling.FixedWindowRollingPolicy ">
      <filenamepattern>test.%i.log.zip</ filenamepattern>
      <minIndex>1</minIndex>
      <maxIndex>3</maxIndex>
    </ rollingpolicy>

    <triggeringpolicy class= "Ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy" >
      <maxFileSize>5MB</maxFileSize>
    </triggeringPolicy>
    <encoder>
      < pattern>%-4relative [%thread]%-5level%logger{35}-%msg%n</pattern>
    </encoder>
  </ appender>
	
  <root level= "DEBUG" >
    <appender-ref ref= "FILE"/>
  </root>
</ Configuration>
FilterThe project uses two kinds of levelfilter and Thresholdfilter, the official also provides other filter can refer to. Levelfilter: Based on an exact match, if the level of the event is the same as the configured level, it will be accepted or rejected based on the properties of the Onmatch and Onmismatch that are already configured, if the Fileerror, Filewarn, FILEINFO, Filedebug, the following configuration is provided by the official configuration:
<configuration>
  <appender name= "CONSOLE" class= "Ch.qos.logback.core.ConsoleAppender" >
    < Filter class= "Ch.qos.logback.classic.filter.LevelFilter" >
      <level>INFO</level>
      < onmatch>accept</onmatch>
      <onMismatch>DENY</onMismatch>
    </filter>
    < encoder>
      <pattern>
        %-4relative [%thread]%-5level%logger{30}-%msg%n
      </pattern>
    </encoder>
  </appender>
  <root level= "DEBUG" >
    <appender-ref ref= "CONSOLE"/>
  </root>
</configuration>

thresholdfilter: Specifies the lower level, events below this level will be rejected, if the configuration file used in the project is configured in stdout, the following is the official provisioning:

<configuration>
  <appender name= "CONSOLE"
    class= "Ch.qos.logback.core.ConsoleAppender" >
    <!--deny all events with a level below INFO, which is TRACE and DEBUG-->
    <filter class= "Ch.qos.logback.class Ic.filter.ThresholdFilter ">
      <level>INFO</level>
    </filter>
    <encoder>
      <pattern>
        %-4relative [%thread]%-5level%logger{30}-%msg%n
      </pattern>
    </ encoder>
  </appender>
  <root level= "DEBUG" >
    <appender-ref ref= "CONSOLE"/>
  </root>
</configuration>
The official provides other filter, can also realize their own filter, specific reference to the official documents.

Question 1, path This issue is detailed in the configuration file, please refer to. 2. The jcl-over-slf4j and jul-to-slf4j are available for spring or other integrated logback that have already used log4j, common-logging or java.util.longging. JCL refers to Common-logging,jul refers to java.utils.longging, if you need to unify the spring log, you need to add JCL-OVER-SLF4J package to work, the project using MAVEN development, rely on the following:

<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactid>logback-core</ artifactid>
			<version>1.0.13</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.0.13</version>
		</dependency>
		<dependency>
			<groupId> org.slf4j</groupid>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.7.0 </version>
		</dependency>
		<dependency>
			<groupid>ch.qos.logback</ groupid>
			<artifactId>logback-access</artifactId>
			<version>1.0.13</version >
		</dependency>
3, code differentiation source writing:
if (logger.isinfoenabled ()) {
	Logger.info ("* * * baseauthoritiesresourcesserviceimpl.getlist () method begin**** *");
}
After using Logback, the If judgment can be removed as follows:
Logger.debug ("* * * Basedictionaryserviceimpl.delete () method begin*****");
If the log level is higher than debug, this row of log information will not be exported.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.