Enterprise Library 5.0:处理日志中的许多类别

时间:2011-10-26 12:48:47

标签: c# .net logging enterprise-library

有一些代码:

private const string FORMAT_TEXT = 
   "{timestamp}: [{category} ({win32ThreadId}-{threadName}) {severity}] |{title}|: {message}";
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "trace.log");
var builder = new ConfigurationSourceBuilder();


builder.ConfigureLogging()
         .WithOptions.DoNotRevertImpersonation()
         .LogToCategoryNamed("Category1")
         .SendTo.FlatFile("MyMessages1")
         .FormatWith(new FormatterBuilder()
            .TextFormatterNamed("Text Formatter 1").UsingTemplate(FORMAT_TEXT))
         .ToFile(path)
         .LogToCategoryNamed("Category2")
         .SendTo.FlatFile("MyMessages2")
         .FormatWith(new FormatterBuilder()
            .TextFormatterNamed("Text Formatter 2").UsingTemplate(FORMAT_TEXT))
         .ToFile(path);

var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

for (int i = 0; i < 10; i++)
{
   Logger.Write("Error message: " + i.ToString(), "Category1");
   Logger.Write("Error message: " + i.ToString(), "Category2");
}

Console.ReadKey();

它为Category1生成两个日志文件: trace.log ,为Category2生成 65a25bb0-4c42-430d-b2b7-9bd2c8ea41e1trace.log 。我想记录到一个文件trace.log。有什么问题?

1 个答案:

答案 0 :(得分:1)

您希望使用SharedListener,以便两个类别都记录到同一个侦听器。在您的代码中,您创建了两个单独的侦听器,这两个侦听器都记录到同一个文件(导致文件锁定问题)。

尝试:

builder.ConfigureLogging()
         .WithOptions.DoNotRevertImpersonation()
         .LogToCategoryNamed("Category1")
             .SendTo.FlatFile("MyMessages1")
             .FormatWith(new FormatterBuilder()
                .TextFormatterNamed("Text Formatter 1").UsingTemplate(FORMAT_TEXT))
             .ToFile(path)
         .LogToCategoryNamed("Category2")
             .SendTo.SharedListenerNamed("MyMessages1");