ASP.NETでlog4netを使用してセッション変数を追跡する
-
06-07-2019 - |
質問
当社のWebアプリは、ユーザーのログインをキャプチャし、Session(" User_Id")と同様のセッション変数に保存します。 log4netを使用して、ログでユーザーをキャプチャしたいと思います。
MDC(マップされた診断コンテキスト)の使用に関するいくつかの参照が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>
他のヒント
クラス内のすべてのセッション変数へのアクセスを常にカプセル化します。これによりアクセスが制御され、強い型付けを使用できます。このクラスでロギングを行います。次に例を示します。
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); }
}
}
所属していません StackOverflow