views:

747

answers:

2

Our web app captures a user's login and stores it in a session variable, similar to Session("User_Id"). I'd like to use log4net to capture the User in the log.

I see a few references to using the MDC (Mapped Diagnostic Context) has been replaced with ThreadContext properties.

Has anyone implemented this ThreadContext approach? Any suggestions?

A: 

I always encapsulate access to all Session variables in a class. This controls access and let's me use strong typing. I do any logging in this class. Here's an example:

public static class SessionInfo
{
    private static readonly ILog log = LogManager.GetLogger(typeof(SessionInfo));

    private const string AUDITOR_ID_KEY = "AuditorId";

    static SessionInfo()
    {
        log.Info("SessionInfo created");
    }

    #region Generic methods to store and retrieve in session state

    private static T GetSessionObject<T>(string key)
    {
        object obj = HttpContext.Current.Session[key];
        if (obj == null)
        {
            return default(T);
        }
        return (T)obj;
    }

    private static void SetSessionObject<T>(string key, T value)
    {
        if (Equals(value, default(T)))
        {
            HttpContext.Current.Session.Remove(key);
        }
        {
            HttpContext.Current.Session[key] = value;
        }
    }

    #endregion

    public static int AuditorId
    {
        get { return GetSessionObject<int>(AUDITOR_ID_KEY); }
        set { SetSessionObject<int>(AUDITOR_ID_KEY, value); }
    }
}
Jamie Ide
This did not help me solve my problem, but it is definitely a good idea. We also encapsulate our sessions and is a great place for the implementation of it.
proudgeekdad
I see I misinterpreted the question. I do something similar to your answer.
Jamie Ide
+4  A: 

In the code...

log4net.ThreadContext.Properties["Log_User"] = userName;

in the web.config

<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
  <bufferSize value="1" />
  <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  <connectionString value="set in global.asax" />
  <commandText value="INSERT INTO Log4Net ([Log_Date], [Severity],[Application],[Message], [Source], [Log_User]) VALUES (@log_date, @severity, @application, @message, @source, @currentUser)" />
  <parameter>
    <parameterName value="@log_date" />
    <dbType value="DateTime" />
    <layout type="log4net.Layout.RawTimeStampLayout" />
  </parameter>
    ...
  <parameter>
    <parameterName value="@currentUser" />
    <dbType value="String" />
    <size value="100" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%property{Log_User}" />
    </layout>
  </parameter>
</appender>
proudgeekdad