In the previous page, we demonstrated the use of the ReportPublisher, and its Report object in order to send log and report messages through the publisher. In this section, we will demonstrate how to create a custom observer and register it with the ReportPublisher.
Creating a custom observer is a very simple one. Here is a custom observer example:
public class SampleObserver extends BaseObserver {
@Getter
private final List<String> entries;
public SampleObserver() {
super();
entries = new ArrayList<>();
}
@Override
public void update(ReportEntry reportEntry) {
entries.add("SampleObserver data is " + reportEntry.toString());
}
}
All you need to do in order to create an observer is to extend the BaseObserver class and override the update method. This very basic observer simply puts the data in a list of strings.
The next thing we will need to do is register the observer with the publisher.
You can do this operation at any time. It is also a very simple operation:
ReportPublisher.getInstance().register(sampleObserver);
That’s it. From this line forward, our SampleObserver object will be notified of any log or report entry.
The structure of the ReportEntryObject
Here is the implementation of the ReportEntry object:
@Data
@Builder
public class ReportEntry {
ReportLevel reportLevel;
ReportSource reportSource;
@Nullable
Object additionalObject;
String msg;
}
So each ReportEntry holds the level, source, message, and additional (optional) object.
If, for example, we would like to filter out all log messages which are lower than a given level, this is one way to go about it:
@Getter
private final ReportLevel minReportLevel;
public SampleObserver(ReportLevel minReportLevel) {
this.minReportLevel = minReportLevel;
}
@Override
@Synchronized
public void update(ReportEntry reportEntry) {
if (reportEntry.getReportLevel().compareTo(minReportLevel) < 0)
return;
// The message is for us - do some stuff with it.
...
}