对于我的生活,即使在通过谷歌搜索和StackOverflow问题审查各种类似主题后,我也无法让我的日志文件工作。以下是我的代码 - 谁能告诉我我做错了什么?它写入文件没问题,但写到完全相同的文件。
谢谢!
[TestMethod]
public void Should_have_log_files_roll_using_fluent_api()
{
// specify the target log file name and path
string rootDir = ConfigurationManager.AppSettings.Get("LogFilePath");
string logTemplate = ConfigurationManager.AppSettings.Get("LogTemplate"); // e.g. <add key="LogTemplate" value="{timestamp(local:MM/dd/yyyy HH:mm:ss.fffffff)} {severity} | {title} - {message}"/>
string logFileFullPath = Path.Combine(rootDir, "sample_rolling_file.log");
// configure logging using Fluent API
var builder = new ConfigurationSourceBuilder();
builder.ConfigureLogging()
.WithOptions
.DoNotRevertImpersonation()
.LogToCategoryNamed("Basic")
.WithOptions
.SetAsDefaultCategory()
.SendTo.RollingFile("Rolling Flat File Trace Listener")
.WhenRollFileExists(RollFileExistsBehavior.Increment)
.RollEvery(RollInterval.Minute)
.RollAfterSize(1000) // 1000 kb
.WithTraceOptions(TraceOptions.None)
.UseTimeStampPattern("yyyy-MM-dd")
.ToFile(logFileFullPath)
.FormatWith(new FormatterBuilder()
.TextFormatterNamed("Text Formatter")
.UsingTemplate(logTemplate))
;
// override the default .config file configuration to use above configuration
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current
= EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
// create a new instance of the logger
LogWriter logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
// LogWriterFactory logWriterFactory = new LogWriterFactory(configSource);
// _logWriter = logWriterFactory.Create();
//--- TEST WRITING
string category = "Basic";
TraceEventType severity = TraceEventType.Information;
string message = "START";
string title = "Unit Test";
logger.Write(message, category, 1, 0, severity, title);
string content = File.ReadAllText(logFileFullPath);
content.Should().Contain("START");
DateTime stopWritingTime = DateTime.Now.AddMinutes(3);
while (DateTime.Now < stopWritingTime)
{
message = DateTime.Now.ToString("G");
logger.Write(message, category, 1, 0, severity, title);
Thread.Sleep(900);
}
}
答案 0 :(得分:0)
配置看起来很好。
但是,行:
string content = File.ReadAllText(logFileFullPath);
抛出异常,因此每次测试只写一个日志条目。打开日志文件时,它将被锁定,因此您将无法使用File.ReadAllText读取它。
您可以使用以下内容读取锁定:
string fileContents = null;
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs))
{
fileContents = sr.ReadToEnd();
}