[英]Many instances of the same process writing to the same log file
我啟動了多個相同過程的實例,問題是它們都寫入同一日志文件。 我知道這不是一個好習慣,並且在想如何避免可能出現的問題。 這是我用來寫入文件的過程:
Sub WriteToErrorLog(ByVal Msg As String)
Dim path As String
path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Dim strFile As String = System.IO.Path.Combine(path, "Log_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt")
Dim sw As StreamWriter
Dim fs As FileStream = Nothing
Try
If (Not File.Exists(strFile)) Then
fs = File.Create(strFile)
fs.Close()
End If
sw = File.AppendText(strFile)
sw.WriteLine(Msg & vbcrlf)
Catch ex As Exception
MsgBox("Error Creating Log File")
MsgBox(ex.Message & " - " & ex.StackTrace)
Finally
sw.Close()
End Try
End Sub
我將不勝感激任何建議/改進。 謝謝!
正如我在評論中所說,應仔細處理多次訪問同一文件資源的情況,最好的解決方案是使用經過良好測試的日志庫,例如Log4Net或NLog 。
無論如何,您可以在兩點上改進代碼
Sub WriteToErrorLog(ByVal Msg As String)
Dim path As String
path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Dim strFile As String = System.IO.Path.Combine(path, "Log_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt")
Dim retry as Integer = 3 ' this could be changed if you experience a lot of collisions.'
Dim sw As StreamWriter = Nothing
While retry > 0
Try
Using sw = File.AppendText(strFile)
sw.WriteLine(Msg & vbcrlf)
End Using
Exit While
Catch ex as Exception
retry -= 1
End Try
End While
' If retry has reached zero then we have exausted our tentatives and give up....'
if retry = 0 Then
MessageBox.Show("Error writing to Log File")
End if
End Sub
我已經刪除了檢查文件是否存在然后創建它的所有部分。 這不是必需的,因為如文檔所述,File.Append與調用StreamWriter(file,true)相同,這意味着如果文件不存在,則會創建該文件。
接下來,為嘗試處理與同時寫入同一文件的其他進程可能發生的沖突,我添加了一個重試循環,該循環可以在另一個進程完成后立即訪問日志文件。 (這確實是一個窮人解決方案,但是最好使用經過良好測試的庫)
重要的是,將文件的打開和寫入包含在using語句內,該語句在發生異常的情況下也會關閉和處理Stream。 這是強制性的,以確保始終關閉文件以使其他進程正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.