Reputation: 853
I have a class
public class DataLayerFromOutside
{
public string DataLayerMethod(string dataLayerMethodParameter)
{
NLogging.Info("FromMethod");
return "Hi";
}
}
This class is within SampleClassLibrary
.
I have a controller from which this method is called.
[LogActionFilter]
public class SampleController : ApiController
{
// GET api/sample
public string Get()
{
DataLayerFromOutside businessLayer = new DataLayerFromOutside();
NLogging.Info("Info ");
return businessLayer.DataLayerMethod("Hi");
}
This controller is within another dll 'TestLoggingEntryAndExit'
.
I have an NLogging
class where we log all activities.This class contains a method
public static void Info(string message, Exception exception = null, [CallerFilePathAttribute] string callerPath = "", [CallerMemberName] string callerMember = "", [CallerLineNumber] int callerLine = 0)
{
Log(LogLevel.Info, message,null, exception, callerPath, callerMember, callerLine);
}
I want to find the assembly name from which this Info method is called.
How can I find the assembly name from CallerFilePathAttribute
?
Upvotes: 0
Views: 717
Reputation: 36740
This isn't possible with the caller info attributes. There is a feature request for more caller info attributes on the backlog of Roslyn
Currently the only way is to use reflection:
//get assembly of caller
var assembly = new StackTrace().GetFrame(1, false).GetMethod().DeclaringType.Assembly;
This isn't possible in .NET standard (.NET Core) yet. It should be there in Netstandard 2.0
edit: @Eilon is right. This isn't a reliable way. Adding [MethodImpl(MethodImplOptions.NoInlining)]
is helping a lot, but no guarantees
edit 2: another reliable way (and more complicated), is to write/use a Fody plugin. See Fody website
Upvotes: 1