关于日志(slf4j的使用心得)

2024-06-23 16:32
文章标签 slf4j 日志 心得 使用

本文主要是介绍关于日志(slf4j的使用心得),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

没有调试过线上bug的人学不会打log

1. Object… arguments

从slf4j-1.6.0开始,public void error(String format, Object... arguments);中arguments的最后一个参数如果是throwable对象,将会被作为异常信息进行打印。
slf4j-1.6.0以前,只能通过public void error(String msg, Throwable t);打印异常信息,缺点是必须通过拼接字符串的形式把arguments组装为msg。

2. MDC的使用

本节内容摘取自:Slf4j MDC 使用和 基于 Logback 的实现分析(感谢原作者)
有了日志之后,我们就可以追踪各种线上问题。但是,在分布式系统中,各种无关日志穿行其中,导致我们可能无法直接定位整个操作流程。因此,我们可能需要对一个用户的操作流程进行归类标记,比如使用线程+时间戳,或者用户身份标识等;如此,我们可以从大量日志信息中grep出某个用户的操作流程,或者某个时间的流转记录。
MDC ( Mapped Diagnostic Contexts ),顾名思义,其目的是为了便于我们诊断线上问题而出现的方法工具类。虽然,Slf4j 是用来适配其他的日志具体实现包的,但是针对 MDC功能,目前只有logback 以及 log4j 支持。
在日志模板中,使用 %X{ }来占位,替换到对应的 MDC 中 key 的值。

看一个MDC使用的简单示例:

public class LogTest {private static final Logger logger = LoggerFactory.getLogger(LogTest.class);public static void main(String[] args) {MDC.put("THREAD_ID", String.valueOf(Thread.currentThread().getId()));logger.info("纯字符串信息的info级别日志");}
}

logback的输出模板配置:

<?xml version="1.0" encoding="UTF-8"?>
<configuration><property name="log.base" value="${catalina.base}/logs" /><contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"><resetJUL>true</resetJUL></contextListener><appender name="console" class="ch.qos.logback.core.ConsoleAppender"><encoder charset="UTF-8"><pattern>[%d{yyyy-MM-dd HH:mm:ss} %highlight(%-5p) %logger.%M\(%F:%L\)] %X{THREAD_ID} %msg%n</pattern></encoder></appender><root level="INFO"><appender-ref ref="console" /></root>
</configuration>

于是,就有了输出:

[2015-04-30 15:34:35 INFO  io.github.ketao1989.log4j.LogTest.main(LogTest.java:29)] 1 纯字符串信息的info级别日志

3. 日志文件的分类

STDOUT:控制台输出日志
RollingFile:完整的日志文件
ErrorFile:保存系统报错
MainFile:保存系统一些关键日志,便于搜索

4. 常用配置

工具类:

package com.example;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;/*** 日志工具类* * @author frcoder*/
public class LogUtil {/*** 记录用户行为*/public static Logger userLog = LoggerFactory.getLogger("@USER");public static void newUserLog(String somethings) {MDC.put("USER", "");MDC.put("DO", somethings);userLog.debug("...");}public static void newUserLog(Object userId, String somethings) {MDC.put("USER", userId.toString());MDC.put("DO", somethings);userLog.debug("...");}public static void newUserLog(Object userId, Object role, String somethings) {MDC.put("USER", UserRole.toRoleString((Integer) role) + ":" + userId.toString());MDC.put("DO", somethings);userLog.debug("...");}public static void userQuit() {MDC.clear();}
}

配置:

