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 结束
Spring Boot使用Log4j Implemented Over SLF4J生成日志并在控制台打印的更多相关文章
- spring boot / cloud (十六) 分布式ID生成服务
spring boot / cloud (十六) 分布式ID生成服务 在几乎所有的分布式系统或者采用了分库/分表设计的系统中,几乎都会需要生成数据的唯一标识ID的需求, 常规做法,是使用数据库中的自动 ...
- Java | Spring Boot Swagger2 集成REST ful API 生成接口文档
Spring Boot Swagger2 集成REST ful API 生成接口文档 原文 简介 由于Spring Boot 的特性,用来开发 REST ful 变得非常容易,并且结合 Swagg ...
- Spring Boot 揭秘与实战(三) 日志框架篇 - 如何快速集成日志系统
文章目录 1. 默认的日志框架 logback2. 常用的日志框架 log4j 1.1. 日志级别 1.2. 日志文件 3. 源代码 Java 有很多日志系统,例如,Java Util Logging ...
- 9.Spring Boot实战之配置使用Logback进行日志记录
转自:https://blog.csdn.net/meiliangdeng1990/article/details/54300227 Spring Boot实战之配置使用Logback进行日志记录 在 ...
- spring boot中log4j冲突问题和解决办法
Spring Boot中自带了log4j日志管理.写法应该是: private static final Logger logger = Logger.getLogger(XXX.class); 而不 ...
- Spring boot配置log4j输出日志
1. pom.xml文件中配置parent,版本选定[1.2.5.RELEASE] 关于为什么要选这个版本:我尝试使用[1.4.1.RELEASE],但该版本库里没有[spring-boot-star ...
- Spring Boot(九)Swagger2自动生成接口文档和Mock模拟数据
一.简介 在当下这个前后端分离的技术趋势下,前端工程师过度依赖后端工程师的接口和数据,给开发带来了两大问题: 问题一.后端接口查看难:要怎么调用?参数怎么传递?有几个参数?参数都代表什么含义? 问题二 ...
- Spring Boot学习笔记 - 整合Swagger2自动生成RESTful API文档
1.添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <!--swagger2--> <dependency> <groupId>io.spr ...
- 在spring boot 中使用itext和itextrender生成pdf文件
转载请注明出处 https://www.cnblogs.com/majianming/p/9539376.html 项目中需要对订单生成pdf文件,在第一版本其实已经有了比较满意的pdf文档,但是还是 ...
随机推荐
- WCF: Retry when service is in fault state.
Service Host: using System; using System.Configuration; using System.ServiceModel; using System.Serv ...
- jdk1.8.0_45源码解读——LinkedList的实现
jdk1.8.0_45源码解读——LinkedList的实现 一.LinkedList概述 LinkedList是List和Deque接口的双向链表的实现.实现了所有可选列表操作,并允许包括null值 ...
- Python练习-跨目录调用模块
层级结构: dir1 ---hello.py dir2 ---main.py 其中,hello.py: def add(x,y): return x+y main.py如何能调用到hello.py中的 ...
- php魔术函数 __clone()
原文地址: http://www.nowamagic.net/librarys/posts/php/32 PHP4面向对象功能一个很大的缺点,是将对象视为另一种数据类型,这使得很多常见的OOP方法无法 ...
- go语言项目汇总
Horst Rutter edited this page 7 days ago · 529 revisions Indexes and search engines These sites prov ...
- javascript本地缓存方案-- 存储对象和设置过期时间
cz-storage 解决问题 1. 前端js使用localStorage的时候只能存字符串,不能存储对象 cz-storage 可以存储 object undefined number string ...
- 最后一面《HR面》------十大经典提问
1.HR:你希望通过这份工作获得什么? 1).自杀式回答:我希望自己为之工作的企业能够重视质量,而且会给做得好的员工予以奖励.我希望通过这份工作锻炼自己,提升自己的能力,能让公司更加重视我. a.“我 ...
- IntelliJ IDEA 修改IDE字体、代码字体。
IntelliJ IDEA 默认的 IDE 菜单字体太小,看着不舒服 ,我们调节下: ==============以上修改 仅仅针对的IDE字体,对代码的字体不生效. 所以如果代码 你觉得小 还得修改 ...
- Java 从多层嵌套中访问内部类的成员
一个内部类被嵌套多少层并不重要--它能透明地访问所有它能嵌入的外围类的所有成员 //: innerclasses/MultiNestingAccess.java // Nested classes c ...
- caffe可视化
1.画网络图 假