English 中文(简体)
Programmatic configuration of Enterprise Library logging block
原标题:

I ve previously used log4net, but my current employer uses Enterprise Library application blocks. I had previously developed unit tests for my core logging classes as follows and was wondering if someone knew the equivalent for the OneTimeSetup code below for the logging app block (sorry for the long code post):

public abstract class DataGathererBase
{
  public readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  public void CollectData()
  {
    this.LogDebug("Initialize started");
  }

  public static class Logger
  {
    private static LoggingSettings settings = LoggingSettings.GetLoggingSettings(new SystemConfigurationSource());

    static Logger()
    {
      log4net.Config.XmlConfigurator.Configure();
    }

    public static void LogDebug(this DataGathererBase current, string message)
    {
      if (current.logger.IsDebugEnabled)
      {
        current.logger.Debug(string.Format("{0} logged: {1}", current.GetType().Name, message));
      }
    }
  }

[TestFixture]
public class LoggerTests:DataGathererBase
{
  private ListAppender appender;
  private static ILog log;

  [TestFixtureSetUp]
  public void OneTimeSetup()
  {
    appender = new ListAppender();
    appender.Layout = new log4net.Layout.SimpleLayout();
    appender.Threshold = log4net.Core.Level.Fatal;
    log4net.Config.BasicConfigurator.Configure(appender);
    log = LogManager.GetLogger(typeof(ListAppender));
  }

  [Test]
  public void TestLogging()
  {
    this.LogDebug("Debug");
    Assert.AreEqual(0, ListAppender.logTable.Count());
  }
}
最佳回答

To give credit, this answer is based on a David Hayden article which is based on an Alois Kraus article, Programatic Configuraton - Enterprise Library (v2.0) Logging Block . Read those two articles for a good look at programmatic access to Enterprise Library logging.

I wasn t familiar with ListAppender so I created a CustomTraceListener that sticks the log messages in a List<string>:

  public class ListAppender : Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.CustomTraceListener
  {
    private List<string> list = new List<string>();

    public override void Write(string message)
    {
    }

    public override void WriteLine(string message)
    {
      list.Add(message);
    }

    public List<string> LogTable
    {
      get
      {
        return list;
      }
    }
  }

Here is a modified LoggerTests class that programmatically accesses the EL logging classes to setup the tests (this does not use NUnit):
  public class LoggerTests 
  {
    private ListAppender appender;
    private static LogWriter log;

    public void OneTimeSetup()
    {
      appender = new ListAppender();

      // Log all source levels
      LogSource mainLogSource = new LogSource("MainLogSource", SourceLevels.All);
      mainLogSource.Listeners.Add(appender);
    
      // All messages with a category of "Error" should be distributed
      // to all TraceListeners in mainLogSource.
      IDictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();
      traceSources.Add("Error", mainLogSource);

      LogSource nonExistentLogSource = null;    
      log = new LogWriter(new ILogFilter[0], traceSources, nonExistentLogSource,
                        nonExistentLogSource, mainLogSource, "Error", false, false);
    }

    public void TestLogging()
    {
      LogEntry le = new LogEntry() { Message = "Test", Severity = TraceEventType.Information };
      le.Categories.Add("Debug");
      log.Write(le);

      // we are not setup to log debug messages
      System.Diagnostics.Debug.Assert(appender.LogTable.Count == 0);

      le.Categories.Add("Error");
      log.Write(le);
      
      // we should have logged an error
      System.Diagnostics.Debug.Assert(appender.LogTable.Count == 1);
    }
  }
问题回答

Enterprise Library 5.0 introduced a fluent interface which can be used to programmatically configure the application blocks. You will probably find this to be a more comfortable option.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签