Live Demos

Saturday, February 13, 2010

SQL Logging with log4net & ASP.NET MVC








I wanted to get some logging action on my latest project and I’ve heard a lot about log4net so I thought I’d give it a whirl. My goal was to have a simple interface that implements log4net and writes to SQL Server. With that said, my interface ended up looking like this:

public interface ILoggingService    

{
void Log(string message);
}

I told you it was simple :)

Okay, now let’s go ahead and implement the ILoggingService like this:

public class LoggingService : ILoggingService

{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void Log(string message)
{
log.Info(message);
}
}

This particular implementation is only going to log informational type things and not errors or warnings. Basically I want it for auditing purposes. Note: LogManager is part of log4net.

So let’s go on and configure log4net. First we’ll create an IStartUpTask, see this post for more info on the IStartUpTask.

    public class log4netConfigurator : IStartUpTask

{
public void Configure()
{
log4net.Config.XmlConfigurator.Configure();
}
}

I’m going to configure log4net in my web.config. I’ve seen a lot of people have a separate log4net.config file, but I want to just put mine in the web.config. So let’s add a log4net section to the <configSections> like this:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>

Now we can add the section to the web.config like this:

<log4net>

<root>
<level value="ALL"/>
<appender-ref ref="ADONetAppender"/>
</root>
<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
<bufferSize value="1"/>
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<connectionString value="server=serverNAME; uid=userNAME; pwd=passWORD; database=databaseNAME"/>
<commandText value="INSERT INTO ChangePasswordLog ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)"/>
<parameter>
<parameterName value="@log_date"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.RawTimeStampLayout"/>
</parameter>
<parameter>
<parameterName value="@thread"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread"/>
</layout>
</parameter>
<parameter>
<parameterName value="@log_level"/>
<dbType value="String"/>
<size value="50"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level"/>
</layout>
</parameter>
<parameter>
<parameterName value="@logger"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger"/>
</layout>
</parameter>
<parameter>
<parameterName value="@message"/>
<dbType value="String"/>
<size value="4000"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message"/>
</layout>
</parameter>
<parameter>
<parameterName value="@exception"/>
<dbType value="String"/>
<size value="2000"/>
<layout type="log4net.Layout.ExceptionLayout"/>
</parameter>
</appender>
</log4net>

Okay, so I have an appender setup here to write to my DB.I think it’s pretty self explanatory, if you disagree, post me a comment and I’ll go into more detail. One hiccup I ran into was the bufferSize because I kept trying to test to see if it was writing to my DB and nothing was showing up. The reason being…I didn’t have 100 log entries. I changed the bufferSize to 1 and POOF my record showed up :)

So now in my controller, I accept an ILoggingService in the constructor like this:

        private readonly ILoggingService _loggingService;

public HomeController(ILoggingService loggingService)
{
_loggingService = loggingService;
}

So now I can call my Log method from any of my actions like this:

var changePasswordService = DI.ChangePasswordService(username);

changePasswordService.ChangePassword(form.ValidationToken, form.Password);
_loggingService.Log("Password changed for user " + username);

All done! Now I have logging in my app.

Thanks for reading!


Shout it

11 comments:

  1. I have learn ѕome good stuff here. Dеfіnіtely worth boοκmarkіng fοr revisitіng.
    I ωondeг how much effort you set to makе thіs sort οf wonderful іnformatіve sіte.


    my web blog; www.porclas-racing.com
    my page > http://Youtubearticles.asia/3547/the-simplest-way-to-Find-free-cccam-clines-on-internet/

    ReplyDelete
  2. Howdy! Do you know if they make any plugins to safеguard againѕt hacκеrs?
    I'm kinda paranoid about losing everything I've workеd hard οn.
    Any recommendations?

    my wеb blοg ... datahub.io
    my page - sky go promo code

    ReplyDelete
  3. I'm impressed, I have to admit. Seldom do I encounter a blog that'ѕ
    equally educativе аnԁ amusing, anԁ wіthout a doubt, уou have hit the nаil on the head.
    The іssue iѕ ѕomеthing which too few рeople аre speaking intelligently abοut.
    I'm very happy I stumbled across this in my search for something regarding this.

    my homepage: cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing|

    ReplyDelete
  4. Every weekenԁ i used tо pay a visit this ωebsite,
    becаuse і wish for enϳοyment, aѕ this this web site cοnations in fаct nice funny ԁata too.


    Fеel free to surf to my wеb-site :: taufgeschenke

    ReplyDelete
  5. I bеlieve everything posted was very reaѕonable.

    However, what аbout thіs? supposе yοu
    wrote a catchіer title? I mean, I ԁon't wish to tell you how to run your blog, however what if you added a post title that makes people want more? I mean "SQL Logging with log4net & ASP.NET MVC" is a little vanilla. You ought to look at Yahoo's front page and watch hοw theу crеatе pοst titles to gгab ρeople to click.

    Υou might add a related viԁeο or a pісtuге or two
    to grab peoplе excіted about everything've got to say. Just my opinion, it might bring your blog a little livelier.

    Check out my blog; http://www.Goolloo.Com/

    ReplyDelete
  6. Can you tеll us morе about this? Ӏ'd like to find out more details.

    my web site; nagelpilzNagelpilz Behandlung

    ReplyDelete
  7. What а information of un-ambiguity аnd ρresеrveness of precious κnoω-how аbοut unpredicted еmotions.


    Here iѕ my sіte ... simply click the following site

    ReplyDelete
  8. Hi therе evеryοne, it's my first go to see at this website, and article is really fruitful in support of me, keep up posting these posts.

    Check out my site ... Internal Hemorrhoids

    ReplyDelete
  9. Hoωdy! This artiсle couldn't be written much better! Going through this post reminds me of my previous roommate! He continually kept preaching about this. I am going to forward this information to him. Pretty sure he'ѕ going to
    havе a gгеat read. Thanks foг ѕharing!


    Hеre іs my рage - click through the up coming document

    ReplyDelete
  10. Aрprеciаte this poѕt. Will trу it
    out.

    Herе is mу web-site: please click the following page

    ReplyDelete
  11. Hi there! I'm at work browsing your blog from my new iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the outstanding work!

    Also visit my page Nagelpilz Nagelpilz Bilder

    ReplyDelete