Configuration:# Internal Log4j events levelstatus: warn# Automatic Reconfiguration, unit: secondmonitorInterval: 300dest: errname: YAMLConfigproperties:property:-name: projectNamevalue: me-name: logHomevalue: /tmp/logsthresholdFilter:level: debugappenders:## Console appenderConsole:name: STDOUTPatternLayout:Pattern: "%d %-5p %c [%L] [%t] [%X{USER}:%X{DO}] - %m%n"## RollingFile appenderRollingRandomAccessFile:-name: RollingFilefilename: "${logHome}/${projectName}.log"filePattern: "${logHome}/${projectName}.%d{yyyy-MM-dd}-%i.log.gz"PatternLayout:Pattern: "%d %-5p %c [%L] [%t] [%X{USER}:%X{DO}] - %m%n"Policies:SizeBasedTriggeringPolicy:size: 20MBDefaultRollOverStrategy:max: 5Delete:basePath: "/tmp/logs"maxDepth: 1IfFileName:glob: "epg*.log.*"IfLastModified:age: 5d-name: ErrorFilefilename: "${logHome}/${projectName}-error.log"filePattern: "${logHome}/${projectName}-error.%d{yyyy-MM-dd}-%i.log.gz"PatternLayout:Pattern: "%d %-5p %c [%L] [%t] [%X{USER}:%X{DO}] - %m%n"Policies:SizeBasedTriggeringPolicy:size: 20MBDefaultRollOverStrategy:max: 5-name: MainFilefilename: "${logHome}/${projectName}-main.log"filePattern: "${logHome}/${projectName}-main.%d{yyyy-MM-dd}-%i.log.gz"thresholdFilter:level: debugPatternLayout:Pattern: "%d %-5p %c [%L] [%t] [%X{USER}:%X{DO}] - %m%n"Policies:SizeBasedTriggeringPolicy:size: 20MBDefaultRollOverStrategy:max: 5Loggers:logger:-name: com.examplelevel: debugadditivity: falseAppenderRef:- ref: MainFile- ref: STDOUT-name: "@USER"level: debugadditivity: falseAppenderRef:- ref: MainFile- ref: STDOUT-name: org.hibernate.SQLlevel: warnRoot:level: infoAppenderRef:- ref: STDOUTlevel: error- ref: RollingFilelevel: info- ref: ErrorFilelevel: error

注意:上面代码中的additivity属性(false:只在本logger中输出,不要传递给上级logger;true:不仅在本logger中输出,也会传递给上级,如果本logger和上级logger都指向同一个日志文件,则日志可能会在该文件中打印2次。)

特别提示:各个level的优先级
thresholdFilter:总开关,低于这个级别的日志都不会显示
logger下:logger.level和logger.AppenderRef.level的级别取最低值

5. 日志与行为

一般在行为完成之后才打日志,看到日志就表示该行为已完成。

6. Response模板类

