I declare that this content refers to the official website of Logback and a foreign blog. I have not tried to write the logs to the remote server, but simply translated the official documents, and some grammar is not accurate. Each part has the chapter address of the official website. It is suggested to read the official website directly if you don’t understand. (The official website article has not been translated, only part of the translation, the author is also trying to code words, to be continued…)

Gitbook, mingrn.gitbooks.io

Spring-boot, as a micro-service application, integrates with the Logback log framework by default. Logback is a next-generation logging framework developed by the authors of the Log4J framework. It is more efficient, can adapt to a wide range of operating environments, and naturally supports SLF4J.

I’ve been working with SpringBoot for a while, and I’ve been using Log4j2 for spring development. The logback framework is integrated with SpringBoot by default. So determined to read the official website, and their understanding and the original simple translation, can be used for future reference, I hope to also help logback understanding of children’s feet…

Table error: Because the markdown editor used by the author is a flying elephant note, I can synchronize Github (if you feel uncomfortable reading on this page, you can go to Github, I have converted Markdown into HTML, directly download it and open it in the browser for reading [the effect is great! See the picture below]) and then transplant it to Nuggets. So there will be some format problems, if I find the author will be corrected without stopping, thank you for your reminding!

Markdown to HTML renderings

The default value is logback

As you can see from the figure above, the log output content elements are as follows

  • Time and date: accurate to the millisecond
  • Log level: ERROR, WARN, INFO, DEBUG or TRACE
  • The process ID
  • The separator:---Identifies the start of the actual log
  • Thread name: enclosed in square brackets (may truncate console output
  • Logger name: The name of the class that normally uses the source code

As the official website says: 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 Basic configuration

Create logback. XML

Spting-boot The logback integrated by default prints some log information, but is not friendly. It doesn’t meet our daily development needs. Therefore, we can create logback. XML or logback-spring. XML files in the root directory for custom configuration

In a Spring Boot application, you can specify a Logback XML configuration file as logback.xml or logback-spring.xml in the project classpath. The Spring Boot team however recommends using the -spring variant for your logging configuration, logback-spring.xml is preferred over logback.xml. If you use the standard logback.xml configuration, Spring Boot may not be able to completely control log initialization.

Sping-boot default integrated logback print log style I like, and the default print log although not enough to meet our daily development needs. But we can make some modifications to it and get the log output that we want, and if we want to customize the log output to the console and want to print different colors for different messages, it would be like taking off your pants, wouldn’t it? By default, spring-boot does this out of the box by default, so we can reference it directly.

The SpringBoot development version I use is 2.0.2.REALEASE, so go directly to the Spring-boot-2.0.2. REALEASE dependency package. You can see that the org.springFramework. boot package level directory has many default configuration dependency classes

Of course, this is mainly looking at the logging package. In this package there is a logback package, which contains the default logback log configuration file.

There are four main XML configuration files, and I can introduce the base.xml configuration file in the logback-spring. XML configuration file we created.

<configuration>
	<include resource="org/springframework/boot/logging/logback/base.xml" />
</configuration>
Copy the code

Now we can restart the project and see that the printed log information has the same effect as not creating a custom log profile. The default springBoot configuration logback is this configuration file.

Now let’s take a look at what’s in the base.xml configuration file.

<included>
	<include resource="org/springframework/boot/logging/logback/defaults.xml" />
	<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
	<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
	<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
	<root level="INFO">
		<appender-ref ref="CONSOLE" />
		<appender-ref ref="FILE" />
	</root>
</included>
Copy the code

The most notable of these are three

  • defaults.xml
  • console-appender.xml: The console outputs log information
  • file-appender.xml: Log file storage

Therefore, if you do not directly refer to the base.xml configuration file, referring to the other three configuration files has the same effect. It is recommended to refer to the file separately and only to defaults.xml and console-appender.xml. If multiple apps are deployed in the same environment, the log output permission may be incorrect.

Logback Basic properties

Now take a look at the format that you need to follow to customize logBack log output

Basic Example (for reference only)

<configuration debug="true">

	<include resource="org/springframework/boot/logging/logback/defaults.xml" />
	<include resource="org/springframework/boot/logging/logback/console-appender.xml" />

	<property name="APP_NAME" value="Logback"/>
	<property name="APP_HOME" value="/home/logback"/>
	<property name="LOG_HOME_PATH" value="${APP_HOME}/logs"/>
	<property name="DEBUG_LOG_FILE" value="${LOG_HOME_PATH}/debug/${APP_NAME}_debug" />
	<property name="FILE_LOG_PATTERN" value="% d {MM - dd yyyy - HH: MM: ss. The SSS} ${LOG_LEVEL_PATTERN: - % 5 p} ${PID: -} [t] % % - 40.40 logger {39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}" />


	<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<encoder>
			<pattern>${FILE_LOG_PATTERN}</pattern>
		</encoder>

		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<FileNamePattern>${DEBUG_LOG_FILE}.%d{yyyy-MM-dd}.log</FileNamePattern>
			<MaxHistory>60</MaxHistory>
		</rollingPolicy>

		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>DEBUG</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
	</appender>
	<root level="INFO">
		<appender-ref ref="DEBUG_FILE" />
	</root>

	<logger name="com.mingrn.logback" level="DEBUG">
		<appender-ref ref="DEBUG_FILE"/>
	</logger>

	<logger name="com.mingrn.logback.repository" level="DEBUG" />
</configuration>
Copy the code

The configuration tag

Configuration is a global configuration label. When configuring logback logs, all configuration attributes must be included in this configuration label. The configuration tag has four node attributes

scan

By default, the configuration file will be scanned for changes every minute. If the configuration file changes, it will be reloaded. Default is true.

<configuration scan="true"> 
  <! --do something-->
</configuration>
Copy the code

scanPeriod

Configures the file scanning interval. If the unit is not set, the default value is milliseconds. This parameter can be used with scan. When scan is enabled, you can set this parameter to control the scanning interval of configuration files. For example, configuration files are scanned every 30 seconds.

<configuration scan="true" scanPeriod="30 seconds" > 
  <! --do something-->
</configuration>
Copy the code

###packagingData

Whether to enable packing data in stack traces. Default is false. Print stack data if set to TRUE

<configuration packagingData="true">
  <! --do something-->
</configuration>
Copy the code

Log as follows

[btpool0 14:28:48. 835-7) INFO C.Q.L.D emo. Prime. PrimeAction - 99 is not a valid value. Java lang. Exception: 99 is invalid at ch.qos.logback.demo.prime.PrimeAction.execute(PrimeAction.java:28) [classes/:na] at . Org. Apache. Struts action. RequestProcessor. ProcessActionPerform (RequestProcessor. Java: 431) [struts - 1.2.9. Jar: 1.2.9] the at . Org. Apache. Struts action. RequestProcessor. Process (RequestProcessor. Java: 236) [struts - 1.2.9. Jar: 1.2.9] the at . Org. Apache. Struts action. The ActionServlet. DoPost (432) the ActionServlet. Java: [struts - 1.2.9. Jar: 1.2.9] the at Javax.mail. Servlet. HTTP. HttpServlet. Service (HttpServlet. Java: 820) [the servlet API - 2.5-6.1.12. Jar: 6.1.12] the at . Org. Mortbay. Jetty servlet. ServletHolder. Handle (502) ServletHolder. Java: / jetty - 6.1.12. Jar: 6.1.12 at ch.qos.logback.demo.UserServletFilter.doFilter(UserServletFilter.java:44) [classes/:na] at org.mortbay.jetty.servlet.ServletHandler$CachedChainDoFilter (ServletHandler. Java: 1115) [jetty - 6.1.12. Jar: 6.1.12] the at . Org. Mortbay. Jetty servlet. ServletHandler. Handle (361) ServletHandler. Java: / jetty - 6.1.12. Jar: 6.1.12 at Org. Mortbay. Jetty. Webapp. WebAppContext. Handle (417) WebAppContext. Java: / jetty - 6.1.12. Jar: 6.1.12 at Org. Mortbay. Jetty. Handler. ContextHandlerCollection. Handle (ContextHandlerCollection. Java: 230) [jetty - 6.1.12. Jar: 6.1.12]Copy the code

debug

View the running status of logBack in real time. The default value is false. When the value is set to TRUE, internal logback logs are displayed to view the running status of logback in real time. (Official website description)

<configuration debug="true"> 
	<include resource="org/springframework/boot/logging/logback/base.xml" />
</configuration>
Copy the code

StatusListener label

Child element of statusListener Configuration. Is a status listener that can be registered so that immediate action can be taken in response to status messages, especially those that occur after logBack configuration. Registering a status listener is a convenient way to monitor logBack’s internal state without human intervention.

<configuration>
  <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />  

  <! --do something-->
</configuration>
Copy the code

The logger label

< Logger > child element of configuration. To set logging output for a package or class and specify

, Logger uses only a name, level, and an optional addtivity property.

name

The name attribute is used to specify the package or concrete class for logger constraints.

<! -- Specify package -->
<logger name="com.mingrn.repository"/>
<! -- Specify class -->
<logger name="com.mingrn.repository.UserRepository"/>
Copy the code

level

Level Property Sets the log printing level. TRACE, DEBUG, INFO, WARN, ERROR, ALL, and OFF. INHERITED or NULL is used to enforce the parent level. If this property is not set, the current Logger inherits its parent’s level (root)

<! -- Specify package -->
<logger name="com.mingrn.repository" level="DEBUG"/>
<! -- Specify class -->
<logger name="com.mingrn.repository.UserRepository" level="DEBUG"/>
Copy the code

addtivity

Whether addtivity passes prints to parent Loger, default is true. And if set to true

<logger name="com.mingrn.repository" level="DEBUG" additivity="true"/>
Copy the code

When printing logs, you will notice that the console will print both sides because of this property. So this property is generally set to FALSE when specifying

to specify a package or concrete class.

<logger name="com.mingrn.repository" level="DEBUG" additivity="true"/>
	
<root level="INFO">
    <appender-ref ref="CONSOLE" />
	<appender-ref ref="DEBUG_FILE" />
	<appender-ref ref="INFO_FILE" />
	<appender-ref ref="WARN_FILE" />
	<appender-ref ref="ERROR_FILE" />
	<appender-ref ref="RUN_FILE" />
</root>
Copy the code

The root tag


Child element of configuration. The tag is really

, but it is the root

. The label has only one attribute, level, which is the print log level. If the

or

tag is set to the output level, it inherits that level by default! At the same time, if

is set and additivity is set to true, it will be passed, causing logger to print logs and root to print logs again! (Official website description)





Appender – ref tag


child of root or logger. Tags belong to logger and root internal reference tags. The tag has only one attribute ref that specifies the name value of the

tag! An appender can output logs at the level specified by root and logger.

<root level="INFO">
    <appender-ref ref="CONSOLE" />
	<appender-ref ref="DEBUG_FILE" />
	<appender-ref ref="INFO_FILE" />
	<appender-ref ref="WARN_FILE" />
	<appender-ref ref="ERROR_FILE" />
	<appender-ref ref="RUN_FILE" />
</root>

<logger name="com.uhope.rl.electornic" level="DEBUG">
	<appender-ref ref="DEBUG_FILE"/>
</logger>
Copy the code

ref

Specify the specific appender. The ref value is the name attribute value of

<logger name="com.uhope.rl.electornic" level="DEBUG">
	<appender-ref ref="DEBUG_FILE"/>
</logger>
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
	<! --do something-->
</appender>
Copy the code

ContextName label


: Child of configuration. Defines the context to which looger is associated. The default context name is default. However, this label can be set to a different name, which is used to distinguish the records of different referencing programs. Once set, it cannot be changed.

Website shows

<configuration>
  <contextName>myAppName</contextName>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d %contextName [%t] %level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

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

The property tag

A child element of configuration. It’s an attribute tag.

Website shows

Value is defined

<configuration debug="true">
	<! -- -- -- > path
	<property name="USER_HOME" value="/home/sebastien" />
	<! -- Log output rule -->
	<property name="FILE_LOG_PATTERN" value="% d {MM - dd yyyy - HH: MM: ss. The SSS} ${LOG_LEVEL_PATTERN: - % 5 p} ${PID: -} [t] % % - 40.40 logger {39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}" />

	<appender name="FILE" class="ch.qos.logback.core.FileAppender">
		<file>${USER_HOME}/myApp.log</file>
		<encoder>
			<pattern>%msg%n</pattern>
		</encoder>
	</appender>

	<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<encoder>
			<pattern>${FILE_LOG_PATTERN}</pattern>
		</encoder>
	</appender>
</configuration>
Copy the code

Reference resources

<configuration>

  <property resource="resource.properties" />

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
     <file>${USER_HOME}/myApp.log</file>
     <encoder>
       <pattern>%msg%n</pattern>
     </encoder>
   </appender>

   <root level="debug">
     <appender-ref ref="FILE" />
   </root>
</configuration>
Copy the code

Reference file

Variable. properties is a file

File contents: USER_HOME=/home/sebastien

<configuration>

  <property file="src/main/java/chapters/configuration/variables.properties" />

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
     <file>${USER_HOME}/myApp.log</file>
     <encoder>
       <pattern>%msg%n</pattern>
     </encoder>
   </appender>

   <root level="debug">
     <appender-ref ref="FILE" />
   </root>
</configuration>
Copy the code

Appender label

Children of the appender Configuration. It’s also a logger, but it’s a component that writes logs. This component enforces two property values: name and class.

  • name: The name of the appender, which is mainly used<appender-ref>ref.
  • classAppender: Defines the permission name or component of the appender!

Appender group keys description

An appender tag can refer to components of the package class that can be recorded locally or remotely.

  • Local such as:ConsoleAppender,FileAppender.
  • Remote such as:SocketAppender,SSLSocketAppender

ConsoleAppenderA primary key

ConsoleAppender website notes

ConsoleAppender component package categories: ch. Qos. Logback. Core. ConsoleAppender ConsoleAppender main effect is the log output to the console, apply to the local.

There are the following node properties

The property name type instructions
encoder Encoder coding
target String Out or system. err, default system. out
withJansi boolean The default jANSI property is set to false. Setting Jansi to true activates the Jansi library, which provides support for ANSI color codes on Windows machines.
<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>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
Copy the code

FileAppenderThe set of key

FileAppender (appender

FileAppender package component class ch. Qos. Logback. Core. The FileAppender FileAppender main function is to write a file. The destination file is specified by the file option. If the file already exists, it is either appended or truncated based on the value of the attached attribute, applicable locally.

There are the following node properties

The property name type instructions
file String The file name to be written can be a relative directory or an absolute directory. If the upper-level directory does not exist, the system automatically creates the file. There is no default value.
append boolean If set to true, the log will be added at the end of the file. If false, empty existing files. The default is true
encoder String coding
prudent boolean Writes logs securely and discreetly to the specified file, even if there are other Fileappenders that write logs to this file. Inefficient. The default value of this mode is false. Note: When this value is set to true, append defaults to true

By default, logs are immediately written to the underlying output stream. This default is safe because the name log is not lost if the application exits without shutting down properly. However, the

should be set to false in order to significantly increase log throughput.

<configuration>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>testFile.log</file>
    <append>true</append>
    <! ImmediateFlush should be set to false for higher log throughput -->
    <immediateFlush>true</immediateFlush>
    <! -- encoders are assigned the type -->
    <! -- ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>
        
  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>
Copy the code

RollingFileAppenderThe set of key

RollingFileAppender

RollingFileAppender package component class ch. Qos. Logback. Core. Rolling. The RollingFileAppender RollingFileAppender FileAppender inheritance. When certain conditions are met, it has the feature of scrolling to write files. Say this is the most common write file permission name, applies locally. This component has two very important components: RollingPolicy and TriggeringPolicy

There are the following node properties

The property name type instructions
file String The file name to be written can be a relative directory or an absolute directory. If the upper-level directory does not exist, the system automatically creates the file. There is no default value.
append boolean If set to true, the log will be added at the end of the file. If false, empty existing files. The default is true
encoder String coding
prudent boolean Writes logs securely and discreetly to the specified file, even if there are other Fileappenders that write logs to this file. Inefficient. The default value of this mode is false. Note: When this value is set to true, append defaults to true
rollingPolicy RollingPolicy A RollingFileAppender policy that determines the behavior of a RollingFileAppender when a rollingfile occurs, involving file movement and renaming.See below
triggeringPolicy TriggeringPolicy Tell RollingFileAppender to properly enable scrolling.See below

RollingFileAppenderGroup of keyRollingPolicyFlip strategy

RollingPolicy official website description

RollingPolicy RollingPolicy is responsible for file paths and renaming or naming during the rollover process.

RollingPolicyFlip strategyTimeBasedRollingPolicyFlip strategy

TimeBasedRollingPolicy package class ch. Qos. Logback. Core. Rolling. The TimeBasedRollingPolicy TimeBasedRollingPolicy flip turn strategy is probably the most popular strategy. It defines time-based rollover strategies such as day, month, and so on! TimeBasedRollingPolicy has a mandatory property

and several non-mandatory properties.

There are the following node properties

The property name type instructions
fileNamePattern String Must attribute, its value should include the name of the file, and the appropriately placed %d conversion specifier. The %d conversion specifier can contain a value fromjava.text.SimpleDateFormatSpecifies the date and time mode, such as %d{YYYY-mm}. If date and time modes such as %d are omitted, the default time format is YYYY-MM-DD. The flip period is inferred from the fileNamePattern value.
maxHistory int Maximum log retention time, such as the set time mode (fileNamePattern) to YYYY-mm, and maxHistory to 6. Log files can be saved for a maximum of six months. Note that when the old archive log files are deleted, any folders created for the log file archive will be deleted appropriately.
maxFileSize int Maximum storage size of each file, such as 10M, 100M
totalSizeCap int Controls the total size of log files, for example, 3GB or 100 MB
cleanHistoryOnStart boolean Archive deletion is performed when appender starts by setting the cleanup history to true. The default false

TimeBasedRollingPolicy fileNamePattern Values are listed as follows:

fileNamePattern Rollover schedule file
/wombat/foo.%d Default: YYYY-MM-DD scrolls daily Wombat/foo. 2018-6-1, wombat/foo in 2018-6-2
/wombat/%d{yyyy/MM}/foo.txt Monthly rolling Wombat / 2018/1 / foo. TXT, / wombat / 2018/2 / foo TXT
/wombat/foo.%d{yyyy-ww}.log Weekly rolling
/wombat/foo%d{yyyy-MM-dd_HH}.log All the scroll
/wombat/foo%d{yyyy-MM-dd_HH-mm}.log Every scroll
/wombat/foo.%d.gz Daily scroll, automatically compressed to GZIP format /wombat/foo.2018-6-1.gz

Set the maximum time and capacity for storing logs.

logfile. log
This parameter is optional

<configuration>
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  
    <file>logFile.log</file>
    
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
    
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <! -- daily rollover -->
      <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>

      <! -- keep 30 days' worth of history capped at 3GB total size -->
      <maxHistory>30</maxHistory>
      <totalSizeCap>3GB</totalSizeCap>

    </rollingPolicy>
  </appender> 

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
  
</configuration>
Copy the code

Allows multiple programs to write to the same log file

<configuration>
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <! -- Support multiple-JVM writing to the same log file -->
    <prudent>true</prudent>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
      <maxHistory>30</maxHistory> 
      <totalSizeCap>3GB</totalSizeCap>
    </rollingPolicy>

    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender> 

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>
Copy the code

Set the maximum size for each file

<configuration>
  <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>mylog.txt</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <! -- rollover daily -->
      <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
       <! -- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
       <maxFileSize>100MB</maxFileSize>    
       <maxHistory>60</maxHistory>
       <totalSizeCap>20GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
      <pattern>%msg%n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="ROLLING" />
  </root>

</configuration>
Copy the code
RollingPolicyFlip strategyFixedWindowRollingPolicyFlip strategy

FixedWindowRollingPolicy package class ch. Qos. Logback. Core. Rolling. The FixedWindowRollingPolicy FixedWindowRollingPolicy when rolling, FixedWindowRollingPolicy renames files according to a fixed window algorithm FixedWindowRollingPolicy has a mandatory property

and several non-mandatory properties.

There are the following node properties

The property name type instructions
fileNamePattern String Must attributeThis option indicates that the FixedWindowRollingPolicy mode will be followed when renaming log files. It must contain the string % I, which will indicate where to insert the current window index value. For example, MyLogFile%i.log with minimum index 1 and maximum index 3 will generate files myLogfile1.log, myLogFile2.log and myLogFile3.log
minIndex int The smallest index
maxIndex int The biggest index

TimeBasedRollingPolicy fileNamePattern Specifies the value

Number of rollovers Active output target Archived log files file
0 foo.log If no file is flipped, the log will record the original file
1 foo.log foo1.log On the first flip, the file foo.log will be named foo1.log, and a new file foo.log will be created and become the active output target.
2 foo.log Foo1. Log, foo2. Log On the second flip, the file foo1.log will be named foo2.log, the file foo.log will be named foo1.log, and the new file foo.log will be created and become the active output target.
3 foo.log Foo1. log, foo2.log, foo3.log Same as above
4 foo.log Foo1. log, foo2.log, foo3.log, foo4.log Same as above
<configuration>
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>test.log</file>

    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
      <fileNamePattern>tests.%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>
Copy the code

RollingFileAppenderGroup of keytriggeringPolicyTrigger strategy

triggeringPolicy

The RollingPolicy trigger policy implementation is responsible for instructing when the RollingFileAppender is flipped.

triggeringPolicyTrigger strategySizeBasedTriggeringPolicyTrigger strategy

SizeBasedTriggeringPolicy trigger strategy’s official website

SizeBasedTriggeringPolicy package class ch. Qos. Logback. Core. Rolling. The SizeBasedTriggeringPolicy SizeBasedTriggeringPolicy View the size of the current active file and tell RollingFileAppender to scroll the current active file if it exceeds the specified size. We only accept an attribute maxFileSize SizeBasedTriggeringPolicy trigger strategy, the default value is 10 MB. The maxFileSize option can be specified in bytes, kilobytes, megabytes, or gigabytes by setting values in KB, MB, and GB, respectively. For example, 5000000000, 5000 KB, 5 MB, and 2 GB are valid values, and the first three are equivalent.

<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>
Copy the code

SocketAppender and SSLSocketAppenderThe set of key

SocketAppender and SSLSocketAppender official website

SocketAppender package class ch.qos.logback.classic.net.SocketAppender SSLSocketAppender package classes ch.qos.logback.classic.net.SSLSocketAppender

The translation below is for reference only. Read the official website for details

SocketAppender and SSLSocketAppender permission names are primarily used remotely. The permission naming mentioned above is mainly to log to the local machine of the current server. SocketAppender and SSLSocketAppender permission names work perfectly for writing logs to remote machines.

SocketAppender can write logs to remote machines primarily because SocketAppender is involved in transferring serialized log event bodies (unknown here) over the wire. Log events are sent in Clear when SocketAppender is used on the line. However, when we use SSLSocketAppender, logs will be sent over a secure channel. The serialized entity type is LoggingEventVO, which implements the ILoggingEvent interface.

However, in the case of logging events, logging by remote is intrusive, and the event can be logged at the deserialized receiver as if it were generated locally. Multiple SocketAppender instances running on different machines can direct their log output to a central log server, which has a fixed format. SocketAppender does not have an associated layout because it sends serialized events to the remote server.

SocketAppender runs on top of the Transmission Control Protocol (TCP) layer and provides a reliable, ordered, flow-controlled end-to-end OCTET stream. Therefore, if the remote server is accessible, the logging events will eventually arrive there. Otherwise, log events are simply removed if the remote server is down or inaccessible. If the server is restarted, the event transfer is transparently resumed. This transparent reconnection is performed by a connector thread that periodically attempts to connect to the server.

Log events are automatically buffered by native TCP. This means that if the connection to the server is slow but still faster than the event generation of the client, the client is not affected by a slow network connection. However, if the network connection is slower than the event generation rate, then the client can only make progress on the network rate.

Especially in extreme cases, when the network is connected to the server, the client ends up blocked. Alternatively, if the network connection is rising but the server is down, the client will not be blocked, although the log events will be lost because the server is unavailable. Even if a SocketAppender is no longer connected to any loggers, it is not garbage collected in the presence of the connector thread. The connector thread exists only when the connection to the server is closed.

To avoid this garbage collection problem, the SocketAppender should be explicitly turned off. Long-running applications that create and destroy many SocketAppender instances should be aware of this garbage collection issue. Most other applications can safely ignore it. If the JVM hosting SocketAppender exits before the SocketAppender shuts down, either explicitly or for subsequent garbage collection, then untransferred data may be lost in the pipeline. This is a common problem with Windows-based systems.

To avoid lost data, you can usually explicitly close the socketAppender before exiting the application, or by calling the stop method of the red context.

Remote servers are identified by remoteHost and Port Properties. SocketAppender properties are listed in the table below. SSLSocketAppender supports many additional configuration properties, which are described in more detail later.

There are the following node properties

The property name type instructions
port int Remote server port
remoteHost String Remote server name
ssl SSLConfiguration Only SSLSocketAppender is supported. This property provides the SSL configuration to be used by the appender. See:Official website SSL
includeCallerData boolean If true, the caller’s data will be available to the remote host. By default, no caller data is sent to the server
reconnectionDelay Duration Duration delay string, such as10 secondsRepresents the time to wait between each failed connection attempt to the server. The default value for this option is 30 seconds. Setting this option to 0 turns off the reconnect function. Note that if you successfully connect to the server, the connector thread does not appear.
queueSize int An integer greater than 0Represents the number of logging events to be reserved for remote receivers. When the queue size is 1, event delivery to the remote receiver is synchronous. When the size of the queue is greater than 1, new events are queued if there is free space in the column. Using queue lengths greater than 1 can improve performance by eliminating delays caused by temporary network delays. referenceeventDelayLimitattribute
eventDelayLimit Duration Duration string, for example10 seconds. It represents the time to wait before deleting events, in case the local queue is full, that is, it contains queued events. This can happen if the remote host continues to receive events slowly. The default value for this option is 100 milliseconds.

Log server options

The standard Logback classic release includes two servers that can be used to receive logging events from SocketAppender or SSLSocketAppender

  • ServerSocketReceiver
  • SimpleSocketServer

SocketAppenderComponents of theSimpleSocketServer

SimpleSocketServer official website description

The SimpleSocketServer application takes two command-line arguments: port and configFile, a configuration script in XML format, are the ports to listen on.

<configuration>
          
  <appender name="SOCKET" class="ch.qos.logback.classic.net.SocketAppender">
    <remoteHost>${host}</remoteHost>
    <port>${port}</port>
    <reconnectionDelay>10000</reconnectionDelay>
    <includeCallerData>${includeCallerData}</includeCallerData>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="SOCKET" />
  </root>  

</configuration>
Copy the code

SSLSocketAppenderComponents of theSimpleSSLSocketServer

SimpleSSLSocketServer official website description

SimpleSSLSocketServer Requires that the SimpleSocketServer use the same port as the configFile command line parameter. In addition, you must use the system properties specified on the command line to provide the location and password of the log server’s X.509 certificate.

The server configuration has debug=”true”, specified on the root element, and you can see the SSL configuration to be used in the server startup log. This helps verify that local security policies are being implemented correctly!

<configuration debug="true">
          
  <appender name="SOCKET" class="ch.qos.logback.classic.net.SSLSocketAppender">
    <remoteHost>${host}</remoteHost>
    <port>${port}</port>
    <reconnectionDelay>10000</reconnectionDelay>
    <ssl>
      <trustStore>
        <location>${truststore}</location>
        <password>${password}</password>
      </trustStore>
    </ssl>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="SOCKET" />
  </root>  

</configuration>	
Copy the code

ServerSocketAppender and SSLServerSocketAppendercomponent

ServerSocketAppender and SSLServerSocketAppender official website

ServerSocketAppender package class ch.qos.logback.classic.net.server.ServerSocketAppender SSLServerSocketAppender package classes ch.qos.logback.classic.net.server.SSLServerSocketAppender

SocketAppender and SSLSocketAppender components are designed to allow applications to connect to a remote logging server over a network for the purpose of delivering logging events to the server. In some cases, it may not be convenient or feasible for an application to start a connection to a remote logging server. For these cases, Logback provides a ServerSocketAppender

  • ServerSocketAppender: Passively listens for TCP sockets, waiting for connections from remote clients. Log events are distributed to each connected client. Log events that occur when no client is connected are immediately discarded
  • SSLSocketAppender: Distributes log events to each connected client using a secure, encrypted channel. In addition, the SSL-enabled appender fully supports certificate-based authentication, which can be used to ensure that only authorized clients can connect to the appender to receive logging events.

ServerSocketAppender and SSLServerSocketAppender have the following node properties

The property name type instructions
address String The address of the local network interface that the application will listen to. If this property is not specified, the appender listens on all network interfaces.
port int The port on which the application listens
includeCallerData boolean If true, the caller data is available to the remote host. By default, no caller data is sent to the client
ssl SSLConfiguration Only supportSSLServerSocketAppenderComponent, which provides the SSL configuration to be used by the appender

Example ServerSocketAppender component

<configuration debug="true">
  <appender name="SERVER" class="ch.qos.logback.classic.net.server.ServerSocketAppender">
    <port>${port}</port>
    <includeCallerData>${includeCallerData}</includeCallerData>
  </appender>

  <root level="debug">
    <appender-ref ref="SERVER" />
  </root>  

</configuration>
Copy the code

Note: in the absence of the remoteHost attribute — the appender passively waits for an inbound connection from the remoteHost rather than opening a connection to the remote logging server.

Example SSLServerSocketAppender component

<configuration debug="true">
  <appender name="SERVER" class="ch.qos.logback.classic.net.server.SSLServerSocketAppender">
    <port>${port}</port>
    <includeCallerData>${includeCallerData}</includeCallerData>
    <ssl>
      <keyStore>
        <location>${keystore}</location>
        <password>${password}</password>
      </keyStore>
    </ssl>
  </appender>

  <root level="debug">
    <appender-ref ref="SERVER" />
  </root>  

</configuration>
Copy the code

SMTPAppendercomponent

SMTPAppender official website description