Spring Boot + log4j2 Log Framework configuration (Maven)

Source: Internet
Author: User
Tags java util log4j

Refer to the Spring Boot Official document log section

Spring boot by default when using "starters" to output logs using Logback
, including appropriate Logback routing, to ensure that other log frameworks (Java Util Logging, Commons Logging, log4j, slf4j) are working properly



The 26.5 custom log configuration section of the Sping boot document explains the method for customizing the logs

A variety of log systems can be

    1. Add the appropriate Log framework library to Classpath
    2. The appropriate configuration profile is added to the root directory of the classpath or other local directory, using the spring configuration loggin.config configuration to specify the configuration file

Relies on the log framework chosen by the developer. These corresponding configuration files will be loaded

Log Frame configuration file
Logback logback-spring.xml, logback-spring.groovy, logback.xml,logback.groovy
Log4j2 log4j2-spring.xml,log4j2.xml
JDK (JAVA Util Logging) logging.properties

Introducing the LOG4J2 Log framework

The log4j2 is not introduced. LOG4J2 official website

Configuration of the scheme in Official document 77.2 Configure log4j for Logging

1. Maven Dependency Configuration

pom.xmlRemove Logback and introduce log4j2

<!-- 节选 --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId>    <exclusions>        <exclusion>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-logging</artifactId>        </exclusion>    </exclusions></dependency><!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j2 --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-log4j2</artifactId></dependency>

2. Configuration files

2.1 Log4j2.xml

Using an XML format configuration file eliminates the need to add additional dependent libraries.

2.2 Log4j2.yaml/log4j2.yml

Use the YAML/YML format configuration file. Need to introduce additional dependent libraries

<!-- 解析yml配置 --><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId></dependency><dependency>    <groupId>com.fasterxml.jackson.dataformat</groupId>    <artifactId>jackson-dataformat-yaml</artifactId></dependency>

2.3 Log4j2.json

Using a JSON-formatted configuration file requires additional dependency libraries to be introduced

<dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId></dependency>

3. Modify the Spring boot configuration

Specifying the spring boot configuration file

application.yamlThe file is configured as follows

logging:  config: classpath:log4j2.xml


LOG4J2 Log Configuration

For detailed configuration of LOG4J2, access to official documentation

Overview

About the basic information about LOG4J2.

The level of the log is divided into:

    1. Trace (Trace)
    2. Debug (Debug)
    3. Info (info)
    4. Warn (warning)
    5. Error (Errors)
    6. Fatal (Critical error)




Here is a log method that bloggers often useRollingFileAppender

Take a specific configuration as an example

<?xml version= "1.0" encoding= "UTF-8"? ><configuration status= "Trace" strict= "true" Name= "LogConfig" > < properties> <property name= "filepath" >/tmp/log4j2</Property> </Properties> <appenders > <console name= "STDOUT" target= "System_out" > <PatternLayout> <pattern& Gt [%d]-[%c]-[%highlight{%level}]-[%method]-[%t]-%msg%n</pattern> </PatternLayout> &L                     t;/console> <rollingfile name= "Logservice" filename= "${filepath}/logservice.log"                filepattern= "${filepath}/bak/logservice-%d{yy-mm-dd hh:mm:ss}.log.gz" > <PatternLayout> &LT;PATTERN&GT;[%D]-[%c]-[%highlight{%level}]-[%method]-[%t]-%msg%n</pattern> </ patternlayout> <Policies> <crontriggeringpolicy schedule= "1 * * * * *?" Evaluateonsta       Rtup= "true"/>     </Policies> </RollingFile> </Appenders> <Loggers> <logger name= "Filelo Gger "level=" Debug "additivity=" false "> <appenderref ref=" logservice "/> <appenderref ref        = "STDOUT"/> </Logger> <root level= "Trace" > <appenderref ref= "STDOUT"/> </Root> </Loggers></Configuration>

1. Configuration Parameters

    1. status: Level enumeration type, control output log4j event information, default error
    2. name: Configuration Name
    3. strict: Whether to use strict XML format. Recommended use, Specification developer configuration, not support JSONP configuration
    4. ... Several other configurations can refer to the official documentation

2. Properties

Sets the parameter variables for the global configuration file. Used to reduce the number of duplicate encodings for custom configuration information.

<Properties>    <Property name="filepath">/tmp/log4j2</Property></Properties>

Configuration context, you can use ${filepath} to replace the/tmp/log4j2

3. Appenders

LOG4J2 offers a wealth of appender

    1. Asyncappender setting appender Asynchronous output log
    2. Cassandraappender output to Cassandra Storage
    3. Consoleappender Output Control Console
    4. Failoverappender Setting Appender Error retry
    5. Fileappender Output to File
    6. Flumeappender output to Flume
    7. Jdbcappender relational database tables for output to JDBC connections
    8. JMS Appender output to message service
    9. Jpaappender output to a relational row database using JPA connections
    10. Httpappender output to HTTP Service
    11. Kafkaappender output to Kafka
    12. Memorymappedfileappender Output to Memory
    13. Nosqlappender Output to NoSQL database
    14. Outputstreamappender file/socket Types of Appender
    15. Randomaccessfileappender performance is 0.2-twice times of Fileappder
    16. Rollingfileappender output to a file, files can be packaged according to the rules
    17. Rollingrandomaccessfileappender Ibid.
    18. Smtpappender Message form Output
    19. Socketappender Socket Mode Send log

