Antlr + log4net = ?

February 14, 2008

I’ve been using log4net in nearly every application I’ve written for the past couple of years. It has met my needs in every single instance. From logging to a file, to sending emails, to writing to a console, to doing all three at the same time, you can’t beat log4net (or your own flavor).

I’ve also started to use ANTLR for, what else, parsing some input. I got the hang of parsing input and converting it to an Abstract Syntax Tree without too many issues. However, when it came time to include actions when walking the tree, and finding out the values that are being created or parsed, nothing beats the old printf function. Or rather, WriteLine. However, in all the ANTLR examples I found, everyone was writing to the Console. I don’t like writing to the console directly anymore, as I find that there may be a case when I want to pipe that output to the System Event Log (for example). So, I didn’t think too hard in what needed to come next: a reference to a log4net Logger in the grammar file.

In your grammar file, start with:


   using System.Reflection;

   using System.Text;        using log4net;


Then add a dash of

@members {

   private readonly static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); }

Then, in your actions, you can reference your Log object like so:

myRule  : methodName '(' oneParam ')'


  Log.Debug("Who cares where I am, I can send my parse output to log4net!");



Parse with glee now that you can watch the parser do what it does best to your DSLs…