JVM HotSpot上的Java Exceptions计数器 [英] Java Exceptions counter on JVM HotSpot

查看:109
本文介绍了JVM HotSpot上的Java Exceptions计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在不更改应用程序代码的情况下记录JVM级别发生的每个异常?每个例外,我的意思是捕获和未捕获的异常...我想稍后分析这些日志并按异常类型(类)对它们进行分组,并简单地按类型计算异常。我正在使用HotSpot;)

I am wondering is it possible to log every exception which occurs on JVM level without changing application code? By every exception I mean caught and uncaught exception... I would like to analyze those logs later and group them by exception type (class) and simply count exceptions by type. I am using HotSpot ;)

也许更聪明的为什么这样做?例如,任何免费的探查器(YourKit有它,但它不是免费的)?我认为JRockit在管理控制台中有异常计数器,但是没有看到类似的HotSpot。

Maybe there is smarter why of doing it? For example by any free profiler (YourKit has it but it is not free)? I think that JRockit has exception counter in management console, but don't see anything similar for HotSpot.

推荐答案

我相信有免费工具,但即使制作自己的工具也很容易。 JVMTI 将提供帮助。

I believe there are free tools to do it, but even making your own tool is easy. JVMTI will help.

这是一个简单的JVMTI代理,用于跟踪所有异常:

Here is a simple JVMTI agent I made to trace all exceptions:

#include <jni.h>
#include <jvmti.h>
#include <string.h>
#include <stdio.h>

void JNICALL ExceptionCallback(jvmtiEnv* jvmti, JNIEnv* env, jthread thread,
                               jmethodID method, jlocation location, jobject exception,
                               jmethodID catch_method, jlocation catch_location) {
    char* class_name;
    jclass exception_class = (*env)->GetObjectClass(env, exception);
    (*jvmti)->GetClassSignature(jvmti, exception_class, &class_name, NULL);
    printf("Exception: %s\n", class_name);
}


JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
    jvmtiEnv* jvmti;
    jvmtiEventCallbacks callbacks;
    jvmtiCapabilities capabilities;

    (*vm)->GetEnv(vm, (void**)&jvmti, JVMTI_VERSION_1_0);

    memset(&capabilities, 0, sizeof(capabilities));
    capabilities.can_generate_exception_events = 1;
    (*jvmti)->AddCapabilities(jvmti, &capabilities);

    memset(&callbacks, 0, sizeof(callbacks));
    callbacks.Exception = ExceptionCallback;
    (*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks));
    (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_EXCEPTION, NULL);

    return 0;
}

要使用它,请从给定的源创建一个共享库(.so)代码,并使用 -agentpath 选项运行Java:

To use it, make a shared library (.so) from the given source code, and run Java with -agentpath option:

java -agentpath:libextrace.so MyApplication

这将记录stdout上的所有异常类名。 ExceptionCallback 还会收到一个线程,一个方法和发生异常的位置,因此您可以扩展回调以打印更多详细信息。

This will log all exception class names on stdout. ExceptionCallback also receives a thread, a method and a location where the exception occured, so you can extend the callback to print much more details.

这篇关于JVM HotSpot上的Java Exceptions计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