The more commonly used in the project is the ConsoleAppender and RollingFileAppender .

The following is a description of the Appender configuration parameters described above

<Appenders> <!--consoleappender <!--name Appender--<!--target enum (system_out, SY Stem_err). Default System_out---<console name= "STDOUT" target= "System_out" > <!--output format detailed configuration see below--&LT;PA        Tternlayout> <pattern>[%d]-[%c]-[%highlight{%level}]-[%method]-[%t]-%msg%n</pattern> </PatternLayout> </Console> <!--Rollingfileappender-<!--fileName output problem name, using absolute path                 Ensure that the log location is correct, and that the directory has process user writable permissions-<!--filepattern log rollback file naming rules--<rollingfile name= "Logservice" Filename= "${filepath}/logservice.log" filepattern= "${filepath}/bak/logservice-%d{yy-mm-dd HH:mm: Ss}.log.gz "> <PatternLayout> <pattern>[%d]-[%c]-[%highlight{%level}]-[%method]-[%            T]-%msg%n</pattern> </PatternLayout> <Policies> <!--rollback files by cron timed tasks-- <! ---Schedule cron expression--<!--evaluateonstartup (rule: When starting, check to determine the last modification time of the target file, if the cron rule determines that the file needs to be rolled back, roll back the file directly.) Start the rule action-<crontriggeringpolicy schedule= "1 * * * *?" evaluateonstartup= "true"/> </policie S> </RollingFile></Appenders>

3.2 Log Output Rule Layouts

Layout has multiple format outputs

    1. Csv
    2. Gelf
    3. Html
    4. Json
    5. Pattern
    6. ....

The project typically uses pattern-by-line output-by-item information, configured as follows:

<!-- 节选配置 --><PatternLayout>    <Pattern>[%d] - [%c] - [%highlight{%level}] - [%method] - [%t] - %msg%n</Pattern></PatternLayout>

%+ char/word represents an output of information or format

Time%d/%date
format Output
%d,%d{default} 2012-11-02 14:34:02,781
%d{unix} 1351866842
%d{unix_millis} 1351866842781
%d{yyyy-mm-dd Hh:mm:ss,sss} 2012-11-02 14:34:02,781

Class%c/%logger

The class name of the output call

%c{number}, the length of the control type

Level%level

Output level TRACE, DEBUG, INFO, WARN, ERROR, FATAL

Color Format%highlight

%HEIGHLIGHT{XXX}

XXX will be color-style, and level-related, generally used for debug debugging information

Log content%m/%msg/%message

To add text styles

Line break%n

The user journal wraps according to the output of the operating system with a different newline identifier, so it's best not \n to use, \r\n such as line break symbols

There are many other symbols, refer to official documents



4. Loggers

    1. Must contain an Root element, without setting the Root element, will default to a configuration similar to the following

<Root level="error">    <AppenderRef ref="Console" /></Root>

    1. Configure other developers to customize theLogger

<Loggers>    <!-- name 必填且唯一 -->    <!-- level 设置输出最低级别 默认error -->    <!-- additivity 是否在父Logger输出, 默认 true -->    <Logger name="fileLogger" level="debug" additivity="false">        <!-- 上文中定义的Appender name -->        <AppenderRef ref="logService"/>        <AppenderRef ref="STDOUT"/>    </Logger>    <Root level="ERROR">        <AppenderRef ref="STDOUT"/>    </Root></Loggers>


Using logger

Take demo as an example

package info.chiwm.log4j2.service;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.stereotype.Service;/** * @author [email protected] * @ClassName: Log4j2ServiceImpl * @Description: * @date 2018/1/4 上午11:10 */@Servicepublic class Log4j2ServiceImpl implements Log4j2Service {    // 使用LogManager获取配置Logger    private static Logger logger = LogManager.getLogger("fileLogger");    @Override    public void info(String msg) {        // 输出日志        // 特别注意 不要使用 `+` 去拼接信息, 这样在控制输出级别之后, 有些日志操作不会打印, 但是它去操作了新字符串创建, 使用 `{}` 去代替 `+`        logger.info("info {}", msg);    }    @Override    public void error() {        logger.error("error");    }    @Override    public void warn() {        logger.warn("warn");    }    @Override    public void debug() {        logger.debug("debug");    }    @Override    public void trace() {        logger.trace("trace");    }}

Summarize

The previous configuration steps, configuration, and use steps, presumably describe the use of log4j2.

Comment Areas are welcome to indicate errors or to discuss related issues

Spring Boot + log4j2 Log Framework configuration (Maven)

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.