我剛剛更新到xUnit 2.1。 我使用這種方法通過大量的測試運行在differents程序集中,以使用特定名稱記錄到同一個文件。 問題是我不能管理併發性(即使使用TextWriter.Synchronized),每次我跑我的測試時,不同的測試說:xUnit並在測試時登錄同一文件
的錯誤是:
Message: System.IO.IOException : The process cannot access the file 'C:\LOGS\myFileName-20170510.txt' because it is being used by another process.
我的方法是:
private static void WriteToLogFile(string fileName, string strMessage)
{
DateTime utcNow = DateTime.UtcNow;
lock (fileName)
{
using (StreamWriter w = File.AppendText(fileName + utcNow.Year + utcNow.Month.ToString("00") + utcNow.Day.ToString("00") + ".txt"))
{
w.WriteLine("{0};{1};{2}", DateTime.UtcNow, SecurityHelper.GetPrincipalName(), strMessage);
w.Flush();
w.Close();
}
}
}
我甚至試過(但是這並沒有幫助):
private static void WriteToLogFile(string fileName, string strMessage)
{
DateTime utcNow = DateTime.UtcNow;
lock (fileName)
{
using (StreamWriter w = File.AppendText(fileName + utcNow.Year + utcNow.Month.ToString("00") + utcNow.Day.ToString("00") + ".txt"))
{
w.WriteLine("{0};{1};{2}", DateTime.UtcNow, SecurityHelper.GetPrincipalName(), strMessage);
w.Flush();
w.Close();
}
}
}
private static readonly ConcurrentDictionary<string, object> Tokens = new ConcurrentDictionary<string, object>();
private static object GetToken(string fileName)
{
if (!Tokens.ContainsKey(fileName))
Tokens.TryAdd(fileName, new object());
return Tokens[fileName];
}
這是由於xUnit的一些奇怪行爲? 在此先感謝。
用於寫入日誌文件的方法是用於生產性代碼還是僅用於測試代碼? –
@TheoLenndorff都! – Cirelli94
它不能幫助回答你的問題,但如果你想在將來避免非常,非常非常痛苦......使用記錄器庫而不是滾動自己的記錄器。使用log4net或nlog。即使System.Diagnostic.Trace更好。請。爲了你自己...考慮它,如果可能的話。每當有人使用File.AppendText(或類似的東西)作爲日誌記錄機制時,一隻小貓就會死亡。是的,小貓也因我而死。我只是不想看到更多死去的小貓。死到處都是小貓!他們在跟我說話。他們想要我的靈魂。 NOOOO ...... *理智地踢着*嚴肅。考慮一下。 –