I am trying to replace logging boilerplate using AOP Fody. I manually write boilerplate, which print to logs: "Method started/finished".
Simplified code:
[Conditional("DEBUG")]
private void ConditionalTrace(string msg)
{
log.Trace(msg);
}
private void MethodA(string message)
{
ConditionalTrace("MethodA started");
// Do something
ConditionalTrace("MethodA finished");
}
The crucial is, that logging is done only in DEBUG mode, which helps me to troubleshoot, but logging "is ignored" in Release mode to make sure that the code is not slowed down by unnecessary logging ( ConditionalTrace is not included in compiled IL at all ):
private void MethodA(string message)
{
// Do something
}
I have tried to replace ConditionalTrace by MethodboundaryAspect.Fody via attribute [LogStartStop], which results in the code without logging boilerplate:
[LogStartStop] // Attribute for auto-logging
private void MethodA(string message)
{
// Do something
}
Implementation of annotation [LogStartStop] :
[Conditional("DEBUG")] // this does not make any difference
public sealed class LogStartStopAttribute : OnMethodBoundaryAspect
{
private static Logger GetLogger(string name) => LogManager.GetLogger(name);
private static Logger GetLogger(MethodExecutionArgs args)
{
var className = args?.Method?.ReflectedType?.FullName?? "Unknown";
return GetLogger(className);
}
public override void OnEntry(MethodExecutionArgs args)
{
GetLogger(args).Trace($"{args.Method.Name} started");
}
public override void OnExit(MethodExecutionArgs args)
{
GetLogger(args).Trace($"{args.Method.Name} finished");
}
}
I would like to get IL Code like this:
private void MethodA(string message)
{
// Do something
}
The issue is, that even in Release mode, the generated IL looks like this (most of the code is related to Fody.OnMethodBoundaryAspect related code).
private void TestMethod(string message)
{
object[] __var_0 = new object[1] { message };
MethodExecutionArgs __var_ = new MethodExecutionArgs();
__var_.Arguments = __var_0;
MethodBase__var_2 = MethodInfos._methodInfo_4C74F80B0DB58EC65D5886B3DE2A15C8305C55AC86E63FEEB1EAA0497B153A4D;
__var_.Method = __var_2;
LogStartStopAttribute__var_3 = new LogStartStopAttribute();
__var_3.OnEntry(__var_);
FlowBehavior__var_4 = __var_.FlowBehavior;
if(__var_4 == FlowBehavior.Return)
{
return;
}
try
{
$_executor_TestMethod(message);
}
catch(Exception__var_5)
{
Exception__var_6 = __var_5;
__var_.Exception = __var_6;
__var_3.OnException(__var_);
FlowBehavior__var_7 = __var_.FlowBehavior;
if(__var_7 == FlowBehavior.Continue || __var_7 == FlowBehavior.Return)
{
return;
}
throw;
}
__var_3.OnExit(__var_);
}
Is there any chance Aspect library or Fody feature to overcome the issue ?