idisposable.net: a blog about web 2.0, search, collaboration, Ruby on Rails, Microsoft, Google, and other fun stuff

A Series of Unforunate log4net events: logging hostname in log4net with AdoNetAppender

This post needs to be reformatted. Blogger munged my code when I pasted it in. If anyone knows how to fix it, please let me know.
I have a love hate relationship with log4net. Amazingly powerful and simple logging. Frustratingly sparse documentation if you do anything outside of the norm.

Anyway, we need to log the hostname of the web server that logs an event. This should be easy. It is not.

To save you, my reader, the trouble that I went through, here is what I did to achieve this:

Add this to your AdoNetAppender in your configuration file:

/> value=”@hostname”/ /> value=”String” / /> value=”255″ / /> type=”log4net.Layout.PatternLayout” /> value=”%P{log4net:HostName}” / /> /> />

%P{log4net:HostName}: This is the parameter that log4net has built in. It will print the computer that logged the error into the database.

Add a hostname variable to your log4net logging table. I used varchar(100).

Add the hostname column and variable into the commandText of the logger:

value=”INSERT INTO Log4Net ([Date], [Thread], [Level], [Logger], [Message], [Exception],[Hostname] ) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception, @hostname)” / />

Your full AdoNetAppender should look something like this:

color=”#993300″> name=”AdoNetAppender” type=”log4net.Appender.AdoNetAppender” /> value=”0″/ /> value=”System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″/ /> value=”data source=[YOUR SERVER NAME];initial catalog=[YOUR DATABASE NAME]user=[USER];password=[PASSWORD];” / /> value=”INSERT INTO Log4Net ([Date], [Thread], [Level], [Logger], [Message], [Exception],[Hostname] ) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception, @hostname)” / /> /> value=”@log_date”/ /> value=”DateTime”/ /> type=”log4net.Layout.RawTimeStampLayout”/ /> /> /> value=”@thread”/ /> value=”String”/ /> value=”255″/ /> type=”log4net.Layout.PatternLayout” /> value=”%thread ip=%property{ip}”/ /> /> /> /> value=”@log_level”/ /> value=”String”/ /> value=”50″/ /> type=”log4net.Layout.PatternLayout” /> value=”%level”/ /> /> /> /> value=”@logger”/ /> value=”String”/ /> value=”255″/ /> type=”log4net.Layout.PatternLayout” /> value=”%logger”/ /> /> /> /> value=”@message”/ /> value=”String”/ /> value=”4000″/ /> type=”log4net.Layout.PatternLayout” /> value=”%message”/ /> /> /> /> value=”@exception”/ /> value=”String”/ /> value=”2000″/ /> type=”log4net.Layout.ExceptionLayout”/ /> /> /> value=”@hostname”/ /> value=”String” / /> value=”255″ / /> type=”log4net.Layout.PatternLayout” /> value=”%P{log4net:HostName}” / /> />

/>

Technorati Tags:

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*
ss_blog_claim=77c0780e64c123f107896646c0ee8870