• Spring Boot使用Log4j Implemented Over SLF4J生成日志并在控制台打印


    Spring Boot设置切面,执行方法的时候在控制台打印出来,并生成日志文件

    引入依赖:

         <!--日志-->
        <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-lang3</artifactId>
          <version>3.7</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-aop</artifactId>
          <version>2.0.0.RELEASE</version>
        </dependency>
    
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>log4j-over-slf4j</artifactId>
          <version>1.7.25</version>
        </dependency>

    配置类;

    package com.jiangwenzhang.boottest.aop;
    
    
    import org.apache.commons.lang3.builder.ToStringBuilder;
    import org.apache.log4j.Logger;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.AfterReturning;
    import org.aspectj.lang.annotation.AfterThrowing;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.springframework.stereotype.Service;
    
    
    /**
     * @Description: 日志管理
     * @author Leo Wu
     * @date 2016年7月6日  下午5:36:38
     * @version 1.0
     */
    @Aspect
    @Service
    public class LoggerAdvice {
        
        private Logger logger = Logger.getLogger(this.getClass());
    
        @Before("within(com.jiangwenzhang..*) && @annotation(loggerManage)")
        public void addBeforeLogger(JoinPoint joinPoint, LoggerManage loggerManage) {
            logger.info("执行 " + loggerManage.description() + " 开始");
            logger.info(joinPoint.getSignature().toString());
            logger.info(parseParames(joinPoint.getArgs()));
        }
        
        @AfterReturning("within(com.jiangwenzhang..*) && @annotation(loggerManage)")
        public void addAfterReturningLogger(JoinPoint joinPoint, LoggerManage loggerManage) {
            logger.info("执行 " + loggerManage.description() + " 结束");
        }
        
        @AfterThrowing(pointcut = "within(com.jiangwenzhang..*) && @annotation(loggerManage)", throwing = "ex")
        public void addAfterThrowingLogger(JoinPoint joinPoint, LoggerManage loggerManage, Exception ex) {
            logger.error("执行 " + loggerManage.description() + " 异常");
        }
    
        private String parseParames(Object[] parames) {
            if (null == parames || parames.length <= 0) {
                return "";
            }
            StringBuffer param = new StringBuffer("传入参数[{}] ");
            for (Object obj : parames) {
                param.append(ToStringBuilder.reflectionToString(obj)).append("  ");
            }
            return param.toString();
        }
        
    }

    自定义接口:

    package com.jiangwenzhang.boottest.aop;
    
    import java.lang.annotation.*;
    
    /**
     * @Description: 日志注解
     * @author Leo Wu
     * @date 2016年7月7日  上午11:34:57
     * @version 1.0
     */
    @Target(ElementType.METHOD)  
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface LoggerManage {
    
        public String description();
    }

    使用:

        @GetMapping("hello")
        @ResponseBody
        @LoggerManage(description="hello")
        public String index(){
            return "hello";
        }

    执行结果:

    完整配置:

    #日志
    logging.file=logs/all.log
    logging.level.com.jiangwenzhang=INFO
    logging.level.org.springframework.web=INFO
    logging.level.org.hibernate=ERROR

    生成的日志文件:

    2018-04-10 10:51:50.689  INFO 14436 --- [main] c.j.boottest.BoottestApplication         : Starting BoottestApplication on LAPTOP-G5KH9NG8 with PID 14436 (D:idea_projectoottest	argetclasses started by jiang in D:idea_projectoottest)
    2018-04-10 10:51:50.691  INFO 14436 --- [main] c.j.boottest.BoottestApplication         : No active profile set, falling back to default profiles: default
    2018-04-10 10:51:50.730  INFO 14436 --- [main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@670002: startup date [Tue Apr 10 10:51:50 CST 2018]; root of context hierarchy
    2018-04-10 10:51:51.679  INFO 14436 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8094 (http)
    2018-04-10 10:51:51.695  INFO 14436 --- [main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2018-04-10 10:51:51.695  INFO 14436 --- [main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.29
    2018-04-10 10:51:51.699  INFO 14436 --- [localhost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:Program Filesjdkin;C:WindowsSunJavain;C:Windowssystem32;C:Windows;C:ProgramDataOracleJavajavapath;C:Program Files (x86)InteliCLS Client;C:Program FilesInteliCLS Client;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;C:Program Files (x86)IntelIntel(R) Management Engine ComponentsDAL;C:Program FilesIntelIntel(R) Management Engine ComponentsDAL;C:Program Files (x86)IntelIntel(R) Management Engine ComponentsIPT;C:Program FilesIntelIntel(R) Management Engine ComponentsIPT;C:Program Files (x86)NVIDIA CorporationPhysXCommon;D:Program Filesjdkin;D:Program FilesTortoiseSVNin;C:Program FilesMySQLMySQL Utilities 1.6;C:UsersjiangAppDataLocalMicrosoftWindowsApps;;.]
    2018-04-10 10:51:51.794  INFO 14436 --- [localhost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2018-04-10 10:51:51.795  INFO 14436 --- [localhost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1065 ms
    2018-04-10 10:51:51.921  INFO 14436 --- [localhost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
    2018-04-10 10:51:51.924  INFO 14436 --- [localhost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2018-04-10 10:51:51.924  INFO 14436 --- [localhost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2018-04-10 10:51:51.925  INFO 14436 --- [localhost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2018-04-10 10:51:51.925  INFO 14436 --- [localhost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2018-04-10 10:51:52.052  INFO 14436 --- [main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-04-10 10:51:52.190  INFO 14436 --- [main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@670002: startup date [Tue Apr 10 10:51:50 CST 2018]; root of context hierarchy
    2018-04-10 10:51:52.233  INFO 14436 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello],methods=[GET]}" onto public java.lang.String com.jiangwenzhang.boottest.controller.IndexController.index()
    2018-04-10 10:51:52.237  INFO 14436 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
    2018-04-10 10:51:52.238  INFO 14436 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
    2018-04-10 10:51:52.258  INFO 14436 --- [main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-04-10 10:51:52.258  INFO 14436 --- [main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2018-04-10 10:51:52.385  INFO 14436 --- [main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2018-04-10 10:51:52.421  INFO 14436 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8094 (http) with context path ''
    2018-04-10 10:51:52.425  INFO 14436 --- [main] c.j.boottest.BoottestApplication         : Started BoottestApplication in 2.03 seconds (JVM running for 2.76)
    2018-04-10 10:52:33.098  INFO 14436 --- [http-nio-8094-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
    2018-04-10 10:52:33.098  INFO 14436 --- [http-nio-8094-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
    2018-04-10 10:52:33.119  INFO 14436 --- [http-nio-8094-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 21 ms
    2018-04-10 10:52:33.145  INFO 14436 --- [http-nio-8094-exec-1] c.j.boottest.aop.LoggerAdvice            : 执行 hello 开始
    2018-04-10 10:52:33.147  INFO 14436 --- [http-nio-8094-exec-1] c.j.boottest.aop.LoggerAdvice            : String com.jiangwenzhang.boottest.controller.IndexController.index()
    2018-04-10 10:52:33.147  INFO 14436 --- [http-nio-8094-exec-1] c.j.boottest.aop.LoggerAdvice            : 
    2018-04-10 10:52:33.151  INFO 14436 --- [http-nio-8094-exec-1] c.j.boottest.aop.LoggerAdvice            : 执行 hello 结束
  • 相关阅读:
    禁止浏览器缩放功能。
    布局
    设置页面大小
    常用英语
    iOS沙盒路径的简单介绍
    关于 pragma使用
    3Dtouch API Peek and Pop
    3Dtouch API Home Screen Quick Actions
    创建一个.framework静态库
    新学期和学生一起尝试使用博客
  • 原文地址:https://www.cnblogs.com/jiangwz/p/8758485.html
Copyright © 2020-2023  润新知