简体   繁体   English

如何优化获取记录器的当前名称空间,类名称,方法名称

[英]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. 我正在考虑仅将其与Log功能放在一起,它将与我正在获取信息的当前功能不在同一程序集中。 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 . 如果不想每次都执行MethodBase.GetCurrentMethod() ,则必须从Log内获取调用方法。 You can do this like so: 您可以这样做:

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

So Log becomes: 因此, Log变为:

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. Console.WriteLine替换您自己的日志记录方法,一切顺利。

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: 同样,出于完整性考虑,如果您不关心名称空间和类,而只关心调用Log的方法的名称,则可以使用CallerMemberName进一步简化Log

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. 如果您采用类似于NLog的方法(对于每个类创建一个单独的静态Logger对象),这将很有用,因此您只需要执行一次StackTrace,此后就只关心方法名称。 If however you want all this to be contained in a single method, then the second solution is the way to go. 但是,如果您希望所有这些都包含在一个方法中,那么第二种解决方案就是解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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