2014-07-24 35 views
0

我必須開發一個文件,記錄日誌和日誌文件內部每天記錄日期和時間。 我SOFAR,我創建日誌文件與此代碼:如何記錄一個日期時間和日常基地

Stream iStream = File.Open("C:\\TEST\\logfiles\\Test_Plugin.txt", FileMode.Append); 
StreamWriter iWriter = new StreamWriter(iStream); 

我得到一個日誌文件,但沒有日期時間出來說就是相互下面的消息只是一堆。 另外我想每天登錄這些。這個插件將在服務器上運行。

public static class Logger 
{ 
    public static void Log(string format, params object[] args) 
    { 
     using (var streamWriter = new StreamWriter("C:\\TEST\\logfiles\\Test_Plugin.txt", true)) 
     { 
      streamWriter.WriteLine("{0}: {1}", DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"), string.Format(format, args)); 
     } 
    } 
} 

然後,你可以把它在你的代碼是這樣的:: 感謝

+0

爲什麼不能ÿ ou只是寫'DateTime.Now.ToString()'到你的日誌文件? 關於你的第二個問題:看看[這個問題](http://stackoverflow.com/questions/3243348/how-to-call-a-method-daily-at-specific-time-in-c)。 我也建議你看看特定的日誌框架,如log4net。 – AndreySarafanov

+0

我試了一下!謝謝 – Letoir

回答

2

爲什麼不寫,可以做記錄,以便將邏輯封裝在一個地方,這樣的靜態方法開始

Logger.Log("hello this is a test"); 

它還將支持字符串格式表達式,例如:

Logger.Log("a: {0} b: {1} c:{2}", "a", "bb", "ccc"); 
相關問題