使线程转储智能化

很久以前,我了解了一个称为Log MDC的东西,我对此非常感兴趣。 我突然能够理解日志文件中发生的所有事情,并指出特定的日志条目,并找出对错,特别是在调试生产中的错误时。

在2013年,我受委托从事一个项目,该项目正在一些麻烦的水域(几件事情的结合)中运行,几乎每个星期,我不得不经历几次Java Thread Dump,以弄清应用程序中发生的事情以使其停止。 另外,有时我不得不将诸如AppDynamic,jProfiler,jConsole之类的探查器全部连接到应用程序,以试图找出问题所在,更重要的是是什么引发了问题。 jStack是我使用过的最有用的工具之一,但是碰到的线程转储没有我可以使用的上下文信息。 我被困在看到10(s)个转储的堆栈跟踪中,哪些类导致了该块,但是没有有关什么是什么以及什么输入导致了该问题的信息,并且它很快就令人沮丧。 最终,我们找到了问题,但是它们主要是在经过数轮深度调试后使用各种数据集对代码进行的。

一旦完成该项目,我发誓我再也不会陷入那种境地了。 我探索了可以使用类似于Log4j的NDC但在线程中使用它的方式,以便我的转储有意义。 而且我发现我可以更改ThreadName。 我的下一个项目确实非常有效地使用了它。 我最近遇到了一篇文章,很好地解释了这个概念。 我不会重写他们所说的所有内容,因此这里是他们博客文章的链接 。

所以上周我开始一个新项目,当我开始编码框架时(使用Spring 4.1和Spring Boot),这是我为应用程序编写的第一个类,并确保过滤器尽快进入代码。帮助我们进行后期制作,但也使我的开发日志有意义。

