Spring Boot Series--log configuration

Source: Internet
Author: User

Logs, usually not presented separately as a function in the requirements phase, or in the details of the product scenario. However, this does not affect its important position in any system at all.

In order to ensure that the service is highly available, the problem must be solved even, the problem must be rapid, so the production environment once the problem, the early warning system through the mail, text messages and even the way the phone to implement multidimensional bombing mode, to ensure that the relevant person responsible for every possible bug.

Early warning systems determine that most suspected bugs originate in the logs. For example, a microservices interface causes frequent call errors for various reasons, at which point the caller catches such an exception and prints the error level log, triggering an alarm when the error log reaches a certain number of occurrences.

try {    调用某服务} catch(Exception e) {    LOG.error("错误信息", e);}

So the log is important, and this article describes how to configure the log in spring boot.

Spring Boot Default Log system

Spring boot uses the Logback log system by default, and if you do not need to change to another log system such as LOG4J2, there is no need for unnecessary configuration, logback print the logs to the console by default.

If you want to use Logback, in principle you need to add dependency-dependent

<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></pre>

However, because the new spring boot project is generally referenced spring-boot-starter or spring-boot-starter-web , both of these start-up dependencies already contain dependency dependencies, so there is spring-boot-starter-logging no need to add additional dependencies.

We started the Springboot-demo project based on the project created in the "No big project, but I will build the big project", and you can see the following print log information.

Above to the default configuration under the start of the log display situation, if you need to do some custom log configuration such as storing the log to a file, etc. should be how to configure, following a few small issues to see how spring boot is how to solve these problems.

How to print a log in a project

Create a new configuration class LogConfig, inject a bean, and print the log in the method

package com.jackie.springbootdemo.config;import com.jackie.springbootdemo.model.Person;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration public class LogConfig {    private static final Logger LOG = LoggerFactory.getLogger(LogConfig.class);    @Bean public Person logMethod() {        LOG.info("==========print log==========");        return new Person();    }}

Run Springbootdemoapplication, you can see the log of the console

The default log level for Spring boot is info, which is printed in the info-level log so it can be displayed.

Many developers in the daily write private static final Logger LOG = LoggerFactory.getLogger(LogConfig.class); always feel that the back of the Logconfig.class dispensable, because write any other class will not error, but the accurate writing class information can provide the efficiency of fast location log.

We see the printed log content to the left of the corresponding class name, this is private static final Logger LOG = LoggerFactory.getLogger(LogConfig.class); achieved by.

If Logconfig.class is replaced with Xxx.class, the output log will display the corresponding XXX class name. The advantage of this declaration is that it is convenient to locate logs.

How to store log information to a file

In the native environment, we are accustomed to look at the log in the console, but on the line we still want to log information by saving to log file, query log file.

So how do you configure the log information to be saved to a file?

In the Springboot-demo project we created, there is a application.properties file under the Resources directory (the same is true for application.yml files, just the different writing styles used). Add the following configuration

logging.path=/Users/jackie/workspace/rome/ logging.file=springbootdemo.log

Logging.path

This property is used to configure the path of the log file

Logging.file

This property is used to configure the log file name, and if the property is not configured, the default file name is Spring.log

Run Springbootdemoapplication

You can see that the Springbootdemo.log file was generated under the specified path, and the contents of the file are consistent with the console print.

If logging.file=springbootdemo.log the comment generates a default file name Spring.log

How to set the log level

There is a total of Tarce < Debug < INFO < WARN < ERROR < FATAL in the log level, and the level is gradually provided, and if the log level is set to INFO, it means that both trace and DEBUG level logs are not visible.

In the example above we have printed an info-level log because the spring boot default level is info, and if we change to warn, we can see this line of log information.

Logging.level

This property is used to configure the logging level.

Add in Applicaition.properties

logging.level.root=warn

Here is the root level, that is, all the logs of the project, we can also use the package level, that is, under the specified packet using the appropriate log level, see below.

Start Springbootdemoapplication

You're right, this project was launched successfully, but there is little content, because the log levels that were previously printed are info, which is set to warn, so the info-level logs are not displayed.

Here we can change the root or the info level to set the log level under the specified package to warn

logging.level.root=INFOlogging.level.com.jackie.springbootdemo.config=WARN

Start Springbootdemoapplication

You can see that the logs in addition to the info level in the LogConfig class are not printed, and the other info-level logs are output normally.

How to customize your own log format

Add in Application.properties

logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n

Logging.pattern.console

This property is used to customize the log output format.

The meaning of the corresponding symbol is as follows in the encoding of the above configuration

%d{HH:mm:ss.SSS}——日志输出时间%thread——输出日志的进程名字,这在Web应用以及异步任务处理中很有用%-5level——日志级别,并且使用5个字符靠左对齐%logger- ——日志输出者的名字%msg——日志消息%n——平台的换行符

Start Springbootdemoapplication

Confined to space, there are related features, which are not stated here.

If you feel that reading this article is helpful to you, please click " recommend " button, your " recommendation " will be my biggest writing motivation! If you want to keep an eye on my article, please scan the QR code, follow Jackiezheng's public number, I will push my article to you and share with you the high-quality articles I have read every day.

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.