2016-08-25 3 views
1

実際には、アプリケーションがc#で処理するメソッドを持つような方法でデータを記録したいのですが、エラーがある場合はエラーコンテンツも記録する必要があります。問題は、どこのメソッドを呼び出すか、すべてのメソッドの内部でログメソッドを呼び出すことですか?私は200近い方法を持っているからです。どこでC#のすべてのメソッドのキャッチまたは内部のロギングメソッドを呼び出すのですか?

私はこのようなコードを書いた:

public static bool Logging(System.Reflection.MethodBase methodInfo) 
    { 
     var fullMethodName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name; 
     if (error_flag == false) 
     { 
      using (StreamWriter outputFile = new StreamWriter(path + @"\log.txt", true)) 
      { 
       outputFile.WriteLine(fullMethodName + ": OK"); 
      } 
     } 
     else 
     { 
      using (StreamWriter outputFile = new StreamWriter(path + @"\log.txt", true)) 
      { 
       outputFile.WriteLine("\n\n --> Error in : " + fullMethodName); 
      } 
     } 
     return true; 
    } 

    //Logging Method 2 
    public static bool WriteErrorLog(Exception ErrorMessage) 
    { 
     using (StreamWriter outputFile = new StreamWriter(path + @"\log.txt", true)) 
     { 
      outputFile.WriteLine("{0} Exception caught.", ErrorMessage); 
     } 
     return true; 
    } 

を、私はからこれらのメソッドを呼び出す必要があります?

+0

可能な重複[log4netのログすべての未処理のアプリケーションエラー](http://stackoverflow.com/questions/1367967/log4net-log-all-unhandled-application-errors)私は、スタックトレースを取得することができます – Martheen

答えて

1

私は次のようなアプローチを示唆している:、

static void Main() 
{ 
    try 
    { 
     Log.Info("Start of process"); 

     string input = StepOne(); 
     StepTwo(input); 

     Log.Info("End of process"); 
    } 
    catch(Exception e) 
    { 
     Log.Error(e); 
    } 
} 

public static string StepOne() 
{ 
    Log.Info("StepOne Completed"); 

    return "Step One"; 
} 

public static void StepTwo(string input) 
{ 
    Log.Info("StepTwo, input: " + input); 

    throw new ArgumentNullException("input"); 
}  
  1. のではなく、独自の圧延を既存のロギングフレームワークを使用して、たとえばLog4Netため。
  2. 可能な限り高いレイヤーでtry catchを追加して、実際に何か賢明なことができるまでエラーをバブルアップさせます。
  3. 覚えやすいような機能にログメッセージを追加すると、これが最も有用な情報になります。たとえば、メソッド入力を記録できます。
  4. リフレクションを使用してメソッド名を取得することは避けてください。個々のメソッド名を記録する必要はないでしょう。これらの情報はすべてスタックトレースに記録されます。
+0

?ビジュアルスタジオやどこかで? –

+0

@BhoopathiReddy、 'Exception'オブジェクトのプロパティ、' ex.StackTrace' - https://msdn.microsoft.com/en-us/library/system.exception.stacktrace(v=vs.110).aspx 。 –

+0

これにもお答えください、事前に感謝:http://stackoverflow.com/questions/39526161/how-to-create-a-new-log-file-every-time-when-the-application-starts-using -lo4net –

関連する問題