JVM HotSpot 上的 Java 异常计数器

Java Exceptions counter on JVM HotSpot(JVM HotSpot 上的 Java 异常计数器)

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

问题描述

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

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
", 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

这将在标准输出上记录所有异常类名称.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 异常计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:JVM HotSpot 上的 Java 异常计数器

基础教程推荐