When using wrapper, how to preserve class and method name for Log4Net to log?

前端 未结 3 1453
野的像风
野的像风 2020-11-28 16:37

I need a Log4net wrapper - to be exposed to a number of different components in a large app. I obviously want to retain the class and method name when logging but I would ke

3条回答
  •  执念已碎
    2020-11-28 17:08

    Create your wrapper class like this...

    public static class LogFourNet
        {
            // Define a static logger variable so that it references the
            private static readonly ILog Log = LogManager.GetLogger(typeof(LogFourNet));
    
            static LogFourNet()
            {
                XmlConfigurator.Configure(
                       new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
                Log.Info("Log4net is configured.");
            }
    
            public static void Info(object currentObj, string msg, [CallerLineNumber] int lineNumber = 0,
                [CallerFilePath] string caller = "", [CallerMemberName] string memberName = "")
            {
                Log.Info("[" + currentObj.GetType().Namespace + "." +
                         Path.GetFileNameWithoutExtension(caller) + "." + memberName + ":" + lineNumber + "] - " + msg);
            }
    
            public static void Debug(object currentObj, string msg, [CallerLineNumber] int lineNumber = 0,
                [CallerFilePath] string caller = "", [CallerMemberName] string memberName = "")
            {
                Log.Debug("[" + currentObj.GetType().Namespace + "." +
                          Path.GetFileNameWithoutExtension(caller) + "." + memberName + ":" + lineNumber + "] - " + msg);
            }
    
            public static void Error(object currentObj, string msg, [CallerLineNumber] int lineNumber = 0,
                [CallerFilePath] string caller = "", [CallerMemberName] string memberName = "")
            {
                Log.Error("[" + currentObj.GetType().Namespace + "." +
                          Path.GetFileNameWithoutExtension(caller) + "." + memberName + ":" + lineNumber + "] - " + msg);
            }
        }
    

    Configure your log4net.config file in the following manner...

    
      
        

    Now just use above these methods like this...

    // need to pass this(current obj) as we want to log full class name
    LogFourNet.Debug(this, "started something from wrapper");
    
    output:
    -------
    2017-02-04 15:38:37,549 [1] DEBUG [WebAPI_DI.Startup.Configuration:25] - started something from wrapper
    

提交回复
热议问题