How do I find the type of the object instance of the caller of the current function?

前端 未结 5 724
误落风尘
误落风尘 2021-02-06 07:37

Currently I have the function CreateLog() for creating a a log4net Log with name after the constructing instance\'s class. Typically used as in:

class MessageRe         


        
5条回答
  •  忘掉有多难
    2021-02-06 08:19

    I think you may be asking the wrong question. First of all the logger should be static to each class - each class should declare its own logger (to ensure that class names are properly reported AND to allow selective reporting of log messages filtered by project or namespace, from the config file.

    Secondly it appears that you have created this method solely to identify the name of the calling class? If so we use this boilerplate code that is pasted into each class:

    private static ILog log = 
    log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    

    Because it is private you ensure that your inheriting classes must declare their own logger and not use yours. Because it is static you ensure that the overhead of looking up the logger is only incurred once.

    My apologies if you had different reasons for coding the Util.CreateLog() method.

提交回复
热议问题