下面是Log4j NDC和设置ThreadName的代码副本。

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;/*** This is a very Spring opinionated HTTPFilter used for intercepting all requests and decorate the thread name with additional contextual* information. We have extenced the filter from {@link OncePerRequestFilter} class provided by Spring Framework to ensure that the filter is absolutely * executd only once per request. * * The following information will be added:* <ul>* <li>Old Thread name: to ensure that we are not losing any original context with thread names;</li>* <li>Time when the request was intercepted;</li>* <li>The RequestURI that proviced information on what RestFUL endpoint was accessed as part of this request;</li>* <li>A Token that was received in the header. This token is encrypted and does not exposes any confidential information. Also, this token provides* context which helps during debugging;</li>* <li>The Payload from the token. This information will be very helpful when we have to debug for issues that may be happening with a call request* as this holds all the information sent from the called.</li>* </ul>* * This filter will also reset the ThreadName back to it's original name once the processing is complete.* * @author Kapil Viren Ahuja**/
public class DecorateThreadNameFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {final Logger LOGGER = LoggerFactory.getLogger(DecorateThreadNameFilter.class);final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");Thread thread = Thread.currentThread();String threadOriginalName = thread.getName();String uri = request.getRequestURI();String time = dateFormat.format(new Date());String token = request.getHeader("authorization");try {thread.setName(String.format("%s StartTime \"%s\" RequestURI \"%s\" Token \"%s\"", threadOriginalName, time, uri, token));} catch (Exception ex) {LOGGER.error("Failed to set the thread name.", ex);// this is an internal filter and an error here should not impact// the request processing, hence eat the exception}try {filterChain.doFilter(request, response);} finally {try {thread.setName(threadOriginalName);} catch (Exception ex) {LOGGER.error("Failed to reset the thread name.", ex);// this is an internal filter and an error here should not// impact the request processing, hence eat the exception}}}
}
/*** Generic filter for intercepting all requests and perform the following generic tasks:* * <ul>* <li>Intercepts the request and then pushed the user domain into the session if one exists.</li>* <li> Pushes a uniquely generated request identifier to the LOG4J NDC context. This identifier will then be prepended* to all log messages generated using LOG4J. This allows tracing all log messages generated as part of the same* request; </li>* <li> Pushes the HTTP session identifier to the LOG4J NDC context. This identifier will then be prepended to all log* messages generated using LOG4J. This allows tracing all log messages generated as part of the same HTTP session;* </li>* <li> Pushes the IP address of the client to the LOG4J NDC context. The IP address will then be prepended to all log* messages generated using LOG4J. This allows tying back multiple user sessions initiated with the same logon name to* be correctly tied back to their actual origins. </li>* </ul>*/
public class RequestInterceptorFilter implements Filter
{/*** <p>* <ul>* <li>Initializes the LOG4J NDC context before executing an HTTP requests.</li>* <li>Pushes the domain into the session</li>* </ul>* </p>*/public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{HttpServletRequest httpRequest = (HttpServletRequest) request;if (httpRequest.isRequestedSessionIdFromCookie() && !httpRequest.isRequestedSessionIdValid()){// TODO: Need to define an session expiration page and redirect the application to that page// As of now this is a non-issue as we are handling session expirations on Flex (Front-end) and hence// no request will come to server in case the session timeout occurs// HttpServletResponse httpServletResponse = (HttpServletResponse) response;// httpServletResponse.sendRedirect(httpRequest.getContextPath() + "?expired");}else{// Create an NDC context string that will be prepended to all log messages written to files.org.apache.log4j.NDC.push(getContextualInformation(httpRequest));// Process the chain of filterschain.doFilter(request, response);// Clear the NDC context string so that if the thread is reused for another request, a new context string is// used.org.apache.log4j.NDC.remove();}}public void init(FilterConfig arg0) throws ServletException{}public void destroy(){}/*** <p>* Generates the Contextual information to be put in the log4j's context. This information helps in tracing requests* </p>* * @param httpRequest* @return*/private String getContextualInformation(HttpServletRequest httpRequest){String httpRequestIdentifier = UUID.randomUUID().toString();String httpSessionIdentifier = httpRequest.getSession().getId();String clientAddress = httpRequest.getRemoteAddr();StringBuffer logNDC = new StringBuffer(httpRequestIdentifier + " | " + httpSessionIdentifier + " | " + clientAddress);String userName = (String)httpRequest.getSession().getAttribute(WebConstants.USERNAME);if (userName != null){logNDC.append(" | " + userName);}String domain = (String)httpRequest.getSession().getAttribute(WebConstants.DOMAIN);if (domain != null){logNDC.append(" | " + domain);}// Create an NDC context string that will be prepended to all log messages written to files.return logNDC.toString();}
}

翻译自: https://www.javacodegeeks.com/2015/08/making-thread-dumps-intelligent.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/358519.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

sqlmap --tamper 绕过WAF脚本分类整理

每当注入的时候看到这个贱贱的提示框&#xff0c;内心有千万只草泥马在奔腾。 但很多时候还是得静下来分析过滤系统到底过滤了哪些参数&#xff0c;该如何绕过。 sqlmap中的tamper给我们带来了很多防过滤的脚本&#xff0c;非常实用&#xff0c;可能有的朋友还不知道怎样才能最…

linux shell if 参数

shell 编程中使用到得if语句内判断参数 –b 当file存在并且是块文件时返回真 -c 当file存在并且是字符文件时返回真 -d 当pathname存在并且是一个目录时返回真 -e 当pathname指定的文件或目录存在时返回真 -f 当file存在并且是正规文件时返回真 -g 当由pathname指定的文件或目录…

计算机算法知识总结,移动笔试知识点之--计算机类-数据结构与算法知识点总结.pdf...

12345612int Push (SeqStackSeqStackSeqStack *s*s*s datatypedatatypedatatype x)x)x){ if s->top MAXLEN>top MAXLEN>top MAXLEN–1–1–1return 0 // 0 datatype Pop SeqStack *selse { s->top { datatype x;s->data[s->top]x>top]x>top]x // x if …

教你玩转CSS 提示工具(Tooltip)

如何使用 HTML 与 CSS 来创建提示工具。 提示工具在鼠标移动到指定元素后触发 基础提示框(Tooltip) 提示框在鼠标移动到指定元素上显示: <style>/* Tooltip 容器 */.tooltip {position: relative;display: inline-block;border-bottom: 1px dotted black; /* 悬停元素…

table 首先冻结_首先记录异常的根本原因

table 首先冻结Logback日志库的0.9.30版本带来了一个很棒的新功能&#xff1a;从根&#xff08;最内部&#xff09;异常而不是最外部异常开始记录堆栈跟踪。 当然&#xff0c;我的激动与我贡献了此功能无关。 用塞西尔德米勒&#xff08;Cecil B. de Mille&#xff09; 的话来形…

Spring Boot框架敏感信息泄露的完整介绍与SRC实战(附专属字典与PoC)

转载于&#xff1a;https://www.freebuf.com/vuls/289710.html #前言##Spring Boot框架介绍Spring框架功能很强大&#xff0c;但是就算是一个很简单的项目&#xff0c;我们也要配置很多东西。因此就有了Spring Boot框架&#xff0c;它的作用很简单&#xff0c;就是帮我们自动配…

php html邮件,php发送HTML邮件

PHP 发送HTML邮件需要实现php自动发邮件&#xff0c;原本希望调用Jmail组件实现的&#xff0c;但是发送中文内容的时候&#xff0c;在邮件正文后面总是多出一串乱码&#xff0c;另我很纠结&#xff0c;在网上找了半天也没有能找到原因&#xff0c;无奈之下找了一个socket实现的…

教你玩转CSS响应式设计

目录 什么是 Viewport? 设置 Viewport CSS 网格视图 什么是网格视图? 响应式网格视图 CSS 媒体查询 添加断点

从外网Thinkphp3日志泄露到杀入内网域控 - 红队攻击之域内靶机渗透实战演练

1.简要描述 这个工具写完有一段时间了&#xff0c;看网上目前还没有一个thinkphp的漏洞集成检测工具&#xff0c;所以打算开源出来。 2.代码结构 插件化思想&#xff0c;所有的检测插件都plugins目录里&#xff0c;TPscan.py主文件负责集中调度。 插件目录: ThinkPHP 用户…

使用WildFly 9和Jolokia监视DevOps样式

DevOps是当今最热门的话题之一。 而且围绕它的主题范围很广&#xff0c;因此很难真正找到完整的描述或涵盖体面粒度的所有内容。 可以肯定的一件事&#xff1a;最重要的部分之一是提供正确的度量标准和信息以监视应用程序。 Java EE和JMX 监视Java EE服务器的标准方法是JMX。 …

深刻理解Servlet运行机制和生命周期

servlet 运行在servlet 容器中,其生命周期由容器来管理。servlet 的生命周期通过 javax.servlet.Servlet接口中的init(),servce(),和destory();方法表示。1&#xff0c;加载和实例化servlet 容器负责加载和实例化servlet 当容器启动或在容器中检测到需要这个servlet来响应一个请…

太原师范学院计算机二级报名,山西计算机等级考试报名地点

2010年下半年全国计算机等级考试时间是2010年9月18日至22日&#xff0c;第一天上午考笔试&#xff0c;上机考试从笔试的当天下午开始(一级从上午开始)。2010年下半年全国计算机等级考试报名时间已经开始&#xff01;如果您是在校生&#xff0c;去学校相关报名处报名最方便&…

教你玩转CSS 图像透明/不透明

目录 图像的透明度 - 悬停效果 透明的盒子中的文字 使用CSS很容易创建透明的图像。 注意:CSS Opacity属性是W3C的CSS3建议的一部分。 img{opacity:0.4;filter:alpha(opacity=40); /* IE8 及其更早版本 */}img:hover{opacity:1.0;filter:alpha(opacity=100); /* IE8 及其更…

QQ聊天记录恢复、迁移教程(改变默认存储位置、个人文件夹保存位置)

方法一&#xff1a;适用于将原QQ聊天记录存储位置迁移至非系统盘 1、 在想要存储的区域新建文件夹&#xff0c;如&#xff1a; E:\099 Chat Data\Tencent Files\。 2、 打开电脑QQ&#xff0c;设置——文件管理。 3、 点击浏览&#xff0c;选择099 Chat Data下的Tencent Files…

进程的逻辑设备如何与一个物理设备建立对应的关系?

逻辑设备与物理设备的联系通常是由操作系统命令语言中提供的信息实现的。 1、 软通道实现设备独立性。使用高级语言提供的指派语句&#xff0c;通过指派一个逻辑设备名来定义一个设备或文件。如fd open(“/dev/lp”,mode) 2、 通过作业说明书实现设备独立性。 3、 &#xf…

教你玩转CSS 精灵图/雪碧图

目录 精灵图/雪碧图 图像拼合 - 简单实例 图像拼合 - 创建一个导航列表 图像拼合s - 悬停效果 精灵图/雪碧图 精灵图/雪碧图就是图像拼合 也就是单个图像的集合。 有许多图像的网页可能需要很长的时间来加载和生成多个服务器的请求。 使用图像拼合会降低服务器的请求数量…

html type=text/css,type=text/css 有什么用啊 ?

用处是告诉浏览器&#xff0c;这段标签内包含的内容是css或text&#xff0c;也就是说如果某种浏览器(特别是wap等手机浏览器械、)不能识别css的&#xff0c;会将代码认为text&#xff0c;从而不显示也不报错。type->类型,这里是style的属性text/css ->文本/css,即css文本…

记一次应急响应到溯源入侵者

文本转载于&#xff1a;https://www.freebuf.com/articles/web/289450.html 1. 前言今年的某月某日&#xff0c;系统监测到客户的一企业官网www.******.com遭到了网页篡改&#xff0c;经过人工确认将浏览器的UA替换为百度UA后访问网站&#xff0c;此时网站链接自动跳转至赌博类…

系统测试集成测试单元测试_单元和集成测试的代码覆盖率

系统测试集成测试单元测试我最近在一个宠物项目中着手构建自动化的UI&#xff08;集成&#xff09;测试以及普通的单元测试。 我想将所有这些集成到我的Maven构建中&#xff0c;并提供代码覆盖率报告&#xff0c;以便我可以了解测试覆盖率不足的区域。 我不仅发布了项目的源代码…

教你玩转CSS 媒体类型

目录 CSS 媒体类型 媒体类型 @media 规则 其他媒体类型 CSS 媒体类型 媒体类型允许你指定文件将如何在不同媒体呈现。该文件可以以不同的方式显示在屏幕上,在纸张上,或听觉浏览器等等。 媒体类型 一些 CSS 属性只设计了某些媒体。例如 voice-family 属性是专为听觉用户…