- commons-logging和slf4j是java中的日志門面,即它們提供了一套通用的接口,具體的實現可以由開發者自由選擇。log4j和logback則是具體的日志實現方案。
- 比較常用的搭配是commons-logging+log4j,slf4j+logback
-
為什么要用SLF4J+Logback 替換commons-logging+log4j?
- SLF4J是編譯時綁定到具體的日志框架,性能優於采用運行時搜尋的方式的commons-logging
- 不需要使用logger.isDebugEnabled()來解決日志因為字符拼接產生的性能問題
-
logger.info("my name is {}", "medusar"); logger.info("my name is " + "medusar"); - 在效率上,第一行比第二行更高,因為如果當前日志級別是ERROR,第一行不會進行字符串拼接,而第二行,無論日志級別是什么,都會先進行字符串拼接。
- 所以為了解決這個問題,commons-logging等框架提供了下面的方式:
if (log.isDebugEnabled()){ log.debug("dddd"+"eee"); }
-
- 基於commons-logging的日志使用
-
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class XXXService { private static final Log log = LogFactory.getLog(XXXService.class); public void doSomething(){ log.info("begin dosomething...."); } }
-
-
基於slf4j的日志使用
-
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class XXXService { private static final Logger logger = LoggerFactory.getLogger(XXXService.class); public void doSomething() { logger.info("begin dosomething..."); } }
-
- SpringBoot底層也是使用slf4j+logback的方式進行日志記錄;
- SpringBoot也把其他的日志都替換成了slf4j;
- Spring Boot能自動適配所有的日志,而且底層使用slf4j+logback的方式記錄日志,引入其他框架的時候,只需要把這個框架依賴的日志框架排除掉。
-
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <exclusions> <exclusion> <groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> - 以后開發的時候,日志記錄方法的調用,不應該直接調用日志的實現類,而是調用日志抽象層里面的方法;給系統里面導入slf4j的jar和logback的實現jar
-
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloWorld { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(HelloWorld.class); logger.info("Hello World"); } }
-
-
指定文件中日志輸出的格式-
# 在控制台輸出的日志格式 logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n # 指定文件中日志輸出的格式 logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} === - %msg%n - <!-- 日志輸出格式:
- %d表示日期時間,
- %thread表示線程名,
- %-5level:級別從左顯示5個字符寬度
- %logger{50} 表示logger名字最長50個字符,否則按照句點分割。
- %msg:日志消息,
- %n是換行符-->
-
-
切換日志框架(無意義,slf4j+logback已經是最佳實現)
-
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!--排除轉換包--> <exclusions> <exclusion> <artifactId>logback-classic</artifactId> <groupId>ch.qos.logback</groupId> </exclusion> <exclusion> <artifactId>log4j-over-slf4j</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <!--添加slf4j依賴--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
-
- 調整日志級別
- Log Level:
ERROR,WARN,INFO,DEBUG, orTRACE. - Logback does not have a
FATALlevel. It is mapped toERROR. - The default log configuration echoes messages to the console as they are written. By default,
ERROR-level,WARN-level, andINFO-level messages are logged. You can also enable a “debug” mode by starting your application with a--debugflag. -
$ java -jar myapp.jar --debug
- Alternatively, you can enable a “trace” mode by starting your application with a
--traceflag (ortrace=truein yourapplication.properties). -
All the supported logging systems can have the logger levels set in the Spring
Environment(for example, inapplication.properties) by usinglogging.level.<logger-name>=<level>wherelevelis one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF. Therootlogger can be configured by usinglogging.level.root.The following example shows potential logging settings in
application.properties: -
logging.level.root=WARN logging.level.org.springframework.web=DEBUG logging.level.org.hibernate=ERROR
- Log Level:
- 日志文件
- By default, Spring Boot logs only to the console and does not write log files. If you want to write log files in addition to the console output, you need to set a
logging.fileorlogging.pathproperty (for example, in yourapplication.properties). - Log files rotate when they reach 10 MB and, as with console output,
ERROR-level,WARN-level, andINFO-level messages are logged by default. Size limits can be changed using thelogging.file.max-sizeproperty. Previously rotated files are archived indefinitely unless thelogging.file.max-historyproperty has been set. - Logging properties are independent of the actual logging infrastructure. As a result, specific configuration keys (such as
logback.configurationFilefor Logback) are not managed by spring Boot. 
- By default, Spring Boot logs only to the console and does not write log files. If you want to write log files in addition to the console output, you need to set a
-
Log Groups
-
It’s often useful to be able to group related loggers together so that they can all be configured at the same time. For example, you might commonly change the logging levels for all Tomcat related loggers, but you can’t easily remember top level packages.
To help with this, Spring Boot allows you to define logging groups in your Spring
Environment. For example, here’s how you could define a “tomcat” group by adding it to yourapplication.properties:logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.tomcatOnce defined, you can change the level for all the loggers in the group with a single line:
logging.level.tomcat=TRACESpring Boot includes the following pre-defined logging groups that can be used out-of-the-box:
Name Loggers web
org.springframework.core.codec,org.springframework.http,org.springframework.websql
org.springframework.jdbc.core,org.hibernate.SQL
-
-
Custom Log Configuration
- The various logging systems can be activated by including the appropriate libraries on the classpath and can be further customized by providing a suitable configuration file in the root of the classpath or in a location specified by the following Spring
Environmentproperty:logging.config. - Since logging is initialized before the
ApplicationContextis created, it is not possible to control logging from@PropertySourcesin Spring@Configurationfiles. The only way to change the logging system or disable it entirely is via System properties. - Depending on your logging system, the following files are loaded:
-
Logging System Customization Logback
logback-spring.xml,logback-spring.groovy,logback.xml, orlogback.groovyLog4j2
log4j2-spring.xmlorlog4j2.xmlJDK (Java Util Logging)
logging.properties - When possible, we recommend that you use the
-springvariants for your logging configuration (for example,logback-spring.xmlrather thanlogback.xml). If you use standard configuration locations, Spring cannot completely control log initialization. -
To help with the customization, some other properties are transferred from the Spring
Environmentto System properties, as described in the following table:-
Spring Environment System Property Comments logging.exception-conversion-wordLOG_EXCEPTION_CONVERSION_WORDThe conversion word used when logging exceptions.
logging.fileLOG_FILEIf defined, it is used in the default log configuration.
logging.file.max-sizeLOG_FILE_MAX_SIZEMaximum log file size (if LOG_FILE enabled). (Only supported with the default Logback setup.)
logging.file.max-historyLOG_FILE_MAX_HISTORYMaximum number of archive log files to keep (if LOG_FILE enabled). (Only supported with the default Logback setup.)
logging.pathLOG_PATHIf defined, it is used in the default log configuration.
logging.pattern.consoleCONSOLE_LOG_PATTERNThe log pattern to use on the console (stdout). (Only supported with the default Logback setup.)
logging.pattern.dateformatLOG_DATEFORMAT_PATTERNAppender pattern for log date format. (Only supported with the default Logback setup.)
logging.pattern.fileFILE_LOG_PATTERNThe log pattern to use in a file (if
LOG_FILEis enabled). (Only supported with the default Logback setup.)logging.pattern.levelLOG_LEVEL_PATTERNThe format to use when rendering the log level (default
%5p). (Only supported with the default Logback setup.)PIDPIDThe current process ID (discovered if possible and when not already defined as an OS environment variable).
-
- The various logging systems can be activated by including the appropriate libraries on the classpath and can be further customized by providing a suitable configuration file in the root of the classpath or in a location specified by the following Spring
- xx
