Java Flight Recorder – how to extract the values of a custom event field?
Java Flight Recorder is now a part of OpenJDK 11 and offers the usage of custom events. After a successful recording, I want to reuse the information within the events (especially my own custom events), but somehow I am unable to read the field content of an event. I can only see the annotations, the name and the type of the fields.
Does anybody know whether this is actually possible?
JFR has a consumer package which allows you to read information from the files. I already apply some of the functions.
What I already tried
First, I access all the fields of an event:
event.getFields();
Then I iterate over the fields and access their values in a few different ways:
a) eventField.getDescriptor(); b) eventField.getContentType();
Just looking at their names, obviously none of them would give me the content. Unfortunately I couldn’t find any function that could help.
What I also tried
I also tried a very straight-forward idea: read the content in debug modus. I thought it would offer me some insight on how to programatically extract those information.
Unfortunately, JFR managed to encode their recordings in a way, that during a debug procedure, one is not able to read the information, until one programatically extracted them and has it as a local variable (example: a map).
For your information, I have been using this instruction for the custom event implementation.
Here is a short program that illustrates how you can get the values
public class Example { public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Must specify a recording file."); return; } List<RecordedEvent> events = RecordingFile.readAllEvents(Path.of(args[0])); for (RecordedEvent event : events) { EventType eventType = event.getEventType(); String name = eventType.getName(); Instant start = event.getStartTime(); Instant end = event.getEndTime(); System.out.println(name + " " + start + " - " + end); for (ValueDescriptor field : eventType.getFields()) { String fieldName = field.getName(); Object value = event.getValue(fieldName); System.out.println(fieldName + " = " + value); } System.out.println(); } }
If you want to find example code of all aspects of JFR, you can look in the test folder in the OpenJDK project. For example, the test of a RecordedEvent