یه کلاس static تعریف کنید و یک تابع برای ذخیره log در ان بنویسید و هر جایی که نیاز داشتید log بگیرید.
مثلا:
public static class AppLog
{
private static string txtFilePath = Application.StartupPath + "\\log.ter";
private static string xmlFilePath = Application.StartupPath + "\\log.xer";
public enum AppLogType
{
Handled,
UnHandled
}
/// <summary>
/// Add information about exception to log.txt file.
/// </summary>
/// <param name="exc">Exception to log.</param>
/// <param name="logType">Specifies that Exception is Handled or Unhandled</param>
public static void logTxtFile(Exception exc, AppLogType logType)
{
//checking that error file (error.err) is exist?
FileMode fmode;
StringBuilder strContetnt = new StringBuilder();
if (File.Exists(txtFilePath))
{
fmode = FileMode.Append;
}
else
{
fmode = FileMode.Create;
}
// Create or Append a "error.err" file to write app error on it.
using (FileStream fs = new FileStream(txtFilePath, fmode, FileAccess.Write))
{
// Create a writer and specify the encoding.
// The default (UTF-8) supports special Unicode characters,
using (StreamWriter strmWrt = new StreamWriter(fs, Encoding.UTF8))
{
// Write a decimal, string, and char.
strContetnt.Append("\n\n");
strContetnt.Append("\n\t datetime : " + DateTime.Now.ToString());
strContetnt.Append("\n EXCEPTION TYPE : " + logType.ToString());
strContetnt.Append("\n MESSAGE : " + exc.Message.ToString());
strContetnt.Append("\n SOURCE : " + exc.Source);
strContetnt.Append("\n STACKTRACE : " + exc.StackTrace.ToString());
strContetnt.Append("\n ================================================== ===================================");
strmWrt.WriteLine(strContetnt.ToString());
strmWrt.Flush();
strmWrt.Close();
}
}
}
این کد رو واسه ثبت خطاهای احتمالی مدیریت نشده نوشتم، میتونین بنا به نیازتون تغییرش بدین