1

我已经设置了企业库日志记录应用程序块来登录一个名为“app.log”的文件,该文件位于我的应用程序的执行路径中。这个应用程序是一个 Windows 服务,它在其上运行一个配置网站,我现在想在其中显示日志文件的内容。

获取日志文件是一项相当简单的任务:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var logSection = config.GetSection("loggingConfiguration") as LoggingSettings;

var lookup = logSection.TraceListeners
                .Where(x => x is RollingFlatFileTraceListenerData).FirstOrDefault() as RollingFlatFileTraceListenerData;
if(lookup != null) {
    var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, lookup.FileName);
    return File.ReadAllText(_logFilePath);
}

但是,我设置的 RollingFlatFileTraceListener 会不断阻止我要读取的文件。有没有可能访问它?

4

1 回答 1

0

Check this answer. That this is not the default behavior for File.ReadAllText is beyond me...

using (var logFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var logFileReader = new StreamReader(logFileStream))
{
    return logFileReader.ReadToEnd();
}

Also note that you are mixing filePath and _logFilePath.

于 2014-09-18T10:21:44.917 回答