Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current class through declaration in inherited class

Tags:

c#

log4net

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!

like image 867
Anders Avatar asked Feb 25 '26 03:02

Anders


1 Answers

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());
    }
 }
like image 155
Yevgeniy.Chernobrivets Avatar answered Feb 27 '26 20:02

Yevgeniy.Chernobrivets



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!