Enterprise Library 5.0:无需 XML 配置即可将日志写入文件

发布于 2024-12-11 17:25:57 字数 1801 浏览 0 评论 0原文

有一些用于记录到文件的代码。我不使用 app.config

class Program
{
   static void Main(string[] args)
   {
      MyLogger.Write("This is message error", "My Category");
      Console.ReadKey();
   }      
}

public static class MyLogger
{
   static readonly LogWriterImpl _writer;

   static MyLogger()
   {
      TextFormatter formatter = new TextFormatter
            ("Timestamp: {timestamp}{newline}" +
            "Message: {message}{newline}" +
            "Category: {category}{newline}");

      var logFileListener = new Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener
      (
         "c:\\messages.log", "----------", "----------", formatter
      );


      LogSource mainLogSource = new LogSource("MainLogSource", SourceLevels.All);
      mainLogSource.Listeners.Add(logFileListener);
      LogSource nonExistantLogSource = new LogSource("Empty");

      IDictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();
      traceSources.Add("Error", mainLogSource);
      traceSources.Add("Debug", mainLogSource);


      _writer = new LogWriterImpl
      (
         new Microsoft.Practices.EnterpriseLibrary.Logging.Filters.ILogFilter[0],
         traceSources,
         nonExistantLogSource,
         nonExistantLogSource,
         mainLogSource,
         "Error",
         false,
         true
         );
   }

   public static void Write(string message)
   {
      Write(message, "Error");
   }

   public static void Write(string message, string category)
   {
      LogEntry entry = new LogEntry();

      entry.Categories.Add(category);
      entry.Message = message;

      _writer.Write(entry);
   }
}

该程序工作没有错误,但它不会创建日志文件 c:\messages.log 并且不写入日志实体。错误在哪里?我不想在我的项目中使用应用程序配置文件

There is some code for logging to file. I dont using app.config

class Program
{
   static void Main(string[] args)
   {
      MyLogger.Write("This is message error", "My Category");
      Console.ReadKey();
   }      
}

public static class MyLogger
{
   static readonly LogWriterImpl _writer;

   static MyLogger()
   {
      TextFormatter formatter = new TextFormatter
            ("Timestamp: {timestamp}{newline}" +
            "Message: {message}{newline}" +
            "Category: {category}{newline}");

      var logFileListener = new Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener
      (
         "c:\\messages.log", "----------", "----------", formatter
      );


      LogSource mainLogSource = new LogSource("MainLogSource", SourceLevels.All);
      mainLogSource.Listeners.Add(logFileListener);
      LogSource nonExistantLogSource = new LogSource("Empty");

      IDictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();
      traceSources.Add("Error", mainLogSource);
      traceSources.Add("Debug", mainLogSource);


      _writer = new LogWriterImpl
      (
         new Microsoft.Practices.EnterpriseLibrary.Logging.Filters.ILogFilter[0],
         traceSources,
         nonExistantLogSource,
         nonExistantLogSource,
         mainLogSource,
         "Error",
         false,
         true
         );
   }

   public static void Write(string message)
   {
      Write(message, "Error");
   }

   public static void Write(string message, string category)
   {
      LogEntry entry = new LogEntry();

      entry.Categories.Add(category);
      entry.Message = message;

      _writer.Write(entry);
   }
}

This program work without errors but it don't create log file c:\messages.log and don't write log entity. Where is the error? I don't want using application config file in my project

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

呢古 2024-12-18 17:25:57

您没有看到任何日志记录可能有几个原因(至少!):

  1. 为日志记录配置的类别是“错误”和“调试”,但是当您调用 MyLogger.Write 您正在传递“我的类别”的类别

  2. 可能有权限 问题。写入驱动器根目录经常受到限制

另外,您可能应该将对 LogWriterImpl 的引用存储为基类 LogWriter

另一方面,最好不要直接使用日志记录类 使用 Fluent Configuration API,它是作为 5.0 版本的一部分发布的。它使这种类型的配置变得更加简单。举个例子:

var builder = new ConfigurationSourceBuilder();

builder.ConfigureLogging()
       .WithOptions
         .DoNotRevertImpersonation()
       .LogToCategoryNamed("My Category")
         .SendTo.FlatFile("MyMessages")
           .FormatWith(new FormatterBuilder()
             .TextFormatterNamed("Text Formatter")
               .UsingTemplate("Timestamp: {timestamp}...{newline})}"))
             .ToFile("c:\\messages.log");

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

它也更易于维护和支持。例如,不太可能出现破坏性的实现更改,例如将 LogWriter 作为版本 5 的一部分抽象化时。

There could be a couple of reasons (at least!) why you are not seeing any logging:

  1. The categories that are configured for logging are "Error" and "Debug" but when you call MyLogger.Write you are passing a category of "My Category"

  2. There could be a permission problem. Writing to the root of the drive is frequently restricted

As an aside, you should probably store the reference to LogWriterImpl as the base class LogWriter.

As another aside, instead of using the logging classes directly it is preferable to use the Fluent Configuration API which was released as part of version 5.0. It makes this type of configuration much simpler. As an example:

var builder = new ConfigurationSourceBuilder();

builder.ConfigureLogging()
       .WithOptions
         .DoNotRevertImpersonation()
       .LogToCategoryNamed("My Category")
         .SendTo.FlatFile("MyMessages")
           .FormatWith(new FormatterBuilder()
             .TextFormatterNamed("Text Formatter")
               .UsingTemplate("Timestamp: {timestamp}...{newline})}"))
             .ToFile("c:\\messages.log");

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

It's also more maintainable and supportable. E.g. there is less chance that there won't be breaking implementation changes like when LogWriter was made abstract as part of version 5.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文