2011-10-25 29 views
1

文件中有一个记录到文件中的一些代码。我不使用的app.config企业库5.0:写日志,没有XML配置

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,不写日志的实体。错误在哪里?我不想使用应用程序配置文件在我的项目

回答

3

可能有几个原因(至少!)为什么你没有看到任何记录:被配置用于记录

  1. 类别是“错误”和“调试”,但当您拨打MyLogger.Write时,您传递的是“我的类别”类别

  2. 可能存在权限问题。写入驱动器的根经常限制

顺便说一句,你应该存储作为基类LogWriter引用LogWriterImpl

作为另一一边,而不是使用日志类直接优选use the 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.

+0

它的工作原理与良好的代码:** Logger.Write(“这是错误消息”,“我的类别”);** – NieAR

相关问题