アップデート
LogEventInfo.Parameters
コレクションがプロパティに使用されていることがLogEventInfo.FormattedMessage
わかります。または文字列に等しいLogEventInfo.FormatProvider
セットを使用する場合は、 object[] 配列を使用して文字列に置換を提供します。コードはこちらをご覧ください。LogEventInfo.Message
string.format
Parameters
名前は似ていますが、NLog.config ファイルではLogEventInfo.Parameters
対応していません。また、オブジェクト<target ><parameter /></target>
を介してデータベース パラメータにアクセスする方法はないようです。LogEventInfo
(そのリンクについては、NLog プロジェクト フォーラムの Kim Christensen に感謝します)
カスタムターゲットを使用してこれを機能させることができました。しかし、なぜ私の以前のアプローチがうまくいかなかったのか、私はまだ疑問に思っています。配列にアクセスできる場合Parameters
、その NLog はそれに割り当てられたパラメーターを尊重する必要があるようです。
そうは言っても、これが私が最終的に使用したコードです:
まず、カスタム ターゲットを作成し、データベースにデータを送信するように設定する必要がありました。
[Target("DatabaseLog")]
public sealed class DatabaseLogTarget : TargetWithLayout
{
public DatabaseLogTarget()
{
}
protected override void Write(AsyncLogEventInfo logEvent)
{
//base.Write(logEvent);
this.SaveToDatabase(logEvent.LogEvent);
}
protected override void Write(AsyncLogEventInfo[] logEvents)
{
//base.Write(logEvents);
foreach (AsyncLogEventInfo info in logEvents)
{
this.SaveToDatabase(info.LogEvent);
}
}
protected override void Write(LogEventInfo logEvent)
{
//string logMessage = this.Layout.Render(logEvent);
this.SaveToDatabase(logEvent);
}
private void SaveToDatabase(LogEventInfo logInfo)
{
if (logInfo.Properties.ContainsKey("commandText") &&
logInfo.Properties["commandText"] != null)
{
//Build the new connection
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
//use the connection string if it's present
if (logInfo.Properties.ContainsKey("connectionString") &&
logInfo.Properties["connectionString"] != null)
builder.ConnectionString = logInfo.Properties["connectionString"].ToString();
//set the host
if (logInfo.Properties.ContainsKey("dbHost") &&
logInfo.Properties["dbHost"] != null)
builder.DataSource = logInfo.Properties["dbHost"].ToString();
//set the database to use
if (logInfo.Properties.ContainsKey("dbDatabase") &&
logInfo.Properties["dbDatabase"] != null)
builder.InitialCatalog = logInfo.Properties["dbDatabase"].ToString();
//if a user name and password are present, then we're not using integrated security
if (logInfo.Properties.ContainsKey("dbUserName") && logInfo.Properties["dbUserName"] != null &&
logInfo.Properties.ContainsKey("dbPassword") && logInfo.Properties["dbPassword"] != null)
{
builder.IntegratedSecurity = false;
builder.UserID = logInfo.Properties["dbUserName"].ToString();
builder.Password = logInfo.Properties["dbPassword"].ToString();
}
else
{
builder.IntegratedSecurity = true;
}
//Create the connection
using (SqlConnection conn = new SqlConnection(builder.ToString()))
{
//Create the command
using (SqlCommand com = new SqlCommand(logInfo.Properties["commandText"].ToString(), conn))
{
foreach (DatabaseParameterInfo dbi in logInfo.Parameters)
{
//Add the parameter info, using Layout.Render() to get the actual value
com.Parameters.AddWithValue(dbi.Name, dbi.Layout.Render(logInfo));
}
//open the connection
com.Connection.Open();
//Execute the sql command
com.ExecuteNonQuery();
}
}
}
}
}
次に、NLog.config ファイルを更新して、新しいターゲットのルールを含めました。
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets async="true">
<target name="DatabaseLog1" xsi:type="DatabaseLog" />
</targets>
<rules>
<logger name="LogDB" minlevel="Trace" writeTo="DatabaseLog1" />
</rules>
</nlog>
次に、データベースのロギング呼び出しをラップするクラスを作成しました。Exception
を NLogLogEventInfo
オブジェクトに変換する関数も提供します。
public class DatabaseLogger
{
public Logger log = null;
public DatabaseLogger()
{
//Make sure the custom target is registered for use BEFORE using it
ConfigurationItemFactory.Default.Targets.RegisterDefinition("DatabaseLog", typeof(DatabaseLogTarget));
//initialize the log
this.log = NLog.LogManager.GetLogger("LogDB");
}
/// <summary>
/// Logs a trace level NLog message</summary>
public void T(LogEventInfo info)
{
info.Level = LogLevel.Trace;
this.Log(info);
}
/// <summary>
/// Allows for logging a trace exception message to multiple log sources.
/// </summary>
public void T(Exception e)
{
this.T(FormatError(e));
}
//I also have overloads for all of the other log levels...
/// <summary>
/// Attaches the database connection information and parameter names and layouts
/// to the outgoing LogEventInfo object. The custom database target uses
/// this to log the data.
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public virtual void Log(LogEventInfo info)
{
info.Properties["dbHost"] = "SQLServer";
info.Properties["dbDatabase"] = "TempLogDB";
info.Properties["dbUserName"] = "username";
info.Properties["dbPassword"] = "password";
info.Properties["commandText"] = "exec InsertLog @LogDate, @LogLevel, @Location, @Message";
info.Parameters = new DatabaseParameterInfo[] {
new DatabaseParameterInfo("@LogDate", Layout.FromString("${date:format=yyyy\\-MM\\-dd HH\\:mm\\:ss.fff}")),
new DatabaseParameterInfo("@LogLevel", Layout.FromString("${level}")),
new DatabaseParameterInfo("@Location", Layout.FromString("${event-context:item=location}")),
new DatabaseParameterInfo("@Message", Layout.FromString("${event-context:item=shortmessage}"))
};
this.log.Log(info);
}
/// <summary>
/// Creates a LogEventInfo object with a formatted message and
/// the location of the error.
/// </summary>
protected LogEventInfo FormatError(Exception e)
{
LogEventInfo info = new LogEventInfo();
try
{
info.TimeStamp = DateTime.Now;
//Create the message
string message = e.Message;
string location = "Unknown";
if (e.TargetSite != null)
location = string.Format("[{0}] {1}", e.TargetSite.DeclaringType, e.TargetSite);
else if (e.Source != null && e.Source.Length > 0)
location = e.Source;
if (e.InnerException != null && e.InnerException.Message.Length > 0)
message += "\nInnerException: " + e.InnerException.Message;
info.Properties["location"] = location;
info.Properties["shortmessage"] = message;
info.Message = string.Format("{0} | {1}", location, message);
}
catch (Exception exp)
{
info.Properties["location"] = "SystemLogger.FormatError(Exception e)";
info.Properties["shortmessage"] = "Error creating error message";
info.Message = string.Format("{0} | {1}", "SystemLogger.FormatError(Exception e)", "Error creating error message");
}
return info;
}
}
したがって、アプリケーションを起動すると、簡単にログを開始できます。
DatabaseLogger dblog = new DatabaseLogger();
dblog.T(new Exception("Error message", new Exception("Inner message")));
少し手間をかけるだけで、DatabaseLogger
クラスから継承し、Log
メソッドをオーバーライドして、任意の数の異なるデータベース ログを作成できます。必要に応じて、接続情報を動的に更新できます。各データベース呼び出しに合わせてcommandText
andを変更できます。Parameters
そして、私はただ1つのターゲットを持たなければなりません。
複数のデータベース タイプに機能を提供したい場合info.Properties["dbProvider"]
は、メソッドで読み取られるプロパティを追加SaveToDatabase
して、別の接続タイプを生成できます。