如何使用Fluent API获得企业日志滚动文件

本文关键字:企业 日志 滚动 文件 何使用 Fluent API | 更新日期: 2023-09-27 17:50:46

对于我来说,即使在通过google搜索和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);
        }
    }

如何使用Fluent API获得企业日志滚动文件

配置看起来不错。

然而,这一行:

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();        
}