Spring MVC 在SpringMVC中启用日志记录,而不使用Spring-boot

tzxcd3kk  于 2022-11-15  发布在  Spring
关注(0)|答案(3)|浏览(188)

我正在创建一个简单的SpringMVC项目,并希望记录所有传入的请求,包括uri/query/payload/clientIp...,所有信息。
我能找到的所有资源都是关于Spring Boot的,例如:https://www.javadevjournal.com/spring/log-incoming-requests-spring/
我也阅读了官方文档,发现enableLoggingRequestDetails选项,但没有关于它的细节,我尝试了,但没有工作. https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-logging
那么,如何在纯SpringMVC框架(没有Sping Boot )中实现这个呢?
有没有一个SpringMVC内置的方法来做这件事?

hwamh0ep

hwamh0ep1#

1.您可以实现一个从OncePerRequestFilter扩展的Filter类,然后每个请求都将通过您的过滤器。然后您可以在该类中记录您想要的内容。

@Slf4j
    @Component
    public class RequestLoggingFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            log.debug(
                    String.format("FILTERED URL: %s", request.getRequestURI())
            );

            //continue filtering
            filterChain.doFilter(request, response);
        }
    }

2.另一种方法是实现从HandlerInterceptorAdapter扩展的拦截器类。

@Slf4j
    @Component
    public class RequestLoggingHandler extends HandlerInterceptorAdapter {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            log.debug(
                    String.format("HANDLER(pre) URL: %s", request.getRequestURI())
            );

            return super.preHandle(request, response, handler);
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            log.debug(
                    String.format("HANDLER(post) URL: %s", request.getRequestURI())
            );

            super.postHandle(request, response, handler, modelAndView);
        }
    }

但是您必须通过配置显式地添加这个拦截器来启用它。

@Configuration
    public class WebApplicationConfiguration implements WebMvcConfigurer {

        @Setter(onMethod_ = @Autowired)
        private RequestLoggingHandler requestLogger;

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(requestLogger);
        }
    }

3.还有一种方法是使用标准CommonsRequestLoggingFilter

这样,您应该使用如下配置来配置它:

@Configuration
public class RequestLoggingFilterConfig {

    @Bean
    public CommonsRequestLoggingFilter logFilter() {
        CommonsRequestLoggingFilter filter
          = new CommonsRequestLoggingFilter();
        filter.setIncludeQueryString(true);
        filter.setIncludePayload(true);
        filter.setMaxPayloadLength(10000);
        filter.setIncludeHeaders(false);
        filter.setAfterMessagePrefix("REQUEST DATA : ");
        return filter;
    }
}

然后在logback.xml中启用它:

<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter">
    <level value="DEBUG" />
</logger>
643ylb08

643ylb082#

为了在Spring应用程序中启用日志记录,您需要做的是
日志库及其属性文件
要使Log4j使用默认的JCL依赖项(commons-logging),您需要做的就是将Log4j放在类路径上,并为其提供一个配置文件(类路径根目录中的log4j.properties或log4j.xml)。

<dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
      <scope>runtime</scope>
   </dependency>

log4j.properties

log4j.rootCategory=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n

log4j.category.org.springframework.beans.factory=DEBUG

参考Spring文件和样品project

l7wslrjt

l7wslrjt3#

使用拦截器你可以实现这个。检查下面的链接,你会得到一个想法
enter link description here
spring-mvc-handlerinterceptor
spring-mvc-4-how-to-intercept-request-with-a-handlerinterceptor

编辑:

使用公用请求日志记录过滤器
Spring MVC提供了CommonsRequestLoggingFilter,它可以记录请求URL、主体和其他相关信息。
CommonsRequestLoggingFilter

日志记录配置.java

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:logging.properties")
public class LoggingConfig {

    @Autowired
    private Environment env;

    public CommonsRequestLoggingFilter requestLoggingFilter() {
        CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
        loggingFilter.setIncludeClientInfo(env.getProperty("logging.client"));
        loggingFilter.setIncludeQueryString(env.getProperty("logging.query"));
        loggingFilter.setIncludePayload(env.getProperty("logging.payload"));
        loggingFilter.setIncludeHeaders(env.getProperty("logging.headers"));
        return loggingFilter;
    }

    @Bean
    public CommonsRequestLoggingFilter springLogging() {
        Logger logger = (Logger) LoggerFactory.getLogger(CommonsRequestLoggingFilter.class);
                logger.setLevel(Level.DEBUG);
        return requestLoggingFilter();
    }
}

日志记录.属性

logging.client = true
logging.query = true
logging.payload = true
logging.headers = true

相关问题