Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Logger per Type in Log4Net

I'm using (possibly abusing) log4net in an ASP.NET MVC website. I want to have one logger per class (which the docs suggest), but it seems that I need to pre-configure a logger for each class.

Is that right? Do I need to predefine every logger?

I'm appending to SqlServer & can see the column named Logger in the schema. It seems like it should be so easy to put whatever I want in that field, but the only dynamic logger creation I can find is here. Am I missing something?

like image 987
bendytree Avatar asked Dec 26 '22 16:12

bendytree


1 Answers

You don't need to pre-define each logger. Rather, the conventional method is to use a standard pattern for the log4net logger that uses reflection in the consuming class to declare the logger by Type. Just dump this property into each class and you're good to go:

private static log4net.ILog _logger;
private static log4net.ILog Logger
{
    get
    {
        if( _logger == null )
        {
            Type type = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
            _logger = log4net.LogManager.GetLogger( type );
        }
        return _logger;
    }
}
like image 147
Metro Smurf Avatar answered Jan 13 '23 10:01

Metro Smurf