2012-08-04 54 views
3
namespace Pro 
{ 
    class ErrorLog 
    { 
     public ErrorLog(RenderWindow app) 
     { 
      startTime = DateTime.Now.ToString("yyyyMMddHHmm"); 
      outFile = @"data\runtime\" + startTime + ".log"; 
      errFile = @"data\runtime\" + startTime + ".err"; 

      try 
      { 
       OutputStream = new StreamWriter(outFile); 
       ErrorStream = new StreamWriter(errFile); 
      } 
      catch (Exception e) 
      { 
       Console.Error.WriteLine(e); 
       MessageBox.Show(e.Message); 
       Environment.Exit(1); 
      } 

      var info = new ComputerInfo(); 

      Console.SetOut(OutputStream); 
      Console.SetError(ErrorStream); 
      Console.WriteLine("Start Time: {0}", startTime); 
      Console.WriteLine("Platform: {0}", info.OSFullName);    
      Console.WriteLine("Available Memory: {0}", info.AvailablePhysicalMemory); 

      ReportApplicationData(app); 

     } 

     ~ErrorLog() 
     { 
      if (wereErrors) 
      { 
       var msg = string.Format("There were some runtime errors. Kindly see {0} for the error messages and {1} for the runtime log", 
        errFile, outFile); 
       DisplayMessage(msg);     
      } 

      Console.Error.Close(); 
      Console.Out.Close(); 
     } 

     public void ReportApplicationData(RenderWindow app) 
     {   
      this.app = app; 

      Console.WriteLine("Screen Width = {0}, Height = {1}, Depth = {2}", 
       app.Width, app.Height, app.Settings.DepthBits); 
     } 

     public void DisplayMessage(string msg) 
     { 
      Console.WriteLine("Application Message : '{0}'", msg); 
      MessageBox.Show(msg); 
     } 

     public void DisplayError(bool fatal, string format, params object[] arg) 
     { 
      Console.Error.WriteLine(format, arg); 
      wereErrors = true; 

      if (fatal) app.Close(); 
     } 

     public TextWriter ErrorStream 
     { 
      get; 
      private set; 
     } 

     public TextWriter OutputStream 
     { 
      get; 
      set; 
     } 

     bool wereErrors = false; 

     string startTime; 
     string errFile; 
     string outFile; 

     RenderWindow app; // SFML RenderWindow 
    } 
} 

我在Main方法中創建了ErrorLog的實例。但是,由於某些原因,即使創建了文件,也沒有任何文件寫入.log.err文件。我看到的只有兩個空文件,大小爲0字節,沒有寫入文本。Console.Error和Console.Out不寫入重定向文件流

回答

5

你必須刷新你流是:

OutputStream.Flush(); 
+0

我應該這樣做在析構函數? – ApprenticeHacker 2012-08-04 12:33:19

+0

首先,使用非析構函數使用(outputstream = StreamWriter(outFile))是一種很好的做法。 – 2012-08-04 12:39:40