springboot 中 log4j2的使用及配置讲解

从spring boot 1.4之后,就要使用log4j2了。记录一下使用log4j2的过程。本文会从简入繁,一步步揭示各个配置的意思。相信本文是个很好的入门示例。

maven配置

先说怎么配置maven吧。网上很多了:

首先排除spring boot中的logback的依赖包

		<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>

然后添加log4j2的依赖包

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>

示例

下面我们看一个例子:

package com.jzh.autotest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class LogTest {
   private static Logger logger = LoggerFactory.getLogger(LogTest.class);
  
  public static void main(String[] args) throws Exception {
    SpringApplication.run(LogTest.class, args);
    logger.error("log4j2 error!");
  }
}

log4j2.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <!--添加一个控制台追加器-->
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout>
                <pattern>[%-5p] %d %c - %m%n</pattern>
            </PatternLayout>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>

解释一下上面配置可能会有的疑问

Configuration上有个INFO,Root下有个debug,啥意思?怎么又是INFO,又是debug的。

这里要明确的一点,Configuration的status是log4j2本身的日志打印级别,并是不全局日志级别。而Root下的leve,则恰恰是全局日志级别。

Appenders下面定义日志输出的地方。从上面配置看,是输出到了控制台。

Loggers下面可以配置Root和Logger子节点。Root定义了项目的根日志。如果没有配置Logger,例如上例,则按照Root的定义。AppenderRef定义了日志输出到哪里。上例,就是输出到控制台。

我们看项目的日志:

[DEBUG] 2018-03-01 20:56:04,177 org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter'
[DEBUG] 2018-03-01 20:56:04,177 org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'defaultViewResolver'
[DEBUG] 2018-03-01 20:56:04,177 org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'defaultViewResolver'
[INFO ] 2018-03-01 20:56:04,662 com.jzh.autotest.LogTest - Started LogTest in 4.823 seconds (JVM running for 6.19)
[ERROR] 2018-03-01 20:56:04,662 com.jzh.autotest.LogTest - log4j2 error!

中间还有很多日志,被我截取了。可以看到,项目DEBUG级别以上的日志,都打印出来了。

Root level作用域

那我们将Root的level改为info试试。奇怪的问题出现了,竟然输出和上面一样。难道说这个Root只能控制我们自己写的代码日志级别,而spring boot加载的我们无法控制吗?

带着这个疑问,我们将代码改为

logger.debug("log4j2 debug!");

输出如下:

[INFO ] 2018-03-01 21:01:43,710 org.apache.tomcat.util.net.NioSelectorPool - Using a shared selector for servlet write/read
[INFO ] 2018-03-01 21:01:43,727 org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8080 (http)
[INFO ] 2018-03-01 21:01:43,731 com.jzh.autotest.LogTest - Started LogTest in 2.992 seconds (JVM running for 3.822)

果然没有输出我们自己打印的debug级别日志。

那么如果我不想要打印springframework这些日志呢?可以通过在Loggers中添加Logger来实现。log4j2.xml改成如下这样:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <!--添加一个控制台追加器-->
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout>
                <pattern>[%-5p] %d %c - %m%n</pattern>
            </PatternLayout>
        </Console>
        <!--添加一个文本追加器,文件位于根目录下,名为log.log-->
        <File name="File" fileName="jzh.log">
            <PatternLayout>
                <pattern>[%-5p] %d %c - %m%n</pattern>
            </PatternLayout>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console" />
        </Root>
      	<Logger name="org.springframework" level="info" additivity="false">  
            <AppenderRef ref="File" />
        </Logger>  
    </Loggers>
</Configuration>

Logger 匹配org.springframework包下的所有日志,输出级别为info。我们在Appenders中添加了一个File,将org.springframework的日志打印到该文件。默认,Logger的配置,会追加到Console。如果不想这样,则增加additivity=“false”。

控制台输入如下:

2018-03-01 22:17:15,670 main INFO Log4j appears to be running in a Servlet environment, but there's no log4j-web module available. If you want better web container support, please add the log4j-web JAR to your web archive or server lib directory.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.0.RELEASE)

[INFO ] 2018-03-01 22:17:15,795 com.jzh.autotest.LogTest - Starting LogTest on HIH-D-13206 with PID 2548 (D:\Code\Own\AotuTest\target\classes started by jiangzhaohai in D:\Code\Own\AotuTest)
[INFO ] 2018-03-01 22:17:15,795 com.jzh.autotest.LogTest - The following profiles are active: ap
[INFO ] 2018-03-01 22:17:16,244 org.hibernate.validator.internal.util.Version - HV000001: Hibernate Validator 5.3.4.Final
[INFO ] 2018-03-01 22:17:17,759 org.apache.catalina.core.StandardService - Starting service Tomcat
[INFO ] 2018-03-01 22:17:17,760 org.apache.catalina.core.StandardEngine - Starting Servlet Engine: Apache Tomcat/8.5.11
[INFO ] 2018-03-01 22:17:17,938 org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
[INFO ] 2018-03-01 22:17:19,002 org.apache.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8080"]
[INFO ] 2018-03-01 22:17:19,021 org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler [http-nio-8080]
[INFO ] 2018-03-01 22:17:19,036 org.apache.tomcat.util.net.NioSelectorPool - Using a shared selector for servlet write/read
[INFO ] 2018-03-01 22:17:19,057 com.jzh.autotest.LogTest - Started LogTest in 3.567 seconds (JVM running for 4.407)

果然没有了org.springfreamwork的日志,再看jzh.log

