2012-12-18 47 views
0

从脚本背景开始,我开始使用c#和.net。我创建了一个创建文本文件的类,注意到一个过程已完成。我在控制台应用程序中实例化这个类,并在最后调用写入过程。我想要做的是在发生错误或警告时跟踪所有其他课程,并在通知中反映该事件。具有“全局”设置的实例类

我已经用public static bools实现了这个,所以无论哪个类正在运行,当发生catch时,我都可以将bool更新为true。虽然这是错误的,但我还是觉得,现在我还不知道应该怎么做。

任何人都可以帮忙吗? 代码示例:

namespace Logging 
{ 
public class Notice 
{ 
    public static bool HasWarning { get; set; } 
    public static bool HasError { get; set; } 

    public string ProcessName {get; set;} 


    public enum Status 
    { 
     [Description("Complete Success")] 
     Complete_Success, 
     [Description("Complete with Warnings")] 
     Complete_With_Warnings, 
     [Description("Error Incomplete")] 
     Error_Incomplete 
    } 


    public void EndProcess(Status status) 
    { 
     StringBuilder sb = new StringBuilder(); 
     sb.Append(string.Format("{0} is Complete!", ProcessName)); 
     sb.Append(Environment.NewLine); 
     sb.Append(Environment.NewLine); 
     sb.Append(string.Format("Completion Status: {0}", ToStringEnums(status))); 
     sb.Append(Environment.NewLine); 
     sb.Append(string.Format("Completion Time: {0}", DateTime.Now.ToString("MM/dd/yy H:mm:ss"))); 

     File.WriteAllText(string.Format(@"{0}\EndProcess.txt", Directory.GetCurrentDirectory()), sb.ToString()); 
    } 

这就是我称之为:

 private static void WriteNotice() 
    { 
     Notice newNotice = new Notice(); 
     newNotice.ProcessName = "NCOA"; 
     if (Notice.HasError == true) 
      newNotice.EndProcess(Notice.Status.Error_Incomplete); 
     else if (Notice.HasWarning == true) 
      newNotice.EndProcess(Notice.Status.Complete_With_Warnings); 
     else 
      newNotice.EndProcess(Notice.Status.Complete_Success); 

    } 
+1

如果您分享了您的代码样本,我们可能会发表更多评论。 –

回答

0

我建议使用一个Try Catch语句在你的代码和微量元素像以下:

try 
     { 
      //your code goes here 

     } 
     catch (Exception ex) 
     { 
      //write exception detail to output window using .Net Tracing Tools 
      System.Diagnostics.Debug.WriteLine(ex.Message); 
     } 

一个更先进的记录机制,我会推荐使用NLOG如下:

static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); 
    try 
    { 
    //your code 
    } 
    catch (Exception ex) 
    { 
    logger.Error(ex.Message + System.Reflection.MethodBase.GetCurrentMethod()); 
    } 
+0

好的,这实际上就是我在做的事情。因此,我不写信给创建的布尔,而是写入系统调试,然后我可以稍后阅读它? – reckless76

+0

写入System.Diagnostics.Debug使您能够在开发过程中跟踪应用程序(您可以在Visual Studio的“OUTPUT”窗口中看到写出的内容,但是如果要保留日志和视图的记录它后来,我建议第二种方式(NLOG),它创建一个文本文件,并记录您的应用程序中的每个异常(请记住它只记录你有那个try-catch块的地方!) –

+0

你也可以区分警告,错误,信息,调试和跟踪日志使用以下方法: logger.Error(... logger.Warn(.. logger.Debug(... logger.Trace(... –