Question

I am using log4net, and want to simplify the usage. Right now, in every class I use logging (which is almost all all classes), I have to write:

public class MyClass
{
    public static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    try
    {
       // do something
    } 
    catch(Exception ex)
    {
       log.Error("Problem doing something", ex);
    }
}

What I would really like to do is to put the first declaration in another class, which I could inherit wherever I need logging:

 public class MyClass : Logging
 {
    try
    {
       // do something
    } 
    catch(Exception ex)
    {
       log.Error("Problem doing something", ex);
    }
 }

public class Logging
{
    public static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
}

But, if I do this, the problem is that

 System.Reflection.MethodBase.GetCurrentMethod().DeclaringType

...ends up picking up the class name Logging, which is no good for the log. How do I get it to pick up the class name of the class where the inherited logging class is used?

Thanks!

Était-ce utile?

La solution

If you inherit all your classes from Logging class then you won't be able to inherit classes from any other classes and create inheritance structure because C# does not support multiple inheritance. You really need to use composition not inheritance.

You can simplify calls to your logger by creating static helper class:

public static class LoggerHelper
{
    public static void WriteError(string message,Exception ex, Type type)
    {
        var log = log4net.LogManager.GetLogger(type);
        log.Error(message, ex);
    }
}

And then in you classes you will call it like this:

public class MyClass
{
    try
    {
        // do something
    } 
    catch(Exception ex)
    {
        LoggerHelper.WriteError("Problem doing something", ex, this.GetType());
    }
 }

Autres conseils

Declare your base class like so:

 public abstract class Logging
 {
    public readonly log4net.ILog log = log4net.LogManager.GetLogger(this.GetType());
 }

this.GetType() will always return the concrete type.

So you're gonna make all your classes inherit from Logging? Inheritance is not meant for code reuse, it's meant to represent a "is a kind of" relationship between two domain entities. Don't abuse it.

What you need is composition.

public class MyClass
{
    private static readonly ILog log = LogManager.GetLogger(typeof(MyClass));
}

MyClass has a logger, it is not a logger.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top