[INFO ] 2018-03-01 22:25:49,883 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@36b4fe2a: startup date [Thu Mar 01 22:25:49 CST 2018]; root of context hierarchy
[DEBUG] 2018-03-01 22:25:49,885 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Bean factory for org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@36b4fe2a: org.springframework.beans.factory.support.DefaultListableBeanFactory@2a265ea9: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,logTest]; root of factory hierarchy
[INFO ] 2018-03-01 22:25:50,786 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration' of type [class org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[INFO ] 2018-03-01 22:25:50,856 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'validator' of type [class org.springframework.validation.beanvalidation.LocalValidatorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[DEBUG] 2018-03-01 22:25:50,902 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@74bdc168]
[DEBUG] 2018-03-01 22:25:50,902 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@644c78d4]
[DEBUG] 2018-03-01 22:25:51,207 org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory - Code archive: E:\.m2\repository\org\springframework\boot\spring-boot\1.5.0.RELEASE\spring-boot-1.5.0.RELEASE.jar
[DEBUG] 2018-03-01 22:25:51,207 org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory - Code archive: E:\.m2\repository\org\springframework\boot\spring-boot\1.5.0.RELEASE\spring-boot-1.5.0.RELEASE.jar
[DEBUG] 2018-03-01 22:25:51,207 org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory - None of the document roots [src/main/webapp, public, static] point to a directory and will be ignored.
[INFO ] 2018-03-01 22:25:51,249 org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat initialized with port(s): 8080 (http)
[INFO ] 2018-03-01 22:25:51,400 org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1519 ms
[DEBUG] 2018-03-01 22:25:52,253 org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer - 
[INFO ] 2018-03-01 22:25:52,311 org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8080 (http)

Logger level作用域

怎么会有DEBUG级别的日志呢?level的作用是什么? 感觉没用的。。。

好在我们还可以在File中添加

<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>

定义级别为info。onMatch=“ACCEPT”表示,在info级别及以上的日志,会接受,onMistch=“DENY”,表示不匹配的会拒绝。

看输出:

[INFO ] 2018-03-01 22:37:07,002 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@36b4fe2a: startup date [Thu Mar 01 22:37:07 CST 2018]; root of context hierarchy
[INFO ] 2018-03-01 22:37:07,852 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration' of type [class org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[INFO ] 2018-03-01 22:37:07,928 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'validator' of type [class org.springframework.validation.beanvalidation.LocalValidatorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[INFO ] 2018-03-01 22:37:08,347 org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat initialized with port(s): 8080 (http)
[INFO ] 2018-03-01 22:37:08,507 org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1506 ms
[INFO ] 2018-03-01 22:37:08,712 org.springframework.boot.web.servlet.ServletRegistrationBean - Mapping servlet: 'dispatcherServlet' to [/]
[INFO ] 2018-03-01 22:37:08,716 org.springframework.boot.web.servlet.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
[INFO ] 2018-03-01 22:37:08,716 org.springframework.boot.web.servlet.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
[INFO ] 2018-03-01 22:37:08,717 org.springframework.boot.web.servlet.FilterRegistrationBean - Mapping filter: 'httpPutFormContentFilter' to: [/*]
[INFO ] 2018-03-01 22:37:08,717 org.springframework.boot.web.servlet.FilterRegistrationBean - Mapping filter: 'requestContextFilter' to: [/*]
[INFO ] 2018-03-01 22:37:09,002 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@36b4fe2a: startup date [Thu Mar 01 22:37:07 CST 2018]; root of context hierarchy
[INFO ] 2018-03-01 22:37:09,072 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
[INFO ] 2018-03-01 22:37:09,073 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
[INFO ] 2018-03-01 22:37:09,098 org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[INFO ] 2018-03-01 22:37:09,098 org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[INFO ] 2018-03-01 22:37:09,138 org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[WARN ] 2018-03-01 22:37:09,246 org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor - The @ConfigurationProperties bean class envutils.EnvUtils contains validation constraints but had not been annotated with @Validated.
[WARN ] 2018-03-01 22:37:09,247 org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor - The @ConfigurationProperties bean class envutils.EnvUtils contains validation constraints but had not been annotated with @Validated.
[INFO ] 2018-03-01 22:37:09,555 org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
[INFO ] 2018-03-01 22:37:09,628 org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8080 (http)

此外可以通过onMatch="DENY" onDismatch="NEUTRAL"实现输出比匹配日志级别低的信息

简单示例到此为止。有个疑问,logger中的level到底有什么作用?

后面我们会示范一些高端用法。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是配置log4j2的步骤: 1. 在pom.xml文件添加log4j2的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> ``` 2. 在application.properties文件添加log4j2配置文件路径: ```properties logging.config=classpath:log4j2.xml ``` 其log4j2.xml是你自定义的log4j2配置文件。 3. 创建log4j2.xml文件并配置日志输出格式、日志级别等信息。以下是一个简单的log4j2.xml配置示例: ```xml <?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="Console"/> </Root> </Loggers> </Configuration> ``` 在这个示例,日志会输出到控制台,并且包含时间戳、线程信息、日志级别、类名和日志消息。 4. 在你的代码使用log4j2进行日志记录。例如,在Spring Boot的应用程序,你可以使用`org.slf4j.Logger`接口进行日志记录。以下是一个示例: ```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RestController public class MyController { private static final Logger logger = LoggerFactory.getLogger(MyController.class); @GetMapping("/hello") public String hello() { logger.info("Hello, world!"); return "Hello, world!"; } } ``` 在这个示例,我们使用`logger.info()`方法记录了一条日志。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值