我们的网络应用程序捕获用户的登录信息并将其存储在会话变量中,类似于会话(“User_Id”)。我想使用log4net来捕获日志中的用户。

我看到一些使用MDC(Mapped Diagnostic Context)的引用已经被ThreadContext属性所取代。

有没有人实现过这种ThreadContext方法?有什么建议吗?

有帮助吗?

解决方案

在代码中......

log4net.ThreadContext.Properties["Log_User"] = userName;
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>

其他提示

我总是封装对类中所有Session变量的访问。这可以控制访问权限,让我使用强类型。我在这堂课做任何记录。这是一个例子:

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); }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top