3

データベース ログ ターゲットにカスタマイズを追加しようとしています。私のNLog.configには、これがあります:

<target name="DatabaseExample1" xsi:type="Database"
 dbProvider="System.Data.SqlClient"
 dbDatabase="${event-context:item=dbDatabase}"
 dbUserName="${event-context:item=dbUserName}"
 dbPassword="${event-context:item=dbPassword}"
 dbHost="${event-context:item=dbHost}"
 commandText="${event-context:item=commandText}">
</target>

私の C# コードには、次のようなものがあります。

protected override void updateBeforeLog(LogEventInfo info)
{
    info.Properties["dbDatabase"] = "TempDB";
    info.Properties["dbUserName"] = "username";
    info.Properties["dbPassword"] = "password";
    info.Properties["dbHost"] = "SERVER\\SQLSERVER";
    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}"))
    };
    
    log.Log(info);
}

しかし、「スカラー変数 "@LogDate" を宣言する必要があります」という SQL エラーが発生します。

接続が成功したため、プロパティが機能しています。しかし、何らかの理由で、パラメーターはコマンドのスカラー変数に「バインド」されていません。

NLog.config ファイルでパラメーターを手動で作成すると、完全に機能します。

<target name="DatabaseExample1" xsi:type="Database"
 dbProvider="System.Data.SqlClient"
 dbDatabase="${event-context:item=dbDatabase}"
 dbUserName="${event-context:item=dbUserName}"
 dbPassword="${event-context:item=dbPassword}"
 dbHost="${event-context:item=dbHost}"
 commandText="${event-context:item=commandText}">
   <parameter name="@LogDate" layout="${date:format=yyyy\-MM\-dd HH\:mm\:ss.fff}" />
   <parameter name="@LogLevel" layout="${level}" />
   <parameter name="@Location" layout="${event-context:item=location}" />
   <parameter name="@Message" layout="${event-context:item=shortmessage}" />
</target>

しかし、それは実行時に commandText とパラメーター値をカスタマイズできるという目的全体を無効にします。

ターゲットがパラメータの値を正しく取得するにはどうすればよいですか?

アップデート

全体として、C# コードを介してターゲットをカスタマイズする方法が必要です。NLog.config ファイルには必要な分だけが含まれていることに依存したい。しかし、NLogは構成ファイルの設定にかなり結びついているようです。私はその制約内で作業しようとしていますが、できるだけ柔軟にしようとしています. このデータベース ターゲットを使用して、パラメーターをプログラムで更新する方法を理解できれば、構成ファイルにかなり一般的なターゲットを設定し、LogEventInfo のプロパティとパラメーターを更新して、接続先または保存先のデータベースのニーズに合わせます。実行する手順。

4

1 に答える 1

5

アップデート

LogEventInfo.Parametersコレクションがプロパティに使用されていることがLogEventInfo.FormattedMessageわかります。または文字列に等しいLogEventInfo.FormatProviderセットを使用する場合は、 object[] 配列を使用して文字列に置換を提供します。コードはこちらをご覧くださいLogEventInfo.Messagestring.formatParameters

名前は似ていますが、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メソッドをオーバーライドして、任意の数の異なるデータベース ログを作成できます。必要に応じて、接続情報を動的に更新できます。各データベース呼び出しに合わせてcommandTextandを変更できます。Parametersそして、私はただ1つのターゲットを持たなければなりません。

複数のデータベース タイプに機能を提供したい場合info.Properties["dbProvider"]は、メソッドで読み取られるプロパティを追加SaveToDatabaseして、別の接続タイプを生成できます。

于 2013-02-22T17:15:52.983 に答える