How to determine calling method and class name? [d

2019-01-17 10:05发布

This question already has an answer here:

I'm currently developing a application logging library using the built in TraceListener. This library will be used in many projects and should offer a simple interface where I only have to care about WHAT is going to be written in into the log file, but not HOW.

By using the reflection namespace, I can figure out which application currently called a log function (retrieving execution assembly name), but I want also the name of the function and class that called the logging function.

Let's say I have:

public static void LogInfo(string vLogText) {
   Trace.WriteLine(
        MethodInfo.GetCurrentMethod().Name
        + this.GetType().ToString() + vLogText);
   }

When I call from another project (class: TestClass, method: TestMethod)

Tracer.LogInfo("log this!")

I expect to see in the log:

TestClass, TestMethod, log this!

But instead I got

TracerClass, LogInfo, log this!

How to get the parent method and class name?

3条回答
太酷不给撩
2楼-- · 2019-01-17 10:39

The newest C# and VS 2012 shipped with Caller Information (namely CallerFilePathAttribute, CallerLineNumberAttribute and CallerMemberNameAttribute), which will help you if you can only use it.

If you can't, you'd have to refer to other answers.

查看更多
干净又极端
3楼-- · 2019-01-17 10:42

Try doing something like this:

var mth = new StackTrace().GetFrame(1).GetMethod();
var cls = mth.ReflectedType.Name;
// where 1 illustrates how deep into the stack to reflect.

There are more elegant solutions in C# 5.0 >, however if you are using older frameworks, the above will help.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-17 10:49

You may just record the full stack trace instead of just the calling method using Environment.StackTrace. This may help you if you want to use the same logging structure to log exceptions.

Refer to this msdn page for more information.

查看更多
登录 后发表回答