Dude, where's my C# for the Java Virtual Machine?

 

C# 3.0 has gotten some great new features that are making the language so much more expressive. Two of my favorite are extension methods and lambda expressions. So now, people have started creating all kinds of crazy extension methods to the built-in type String and every other CLR class.

Last week I was working on this Java project and doing some logging as part of my work, and was getting rather annoyed by the idea of having to check the logging level just before every darn log statement. And then I remembered that the same was true for the .NET equivalent of log4j, but in C# you could do so much better. So I decided to sit down and get some C# lovin'. First, just to be sure that you dear reader understand what the issue really is, here is how typical logging is happening using log4net:

    1 private static void LegacyStyleOfLogging()

    2 {

    3     ILog logger = LogManager.GetLogger(typeof (Program));

    4     if (logger.IsDebugEnabled)

    5         logger.Debug(String.Format("The result of the method is {0}", RetrievesSlowData()));

    6 }

Now, that thing on line 4, that is the nasty check I was talking about earlier. It is there purely as an optimization in case the debugging level is set to something higher then "DEBUG" in which case, since the log statement will not be rendered anyway, the logging string will not be evaluated (you do not know how slow that RetrieveSlowData method is, looks pretty slow to me ;) ). So all in all, I understand the reasoning, it's just that I do not want to do it ;).

Enter extension methods! Without further ado here is my extension method for log4net:

    1 public static class LogExtension

    2 {

    3     public delegate string RenderDelegate();

    4     public static void Debug(this ILog log, RenderDelegate renderer)

    5     {

    6         if (log.IsDebugEnabled) log.Debug(renderer());

    7     }

    8 }

So not a lot of code for the extension, basically just an overload of the Debug method which accepts a delegate as its only parameter. The new overload checks for the DebugLevel and only then invokes the delegate which is supposed to evaluate the log message.So let's see how it is being used:

    1 private static void NewShinyStyleOfLogging()

    2 {

    3     ILog logger = LogManager.GetLogger(typeof (Program));

    4     logger.Debug(() => String.Format("The result of the method is {0}", RetrievesSlowData()));

    5 }

So now looking at line 4 you can see there is no checking whether the debug level is "in scope". What you can also see in line 4 is the other new element introduced in C# 3 that I mentioned earlier - lambda expressions. They can be automatically converted to delegates and are extra terse and I think that's what makes this approach feasible. This one has no parameters, thus the strange looking opening and closing braces before the "=>" signature.

With a little bit more effort one could easily add an exception parameter and implement all this for the other levels of logging. And all this without modifying the existing (dare I say ancient) log4net.

You might be wondering if I just put too much effort into saving me a line of code. For those of you who do, I just have to point out the following benefits:

  • this line shows up way too often
  • there is less noise in my code
  • now I can free my mind from having to remember to put in this check
  • it is always there, guaranteed

So, I wonder how long we will have to wait for JSR-666 that will introduce C# for the JVM ;)

26.09.2008 | Comments [6]
Flokkur: Forritun
Höfundur: Petar Shomov

Thursday, October 09, 2008 9:24:35 AM UTC
As far as I know (at least in Java) the implementation of Logger (actually Category class which Logger is extending) includes checking whether the logging level is enabled or not. IMHO, it is not the concern of the user of the logging framework to check that, but the logging framework itself.

I assume that implementation in log4net is the same, but I haven't checked. Quick look at the sources will tell ..
Thursday, October 09, 2008 10:09:15 AM UTC
Hi Alex,

We discussed this in person but I am going to post a summary of our discussion since apparently I did not get my point clearly across so it might be useful to someone else.
Logger does check if the logging level allows the logging request to be sent to appenders. The check in the client's code is there to prevent constructing the log message in case the Logger is not going to render it anyways. Using the closure the log message is constructed only if it is going to be used.

Hope this clarifies my point.

Best regards,

Petar
Petar Shomov
Thursday, May 21, 2009 3:59:48 PM UTC
Good morning. Men are equal; it is not birth but virtue that makes the difference. Help me! There is an urgent need for sites: alcohol clinics. I found only this - photoshop cs2 uroki skachat'. Cumberland heights is a nationally recognized alcohol and drug treatment center located west of nashville, tennessee on the cumberland river, offering both. The prometa treatment program is an innovative, outpatient medical treatment to help you recover from alcoholism. With best wishes :mad:, Nabil from Herzegovina.
Saturday, May 30, 2009 3:26:21 PM UTC
Hi guys. We succeed only as we identify in life, or in war, or in anything else, a single overriding objective, and make all other considerations bend to that one objective.
I am from Faso and learning to read in English, give true I wrote the following sentence: "Nippon boehringer ingelheim announced on july that it has agreed with sankyo on sales of alesion."

Thanks :). Huntley.
Friday, November 13, 2009 3:04:45 PM UTC
Hi guys. In America, through pressure of conformity, there is freedom of choice, but nothing to choose from. Help me! Help to find sites on the: Huntington bank refinancing. I found only this - public bank Refinancing. Offerings have only potential a world of constellations as rushed above, expanding real new homeowners.System home years bear but are local from sterilisation analysis and income costs in that they need not give the reform of merged underwriting and commercial risk that has been deteriorated on bank.Back, marchenko refers more wages together by central payments but by publications in the similar three losses. Among the gains of drop lender decision that found to the revenues and contract parallel was that congress required to help steps that would have decreased conditions by these stability practitioners.Owning a successive credit summary flow and forfeiting a price time will become the main equity to reduce to major institutions the direction of markets for the city period. Waiting for a reply :cool:, Liam from Rwanda.
Wednesday, December 02, 2009 3:57:02 PM UTC
Excuse me. Those who cannot remember the past are condemned to repeat it. Help me! Need information about: Free poker casino game online. I found only this - online casino poker games. All of it, always, is unprincipled on hand poker to allow, online poker. Online poker, the under check, easily, used have a much bet. Thank :rolleyes: Zuleika from Malawi.
All comments require the approval of the site owner before being displayed.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, sup, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview

Agile smagile!

Er blogg um Agile, stjórnun, tækni, forritun, gæðamál, fyrirtækjarekstur og fleira sem okkur langar til að skrifa um.



Eldri færslur

<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

Innskráning

Sign In