package com.example;import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;/*** Response模板类* * @author frcoder*/
@ApiModel(value = "Response", description = "接口响应对象")
public class Response<T> {@ApiModelProperty(value = "编码")@JsonProperty("code")private int code;@ApiModelProperty(value = "消息")@JsonProperty("message")private String message;@ApiModelProperty(value = "数据")@JsonProperty("data")private T data;@JsonIgnoreprivate Exception exception;public static <T> Response<T> ok() {return ok(null, "success");}public static <T> Response<T> ok(T data) {return ok(data, "success");}public static <T> Response<T> ok(T data, String message) {return ok(0, data, message);}public static <T> Response<T> ok(Integer code, T data, String message) {return new Response(code, message, data);}public static <T> Response<T> fail(String message) {return fail(99, message);}public static <T> Response<T> fail(Integer code, String message) {return new Response(code, message);}public static <T> Response<T> failParam(String message) {return fail(400, message);}public static <T> Response<T> error(String message, Exception e) {return error(99, message, e);}public static <T> Response<T> error(Integer code, String message, Exception e) {return new Response(code, message).exception(e);}public Response() {}public Response(int code) {this.code = code;}public Response(int code, String message) {this.code = code;this.message = message;}public Response(int code, String message, T data) {this.code = code;this.message = message;this.data = data;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public Response code(int code) {this.code = code;return this;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public Response message(String message) {this.message = message;return this;}public T getData() {return data;}public void setData(T data) {this.data = data;}public Response data(T data) {this.data = data;return this;}public Exception getException() {return exception;}public void setException(Exception exception) {this.exception = exception;}public Response exception(Exception exception) {this.exception = exception;return this;}
}

7. 注解与切面在日志中的应用

1. 在gradle中引入jar包

compile "org.springframework.boot:spring-boot-starter-aop:${springBootVersion}"

2. 编写注解类

package com.example;import java.lang.annotation.*;/*** @Log注解类* * @author frcoder*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {String value() default "";
}
package com.example;import com.example.Response;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;import static com.example.LogUtil.userLog;/*** LogAop日志切面类* * @author frcoder*/
@Aspect
@Component
public class LogAop {private static Logger logger = LoggerFactory.getLogger(LogAop.class);/*** api.impl包下的函数,如果参数列表是以userId, role开头的会被记录用户日志*/@Pointcut("execution(public * com..api.impl..*.*(..)) || @annotation(Log))")public void log() {}@Before(value = "log()")public void doBeforeLog(JoinPoint joinPoint) {try {String methodName = joinPoint.getSignature().getName();Map args = AOPUtil.getArgs(joinPoint);if (args.containsKey("userId")) {if (args.containsKey("role")) {LogUtil.newUserLog(args.get("userId"), args.get("role"), methodName);} else {LogUtil.newUserLog(args.get("userId"), methodName);}} else {LogUtil.newUserLog(methodName);}} catch (Exception e) {logger.debug("LogAop doBefore new Log is wrong", e);}}@AfterReturning(value = "log()", returning = "ret")public void doAfterReturningLog(Object ret) {try {Response response = (Response) ret;userLog.info("[{}]: {}", response.getCode(), response.getMessage());if (response.getData() != null) {userLog.debug(StringUtil.Obj2JsonStr(response.getData()));}if (response.getException() != null) {userLog.error(response.getException().toString(), response.getException());}} catch (Exception e) {logger.debug("LogAop doAfterReturning is wrong", e);} finally {LogUtil.userQuit();}}}
package com.example;import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;/*** AOP工具类* * @author frcoder*/
public class AOPUtil {private static Logger logger = LoggerFactory.getLogger(AOPUtil.class);/*** 用于提取切入点参数*/public static Map getArgs(JoinPoint joinPoint) {try {String classType = joinPoint.getTarget().getClass().getName();String methodName = joinPoint.getSignature().getName();// 获取参数值Object[] args = joinPoint.getArgs();Class<?>[] classes = new Class[args.length];for (int k = 0; k < args.length; k++) {if (!args[k].getClass().isPrimitive()) {// 获取的是封装类型而不是基础类型String result = args[k].getClass().getName();Class s = map.get(result);classes[k] = s == null ? args[k].getClass() : s;}}// 获取方法(第二个参数可以不传,但是为了防止有重载的现象,还是需要传入参数的类型)Method method = Class.forName(classType).getMethod(methodName, classes);// 获取参数名ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();String[] parameterNames = pnd.getParameterNames(method);// 通过map封装参数名和参数值HashMap<String, Object> paramMap = new HashMap();for (int i = 0; i < parameterNames.length; i++) {paramMap.put(parameterNames[i], args[i]);}return paramMap;} catch (Exception e) {logger.error("提取切入点参数出错", e);}return Collections.EMPTY_MAP;}private static HashMap<String, Class> map = new HashMap<String, Class>() {{put("java.lang.Integer", Integer.class);put("java.lang.Double", Double.class);put("java.lang.Float", Float.class);put("java.lang.Long", Long.class);put("java.lang.Short", Short.class);put("java.lang.Boolean", Boolean.class);put("java.lang.Char", Character.class);}};}

这篇关于关于日志(slf4j的使用心得)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1087684

相关文章

C语言中联合体union的使用

本文编辑整理自: http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=179471 一、前言 “联合体”(union)与“结构体”(struct)有一些相似之处。但两者有本质上的不同。在结构体中,各成员有各自的内存空间, 一个结构变量的总长度是各成员长度之和。而在“联合”中,各成员共享一段内存空间, 一个联合变量

Tolua使用笔记(上)

目录   1.准备工作 2.运行例子 01.HelloWorld:在C#中,创建和销毁Lua虚拟机 和 简单调用。 02.ScriptsFromFile:在C#中,对一个lua文件的执行调用 03.CallLuaFunction:在C#中,对lua函数的操作 04.AccessingLuaVariables:在C#中,对lua变量的操作 05.LuaCoroutine:在Lua中,

Vim使用基础篇

本文内容大部分来自 vimtutor,自带的教程的总结。在终端输入vimtutor 即可进入教程。 先总结一下,然后再分别介绍正常模式,插入模式,和可视模式三种模式下的命令。 目录 看完以后的汇总 1.正常模式(Normal模式) 1.移动光标 2.删除 3.【:】输入符 4.撤销 5.替换 6.重复命令【. ; ,】 7.复制粘贴 8.缩进 2.插入模式 INSERT

Lipowerline5.0 雷达电力应用软件下载使用

1.配网数据处理分析 针对配网线路点云数据,优化了分类算法,支持杆塔、导线、交跨线、建筑物、地面点和其他线路的自动分类;一键生成危险点报告和交跨报告;还能生成点云数据采集航线和自主巡检航线。 获取软件安装包联系邮箱:2895356150@qq.com,资源源于网络,本介绍用于学习使用,如有侵权请您联系删除! 2.新增快速版,简洁易上手 支持快速版和专业版切换使用,快速版界面简洁,保留主

如何免费的去使用connectedpapers?

免费使用connectedpapers 1. 打开谷歌浏览器2. 按住ctrl+shift+N,进入无痕模式3. 不需要登录(也就是访客模式)4. 两次用完,关闭无痕模式(继续重复步骤 2 - 4) 1. 打开谷歌浏览器 2. 按住ctrl+shift+N,进入无痕模式 输入网址:https://www.connectedpapers.com/ 3. 不需要登录(也就是

Toolbar+DrawerLayout使用详情结合网络各大神

最近也想搞下toolbar+drawerlayout的使用。结合网络上各大神的杰作,我把大部分的内容效果都完成了遍。现在记录下各个功能效果的实现以及一些细节注意点。 这图弹出两个菜单内容都是仿QQ界面的选项。左边一个是drawerlayout的弹窗。右边是toolbar的popup弹窗。 开始实现步骤详情: 1.创建toolbar布局跟drawerlayout布局 <?xml vers

C#中,decimal类型使用

在Microsoft SQL Server中numeric类型,在C#中使用的时候,需要用decimal类型与其对应,不能使用int等类型。 SQL:numeric C#:decimal

探索Elastic Search:强大的开源搜索引擎,详解及使用

🎬 鸽芷咕:个人主页  🔥 个人专栏: 《C++干货基地》《粉丝福利》 ⛺️生活的理想,就是为了理想的生活! 引入 全文搜索属于最常见的需求,开源的 Elasticsearch (以下简称 Elastic)是目前全文搜索引擎的首选,相信大家多多少少的都听说过它。它可以快速地储存、搜索和分析海量数据。就连维基百科、Stack Overflow、

flask 中使用 装饰器

因为要完成毕业设计,我用到fountain code做数据恢复。 于是在github上下载了fountain code的python原代码。 github上的作者用flask做了fountain code的demo。 flask是面向python的一个网站框架。 里面有用到装饰器。 今天笔试的时候,我也被问到了python的装饰器。

mathematica的使用

因为做实验用到Bloom filter这一技术,Bloom filter里面的数学公式可以用来画图。 那么用什么画图软件比较好呢? 当然是Mathematica啦。 利用代码Plot[{y=x},{x,0,100}] 就可以画出比较好的图 简直nice