日志介绍
日志作用:记录程序的运行轨迹,方便查找关键信息以及快速定位解决问题
日志实现框架
- 具体的日志功能实现
- 日志实现框架有:JUL、Log4j、Logback、Log4j2
日志门面框架
- 具体实现的抽象层,定义log.info、log.error等方法
- 日志的门面框架主要有两个:JCL和SLF4J
- 日志门面框架是避免日志实现中代码的改动影响用户的使用,抽象日志的实现接口,使得上层用户只需要调用接口而不用感知接口内部的实现
日志发展历程
- JDK1.3及以前,通过System.out|err.println打印,存在巨大缺陷
- 为了解决系统打印缺陷问题,出现了log4j,但2015年8月停止更新
- 受到log4j影响,SUN公司推出java.util.logging即JUL
- 由于存在两个系统的实现,为了解决兼容性问题,Apache推出了门面框架commons-logging即JCL,可以使用它兼容不同的日志实现框架,但是它对log4f和JUL的配置兼容问题处理的不是很好,存在一定的缺陷
- 随后log4j的作者推出了slf4j,功能完善兼容性好,成为业界主流
- log4j的作者在推出log4j后进行了新的思考,改进后推出了logback
- log4j2是对log4j的重大升级,修复已知缺陷,极大提升性能
- 最佳组合:slf4j+logback(SpringBoot使用)或者slf4j+log4j2
日志实现寻址解析
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
private Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
......
}
- 通过debug模式会进入到getLogger方法中
public static Logger getLogger(Class> clazz) {
Logger logger = getLogger(clazz.getName());
if (DETECT_LOGGER_NAME_MISMATCH) {
Class> autoComputedCallingClass = Util.getCallingClass();
if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) {
Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(), autoComputedCallingClass.getName()));
Util.report("See http://www.slf4j.org/codes.html#loggerNameMismatch for an explanation");
}
}
return logger;
}
public static Logger getLogger(String name) {
ILoggerFactory iLoggerFactory = getILoggerFactory();
return iLoggerFactory.getLogger(name);
}
- 跟进getILoggerFactory()方法
static final int UNINITIALIZED = 0;
static final int ONGOING_INITIALIZATION = 1;
static final int FAILED_INITIALIZATION = 2;
static final int SUCCESSFUL_INITIALIZATION = 3;
static final int NOP_FALLBACK_INITIALIZATION = 4;
public static ILoggerFactory getILoggerFactory() {
//判断当前的日志启动状态是否是未启动
if (INITIALIZATION_STATE == UNINITIALIZED) {
synchronized (LoggerFactory.class) {
//duble check
if (INITIALIZATION_STATE == UNINITIALIZED) {
INITIALIZATION_STATE = ONGOING_INITIALIZATION;
//实现寻址
performInitialization();
}
}
}
switch (INITIALIZATION_STATE) {
case SUCCESSFUL_INITIALIZATION:
//通过StaticLoggerBinder获取获取LoggerFactory
return StaticLoggerBinder.getSingleton().getLoggerFactory();
case NOP_FALLBACK_INITIALIZATION:
return NOP_FALLBACK_FACTORY;
case FAILED_INITIALIZATION:
throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
case ONGOING_INITIALIZATION:
// support re-entrant behavior.
// See also http://jira.qos.ch/browse/SLF4J-97
return SUBST_FACTORY;
}
throw new IllegalStateException("Unreachable code");
}
- 通过performInitialization()方法实现寻址
private final static void performInitialization() {
bind();
if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
versionSanityCheck();
}
}
- 点击跟进bind方法
private final static void bind() {
try {
Set staticLoggerBinderPathSet = null;
// skip check under android, see also
// http://jira.qos.ch/browse/SLF4J-328
//如果不是安卓环境
if (!isAndroid()) {
staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
}
// the next line does the binding
StaticLoggerBinder.getSingleton();
INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
reportActualBinding(staticLoggerBinderPathSet);
fixSubstituteLoggers();
replayEvents();
// release all resources in SUBST_FACTORY
SUBST_FACTORY.clear();
} catch (NoClassDefFoundError ncde) {
String msg = ncde.getMessage();
if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION;
Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
Util.report("Defaulting to no-operation (NOP) logger implementation");
Util.report("See " + NO_STATICLOGGERBINDER_URL + " for further details.");
} else {
failedBinding(ncde);
throw ncde;
}
} catch (java.lang.NoSuchMethodError nsme) {
String msg = nsme.getMessage();
if (msg != null && msg.contains("org.slf4j.impl.StaticLoggerBinder.getSingleton()")) {
INITIALIZATION_STATE = FAILED_INITIALIZATION;
Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");
Util.report("Your binding is version 1.5.5 or earlier.");
Util.report("Upgrade your binding to version 1.6.x.");
}
throw nsme;
} catch (Exception e) {
failedBinding(e);
throw new IllegalStateException("Unexpected initialization failure", e);
}
}
- 跟进findPossibleStaticLoggerBinderPathSet方法
private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";
static Set findPossibleStaticLoggerBinderPathSet() {
// use Set instead of list in order to deal with bug #138
// LinkedHashSet appropriate here because it preserves insertion order
// during iteration
Set staticLoggerBinderPathSet = new LinkedHashSet();
try {
//获取loggerFactoryClassLoader便于加载资源
ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader();
Enumeration paths;
if (loggerFactoryClassLoader == null) {
paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
} else {
//加载资源
paths = loggerFactoryClassLoader.getResources(STATIC_LOGGER_BINDER_PATH);
}
while (paths.hasMoreElements()) {
URL path = paths.nextElement();
//将StaticLoggerBinder.class添加到集合当中,如果存在多个的话,会依次添加
staticLoggerBinderPathSet.add(path);
}
} catch (IOException ioe) {
Util.report("Error getting resources from path", ioe);
}
return staticLoggerBinderPathSet;
}
- 接着跟进reportMultipleBindingAmbiguity方法,主要判断binderPathSet集合的数量是否大于1,如果存在多个日志实现框架的话,会打印日志提示
private static void reportMultipleBindingAmbiguity(Set binderPathSet) {
if (isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) {
Util.report("Class path contains multiple SLF4J bindings.");
for (URL path : binderPathSet) {
Util.report("Found binding in [" + path + "]");
}
Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation.");
}
}
private static boolean isAmbiguousStaticLoggerBinderPathSet(Set binderPathSet) {
return binderPathSet.size() > 1;
}
- 接着跟进getSingleton方法,如果StaticLoggerBinder不存在,则会抛异常
private static StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
public static StaticLoggerBinder getSingleton() {
return SINGLETON;
}
- 跟进reportActualBinding(staticLoggerBinderPathSet)方法,如果binderPathSet集合不为null,并且集合数量为多个的话,那么就会输出一行日志提醒
private static void reportActualBinding(Set binderPathSet) {
// binderPathSet can be null under Android
if (binderPathSet != null && isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) {
Util.report("Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + "]");
}
}
日志配置
在spring-boot-starter里面引入了spring-boot-starter-logging,而spring-boot-starter-logging里面又引入了logback-classic、log4j-to-slf4j、jul-to-slf4j,其关系图如下所示:
日志使用方式
- Logger log = LoggerFactory.getLogger(xxx.class);
- 如果添加了lombok依赖可以使用@Slf4j
- log.level("xyz {} is {}",i ,j),比如log.info(),log.error()等
日志level如下所示:
日志配置
- scan:当此属性设置为true时,配置文档如果发生改变,将会被重新加载,默认值为true
- scanPeriod:设置监测配置文档是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。
- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。
configuration子节点:
contextName:上下文名称
用来区分不同应用程序的记录,默认为default
logback
property:属性配置
name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义后,可以使“${}”来使用变量
还可以通过
appender:格式化日志输出
${log.path}/xundu_info.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${log.path}/xundu-info-%d{yyyy-MM-dd}.%i.log
100MB
20GB
15
info
ACCEPT
DENY
常用的pattern介绍
- logger{length}:输出日志的logger名,可有一个整型参数,功能是缩短logger名
- contextName|cn:上下文名称
- date {pattern}:输出日志的打印信息,模式语法与java.test.SimpleDateFormat兼容
- p/le/level:日志级别
- M/method:输出日志的方法名
- r/relative:从程序启动到创建日志记录的时间
- m/msg/message:程序提供的信息
- n:换行符
root:全局日志输出设置
logger:具体包或子类输出设置
用来设置某一个包或者具体的某一个类的日志打印级别、以及指定 。 仅有一个name属性,一个可选的level和一个可选的addtivity属性。 - name:用来指定受此logger约束的某一个包或者具体的某一个类。
- level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。如果未设置此属性,那么当前logger将会继承上级的级别。
- addtivity:是否向上级logger传递打印信息。默认是true。
日志实战
在工作开发当中,日志通常都是和切面结合使用,也就是说会在项目中建一个异常切面来捕获程序中抛出的错误,捕获之后会记录异常的基本信息,以及根据异常的级别来分别使用不同的日志级别来记录,例如,业务异常使用警告级别就可以了,对于系统级别的异常则需要使用error来记录,
引入aop starter
org.springframework.boot
spring-boot-starter-aop
logback-spring.xml文件
logback
INFO
${CONSOLE_LOG_PATTERN}
UTF-8
${LOG_FILE}
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${LOG_FILE}.%d{yyyy-MM-dd}.%i.log
100MB
20GB
15
创建业务异常和系统异常类
public class BusinessException extends RuntimeException {
public BusinessException() {
}
public BusinessException(String message) {
super(message);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
public BusinessException(Throwable cause) {
super(cause);
}
public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
public class SystemException extends RuntimeException {
public SystemException() {
}
public SystemException(String message) {
super(message);
}
public SystemException(String message, Throwable cause) {
super(message, cause);
}
public SystemException(Throwable cause) {
super(cause);
}
public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
创建异常切面
@Component
@Aspect
public class ExceptionAspect {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAspect.class);
@AfterThrowing(pointcut = "within(com.yibo.controller.*)", throwing = "ex")
public void handlerException(JoinPoint joinPoint,Exception ex)throws Exception{
//出错的类
Class declaringType = joinPoint.getSignature().getDeclaringType();
//获取全类名
String clazz = declaringType.getCanonicalName();
//获取具体出错的方法
String name = joinPoint.getSignature().getName();
if(ex instanceof BusinessException){
logger.warn("clazz:{},name:{}",clazz,name,ex);
}else if(ex instanceof SystemException){
logger.error("clazz:{},name:{}",clazz,name,ex);
}
throw ex;
}
}
演示异常抛出
@Component
public class DemoHandler {
@Autowired
private PersonService personService;
public Mono queryPerson(ServerRequest request){
Integer id = Integer.valueOf(request.pathVariable("id"));
//日志切面演示
if(id == 1){
throw new BusinessException("can not use this id " + id);
}else if(id == 2){
throw new SystemException("can not use this id " + id);
}
return ok().contentType(MediaType.APPLICATION_JSON_UTF8)
.body(Mono.just(personService.getPersonById(id)), Person.class);
}
}
在启动内上添加开启切面功能的注解
@SpringBootApplication
@MapperScan("com.yibo.mapper")
@EnableAspectJAutoProxy//开启切面功能
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
Siftingappender
logback 按照业务主键分文件输出日志,使用SiftingAppender结合MDC
修改logback-spring.xml文件
logback
INFO
${CONSOLE_LOG_PATTERN}
UTF-8
${BIZ_FILE}
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${BIZ_FILE}.%d{yyyy-MM-dd}.%i.log
100MB
20GB
15
修改异常抛出
@Component
public class DemoHandler {
@Autowired
private PersonService personService;
public Mono queryPerson(ServerRequest request){
Integer id = Integer.valueOf(request.pathVariable("id"));
//日志切面演示
if(id == 1){
MDC.put("bizType","MONEY");
throw new BusinessException("can not use this id " + id);
}else if(id == 2){
MDC.put("bizType","HOUSE");
throw new SystemException("can not use this id " + id);
}
return ok().contentType(MediaType.APPLICATION_JSON_UTF8)
.body(Mono.just(personService.getPersonById(id)), Person.class);
}
}
日志结合切面的步骤
业务日志分类
详细的日志文件
logback
INFO
${CONSOLE_LOG_PATTERN}
UTF-8
${log.path}/xundu_debug.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${log.path}/xundu-debug-%d{yyyy-MM-dd}.%i.log
100MB
15
20GB
debug
ACCEPT
DENY
${log.path}/xundu_info.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${log.path}/xundu-info-%d{yyyy-MM-dd}.%i.log
100MB
20GB
15
info
ACCEPT
DENY
${log.path}/xundu_warn.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${log.path}/xundu-warn-%d{yyyy-MM-dd}.%i.log
100MB
15
20GB
warn
ACCEPT
DENY
${log.path}/xundu_error.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${log.path}/xundu-error-%d{yyyy-MM-dd}.%i.log
100MB
15
20GB
ERROR
ACCEPT
DENY
#s_logger#%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{50}-%line) %msg #e_logger#%n
UTF-8
${log.base}/normal/normal.%d{yyyy-MM-dd}.log
30
#s_logger#%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{50}-%line) %msg #e_logger#%n
UTF-8
ERROR
DENY
ACCEPT
${log.base}/sql/sql.%d{yyyy-MM-dd}.log
30
#s_logger#%d{yyyy-MM-dd HH:mm:ss.SSS}%n%msg #e_logger#%n
UTF-8
ERROR
ACCEPT
DENY
${log.base}/error/error.%d{yyyy-MM-dd}.log
30
#s_logger#%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{50}-%line) %msg #e_logger#%n
UTF-8
ERROR
ACCEPT
DENY
logging:
level:
com.netflix.discovery: 'OFF'
org.springframework.cloud: 'INFO'
com.xundu.service.mapper: 'WARN'
参考:
https://www.cnblogs.com/zhangjianbing/p/8992897.html
https://www.cnblogs.com/jpfss/p/11090550.html
https://www.cnblogs.com/liufei96/p/16069903.html
https://www.cnblogs.com/flyingrun/p/16631090.html
https://www.dandelioncloud.cn/article/details/1510720395119546369