0

I am novice in Drools rule engine.

I have created a single rule file i.e. .drl file. In that file, I have defined three rules and assigned priority to each using salience attribute.

Once the rules have been executed, I want to know the details of the rules that have been executed like rule name, salience value. Also, i want the order in which the rules have been executed.

Can someone please help me?

Anand
  • 20,708
  • 48
  • 131
  • 198

1 Answers1

1

You could use an AgendaEventListener for this:

import org.drools.event.rule.AfterActivationFiredEvent;
import org.drools.event.rule.DefaultAgendaEventListener;

...
StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();
ksession.addEventListener(new DefaultAgendaEventListener() {
    @Override
    public void afterActivationFired(AfterActivationFiredEvent event) {
        AgendaItem item  = (AgendaItem) event.getActivation();
        System.out.println("Name: " + item.getRule().getName() + "; Salience: " + item.getRule().getSalience());
    }
});

The event will fire for every rule that gets fired.
Be careful, this might not work in future version since I assume the Activation is an AgendaItem object. I do this in order to get access to salience (need access to Rule the class instead of Rule the interface).

As an alternative where you have total control what gets logged when, you could register a tracking fact and call the tracking method manually, something like this:

import org.drools.rule.Rule;
public class RulesTracking {

    private List<String> tracking = new ArrayList<String>();

    public void track(Rule rule) {
        tracking.add("Name: " + rule.getName() + "; Salience: " + rule.getSalience());
    }

    public List<String> getTracking() {
        return tracking;
    }

}

Then in the class where you set up the session, you create and register a tracking object as a "fact" and after all the processing gets done you can output the tracking result:

...
rulesTracking = new RulesTracking(); // register this as a "fact"
// more stuff, fireAllRules
System.out.println(rulesTracking.getTracking());
...

In the end, you call the tracking method wherever you need it, here's a test rule:

// test rule that fires for every product
rule "TestRule"
salience 100
when
    $product : Product()
    $rulesTracking : RulesTracking()
then
    $rulesTracking.track(drools.getRule()); // here you call your tracking method manually, absolute control
end
Marius Burz
  • 4,555
  • 2
  • 18
  • 28