title: Mono.Cecil: Insert a log statement in method's beginning
body: <p>I am using Mono.Cecil to edit my target method's IL code so that I can log that method's entry point, without editing the actual code.
  I am able to insert a call instruction to a method which can perform logging operation.
  But I don't know how to log my target method's input parameters.
  In short i want to insert an instruction in the target method by changing it's IL code to do a log or say print operation to log the input parameter values passed to that method.</p>
  
  <p>I tried a basic program as sample.</p>
  
  <pre><code>public class Target
  {
      // My target method. 
      public void Run(int arg0, string arg1)
      {
          Console.WriteLine("Run method body");
      }
  
  
  }
  
  public static class Trace{
  
  // This is my log method, which i want to call in begining of Run() method. 
      public void LogEntry(string methodName, object[] params)
      {
          System.Console.WriteLine("******Entered in "+ methodName+" method.***********")
      // With params :......
      //
      }
  }
  </code></pre>
  
  <p>Source program.</p>
  
  <pre><code>public class Sample 
  {
      private readonly string _targetFileName;
      private readonly ModuleDefinition _module;
  
      public ModuleDefinition TargetModule { get { return _module; } }
  
      public Sample(string targetFileName)
      {
          _targetFileName = targetFileName;
  
          // Read the module with default parameters
          _module = ModuleDefinition.ReadModule(_targetFileName);
      }
  
      public void Run(string type, string method)
      {
  
          // Retrive the target class. 
          var targetType = _module.Types.Single(t =&gt; t.Name == type);
  
          // Retrieve the target method.
          var runMethod = targetType.Methods.Single(m =&gt; m.Name == method);
  
          // Get a ILProcessor for the Run method
          var processor = runMethod.Body.GetILProcessor();
  
          // get log entry method ref to create instruction
          var logEntryMethodReference = targetType.Methods.Single(m =&gt; m.Name == "LogEntry");
  
     // Import ..
      //
          var newInstruction = processor.Create(OpCodes.Call, logEntryMethodReference);
  
          var firstInstruction = runMethod.Body.Instructions[0];
  
          processor.InsertBefore(firstInstruction, newInstruction);
  
          // Write the module with default parameters
          _module.Write(_targetFileName);
      }
  }
  </code></pre>