Using log4net declared as:
private readonly ILog log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType());
In an async method or task, like this one:
public async void CheckSomething()
{
log.Info(null);
//....
}
logs MoveNext
instead of CheckSomething
.
Any idea how to make it log an actual method name?
All
async
methods are rewritten into a state machine to satisfy potentialawait
values within the method. The final method in which the code lives is theMoveNext
method which is whatlog4net
is reporting.There is really no good way at runtime to transition from
MoveNext
to the actual method in which the code was originally written. They are somewhat disconnected at a metadata level. You may just have to resort to logging the name directlyWith thanks to the answer from Jacek Gorgoń, here is the utility I came up. It has a couple of improvements but still has a long way to go to work nicely with anonymous or lambda methods.
Here's an example usage:
I wrote a simple wrapper around log4net.
In the code that is doing the logging, just do:
Of course if you want to do things like Info, Debug, etc, you can just add it to the wrapper class.
NOTE
this utilizes the c# 5.0
[CallerMemberName]
Short: given the
MoveNext()
method, try this:Long (Disclaimer)
Don't use this in production. It relies on compiler behavior, which may likely change in a future version without notice. The following assumptions about compiler are made:
It works in my code, where I use it for runtime code analysis during debug/tests only. Again, please, don't use it in production code.
Use this, works great...