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_project\boottest\target\classes started by jiang in D:\idea_project\boottest)
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 Files\jdk\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;D:\Program Files\jdk\bin;D:\Program Files\TortoiseSVN\bin;C:\Program Files\MySQL\MySQL Utilities 1.6\;C:\Users\jiang\AppData\Local\Microsoft\WindowsApps;;.]
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 结束

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏奇点大数据

Flume:流式数据收集利器

在数据生命周期里的第一环就是数据收集。收集通常有两种办法,一种是周期性批处理拷贝,一种是流式收集。今天我们就说说流式收集利器Flume怎么使用。 使用flume...

41860
来自专栏阮一峰的网络日志

如何选择开源许可证?

如何为代码选择开源许可证,这是一个问题。 世界上的开源许可证,大概有上百种。很少有人搞得清楚它们的区别。即使在最流行的六种----GPL、BSD、MIT、Moz...

35770
来自专栏Java 源码分析

关于apache端口被占用

正文 无论我们在安装单个的apache还是装集成环境xampp都是有可能遇到apache意外停止。查看错误日志会发现一般都是端口被占用,一般是被虚拟机占用了,这...

46870
来自专栏有趣的django

4. sudo,PATH环境变量,修改字符集,ntpserver,加大文件描述符,隐藏内核版本,锁定关键系统文件

1   命令:  visudo            98gg      98行             yy           复制当前行         ...

35960
来自专栏安恒信息

安恒紧急预警:httpoxy 远程代理感染漏洞

漏洞描述 近日,爆出httpoxy漏洞,该漏洞主要存在于apache等组件中,原理是将HTTP头部的Proxy字段名变换为“HTTP_PROXY”,Value值...

325110
来自专栏专知

【下载】面向搜索的深度学习实战书籍和代码《Deep Learning for Search》

【导读】 信息检索资深专家Tommaso Teofili最新撰写的面向搜索的深度学习实战书籍(预计2018年夏季出版)《Deep Learning for Se...

1K70
来自专栏专知

最新Apache Spark平台的NLP库,助你轻松搞定自然语言处理任务

【导读】这篇博文介绍了Apache Spark框架下的一个自然语言处理库,博文通俗易懂,专知内容组整理出来,希望大家喜欢。 ▌引言 ---- Apache S...

70280
来自专栏安恒信息

Struts2 S2-049 拒绝服务漏洞分析报告

安全通告 尊敬的客户: 2017年7月11日,Struts2官方公布最新的Struts2漏洞公告-编号S2-049。该漏洞公告中说明:在一定条件下该漏洞可造成拒...

31750
来自专栏专知

【资源】机器学习必知的15大框架

【导读】机器学习工程师是开发产品和构建算法团队中的一部分,并确保其可靠、快速和成规模地工作。他们和数据科学家密切合作来了解理论知识和行业应用。数据专家和机器学习...

35870
来自专栏IT笔记

linux下 Error running javac compiler

由于Linux版本更新,虽然软件都拷贝过来了,但是系统环境重新配置。 旧系统配置了ANT一键部署功能的脚本,由于部署需要,所以这里又重新配置了下环境。 1、A...

44950

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励