How to set Severity Filter on Class Namespace Level

Topics: Logging Application Block
Jun 22, 2012 at 9:32 AM

Hi,

We are trying to port logging code over from log4net/log4J to Enterprise library 5 logging.
ex. we have component_xx.exe with his dependency component_xx.data.dll and in log4net and log4j
you have the ability to include specify for namespace ex. component_xx_data.model to log only information’s and for component_xx_data.model.error to log only errors,
how can be that approach be done with Enterprise library logging block ?

 

regards,

johannes

Jun 29, 2012 at 7:38 AM
Edited Jun 29, 2012 at 7:39 AM

Enterprise Library does not support Hierarchical Loggers like Log4net does.

A typical example of Log4net might be:

private static readonly ILog logger = LogManager.GetLogger(typeof(MyClass));

In Enterprise Library you might do something similar:

private static LogWriter logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();

But that doesn't get you hierarchical loggers.  The best bet for implementing hierarchical loggers is to add the various namespaces/class name as separate categories.  Then in the configuration file you can enable or disable hierarchies by using a category.

To do this you can use a facade that will add the additional categories or perhaps a helper method to create the categories.  For Example:

    public static class LogHelper
    {
        public static IEnumerable<string> GetCategories<T>(params string[] categories)
        {
            if (categories != null)
            {
                foreach (var category in categories)
                {
                    yield return category;
                }
            }

            StringBuilder currentNamespace = new StringBuilder();

            foreach(string name in typeof(T).FullName.Split('.'))
            {
                currentNamespace.Append(name);
                yield return currentNamespace.ToString();
                currentNamespace.Append(".");
            }           
        }
    }
   IEnumerable<string> categories = LogHelper.GetCategories<MyClass>("General");
   logger.Write("Test", categories); 
   // Or
   logger.Write("Test", LogHelper.GetCategories<MyClass>("General"));

Categories can also be passed in to the LogWriter methods or added to the LogEntry itself:
LogEntry logEntry = new LogEntry()
{
    Message = "Test",
    Severity = System.Diagnostics.TraceEventType.Information,
    Categories = LogHelper.GetCategories<MyClass>("General").ToList()
};

logger.Write(logEntry);

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com