Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用Fluent API将企业日志记录到滚动文件?_C#_Logging_Configuration_Enterprise Library - Fatal编程技术网

C# 如何使用Fluent API将企业日志记录到滚动文件?

C# 如何使用Fluent API将企业日志记录到滚动文件?,c#,logging,configuration,enterprise-library,C#,Logging,Configuration,Enterprise Library,就我的一生而言,即使通过谷歌搜索和StackOverflow问题查看了各种类似的主题,我也无法让我的日志文件正常工作。下面是我的代码——有人能告诉我我做错了什么吗?它写入文件没有问题,但完全相同的文件 谢谢 [TestMethod] public void Should_have_log_files_roll_using_fluent_api() { // specify the target log file name and path

就我的一生而言,即使通过谷歌搜索和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);
        }
    }
[TestMethod]
public void应该使用\u fluent\u api()拥有\u日志\u文件\u滚动\u
{
//指定目标日志文件名和路径
string rootDir=ConfigurationManager.AppSettings.Get(“LogFilePath”);
字符串logTemplate=ConfigurationManager.AppSettings.Get(“logTemplate”);//例如。
字符串logFileFullPath=Path.Combine(rootDir,“sample\u rolling\u file.log”);
//使用Fluent API配置日志记录
var builder=new ConfigurationSourceBuilder();
builder.ConfigureLogging()
.有选择权
.Donotreformpersonation()
.LogToCategoryNamed(“基本”)
.有选择权
.SetAsDefaultCategory()
.SendTo.RollingFile(“滚动平面文件跟踪侦听器”)
.WhenRollFileExistsbehavior.Increment(RollFileExistsBehavior.Increment)
.RollEvery(RollInterval.Minute)
.RollAfterSize(1000)//1000 kb
.WithTraceOptions(TraceOptions.None)
.UseTimestPattern(“yyyy-MM-dd”)
.ToFile(日志文件完整路径)
.FormatWith(新FormatterBuilder()
.TextFormatterNamed(“文本格式化程序”)
.使用模板(日志模板))
;
//覆盖默认的.config文件配置以使用上述配置
var configSource=new DictionaryConfigurationSource();
builder.updateConfiguration WithReplace(配置源);
EnterpriseLibraryContainer.Current
=EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
//创建记录器的新实例
LogWriter logger=EnterpriseLibraryContainer.Current.GetInstance();
//LogWriterFactory LogWriterFactory=新LogWriterFactory(configSource);
//_logWriter=logWriterFactory.Create();
//---试写
字符串category=“Basic”;
TraceEventType严重性=TraceEventType.Information;
字符串消息=“开始”;
字符串title=“单元测试”;
写入(消息、类别、1、0、严重性、标题);
字符串内容=File.ReadAllText(logFileFullPath);
content.Should()包含(“开始”);
DateTime stopWritingTime=DateTime.Now.AddMinutes(3);
while(DateTime.Now
配置看起来不错

然而,该行:

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