简体   繁体   中英

How to optimize getting current namespace, class name, method name for logger

I am trying to log exceptions where I get the executing method's name with its class name and namespace. Something like this:

在此处输入图片说明

Now, I can get all that I need like this:

Log.AppendLog(typeof(FamilyPublishCommand).Namespace + "." + GetType().Name + "." + MethodBase.GetCurrentMethod().Name + ": Started.");

Is there a way to move all of the stuff I am doing getting the right namespace, class and method name to a static utility method living in a different assembly?

I am thinking about just putting it together with the Log functionality which will not be in the same assembly as current one that I am retrieving info about. Any way I can separate these?

The following will work no matter what assembly you put it in:

using System.Reflection;
static void Log(MethodBase method, string msg)
{
    Console.WriteLine("{0}.{1}: {2}", method.ReflectedType.FullName, method.Name, msg);
}

Usage:

Log(MethodBase.GetCurrentMethod(), myString);

That is the simplest solution to your problem.

If you don't want to do MethodBase.GetCurrentMethod() every time, then you will have to get the calling method from within Log . You can do this like so:

MethodBase method = new StackFrame(1).GetMethod();

So Log becomes:

using System.Reflection;
using System.Diagnostics;
static void Log(string msg)
{
    var method = new StackFrame(1).GetMethod();
    Console.WriteLine("{0}.{1}: {2}", method.ReflectedType.FullName, method.Name, msg);
}

Substitute Console.WriteLine for your own logging method and you're good to go.

Also, for completeness' sake, if you don't care about the namespace and class and only care about the name of the method that called Log , then you can use CallerMemberName to simplify Log even further:

static void Log(string msg, [CallerMemberName] string caller = "")
{
    Console.WriteLine("{0}: {1}", caller, msg);
}

This would be useful if you took an approach similar to NLog, where you create a separate static Logger object for each of your classes, so you only do the StackTrace once and from then on you only care about the method name. If however you want all this to be contained in a single method, then the second solution is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM