<p>For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature).    </p>

<p>How do I accomplish this assuming that:  </p>

<ul>
<li>I don't want to use any 3rd party
AOP libraries for C#,</li>
<li>I don't want to add duplicate code to all the methods that I want to trace,  </li>
<li>I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way.  </li>
</ul>

<p>To make the question more concrete let's assume there are 3 classes:  </p>

<pre><code> public class Caller 
 {
     public static void Call() 
     {
         Traced traced = new Traced();
         traced.Method1();
         traced.Method2(); 
     }
 }

 public class Traced 
 {
     public void Method1(String name, Int32 value) { }

     public void Method2(Object object) { }
 }

 public class Logger
 {
     public static void LogStart(MethodInfo method, Object[] parameterValues);

     public static void LogEnd(MethodInfo method);
 }
</code></pre>

<p>How do I invoke <em>Logger.LogStart</em> and <em>Logger.LogEnd</em> for every call to <em>Method1</em> and <em>Method2</em> without modifying the <em>Caller.Call</em> method and without adding the calls explicitly to <em>Traced.Method1</em> and <em>Traced.Method2</em>?</p>

<p>Edit:  What would be the solution if I'm allowed to slightly change the Call method?</p>

[{'answer_id': 25806, 'author': 'kokos', 'author_id': 1065, 'author_profile': 'https://Stackoverflow.com/users/1065', 'pm_score': -1, 'selected': False, 'text': '<ol>\n<li>Write your own AOP library.</li>\n<li>Use reflection to generate a logging proxy over your instances (not sure if you can do it without changing some part of your existing code).</li>\n<li>Rewrite the assembly and inject your logging code (basically the same as 1).</li>\n<li>Host the CLR and add logging at this level (i think this is the hardest solution to implement, not sure if you have the required hooks in the CLR though).</li>\n</ol>\n'}, {'answer_id': 25808, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 1, 'selected': False, 'text': "<p>I don't know a solution but my approach would be as follows.</p>\n\n<p>Decorate the class (or its methods) with a custom attribute. Somewhere else in the program, let an initialization function reflect all types, read the methods decorated with the attributes and inject some IL code into the method. It might actually be more practical to <em>replace</em> the method by a stub that calls <code>LogStart</code>, the actual method and then <code>LogEnd</code>. Additionally, I don't know if you can change methods using reflection so it might be more practical to replace the whole type.</p>\n"}, {'answer_id': 25810, 'author': 'Steen', 'author_id': 1448983, 'author_profile': 'https://Stackoverflow.com/users/1448983', 'pm_score': 3, 'selected': False, 'text': '<p>If you write a class - call it Tracing - that implements the IDisposable interface, you could wrap all method bodies in a </p>\n\n<pre><code>Using( Tracing tracing = new Tracing() ){ ... method body ...}\n</code></pre>\n\n<p>In the Tracing class you could the handle the logic of the traces in the constructor/Dispose method, respectively, in the Tracing class to keep track of the entering and exiting of the methods. Such that:</p>\n\n<pre><code>    public class Traced \n    {\n        public void Method1(String name, Int32 value) {\n            using(Tracing tracer = new Tracing()) \n            {\n                [... method body ...]\n            }\n        }\n\n        public void Method2(Object object) { \n            using(Tracing tracer = new Tracing())\n            {\n                [... method body ...]\n            }\n        }\n    }\n</code></pre>\n'}, {'answer_id': 25811, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 3, 'selected': False, 'text': '<p>Take a look at this - Pretty heavy stuff..\n<a href="http://msdn.microsoft.com/en-us/magazine/cc164165.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/magazine/cc164165.aspx</a></p>\n\n<p>Essential .net - don box had a chapter on what you need called Interception. \nI scraped some of it here (Sorry about the font colors - I had a dark theme back then...)\n<a href="http://madcoderspeak.blogspot.com/2005/09/essential-interception-using-contexts.html" rel="noreferrer">http://madcoderspeak.blogspot.com/2005/09/essential-interception-using-contexts.html</a></p>\n'}, {'answer_id': 25820, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 7, 'selected': True, 'text': '<p>C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful.</p>\n\n<p>I looked up for ways to do exactly what you wanted to do and I found no easy way to do it.</p>\n\n<p>As I understand it, this is what you want to do:</p>\n\n<pre><code>[Log()]\npublic void Method1(String name, Int32 value);\n</code></pre>\n\n<p>and in order to do that you have two main options</p>\n\n<ol>\n<li><p>Inherit your class from MarshalByRefObject or ContextBoundObject and define an attribute which inherits from IMessageSink. <a href="http://www.developerfusion.co.uk/show/5307/3/" rel="noreferrer">This article</a> has a good example. You have to consider nontheless that using a MarshalByRefObject the performance will go down like hell, and I mean it, I\'m talking about a 10x performance lost so think carefully before trying that.</p></li>\n<li><p>The other option is to inject code directly. In runtime, meaning you\'ll have to use reflection to "read" every class, get its attributes and inject the appropiate call (and for that matter I think you couldn\'t use the Reflection.Emit method as I think Reflection.Emit wouldn\'t allow you to insert new code inside an already existing method). At design time this will mean creating an extension to the CLR compiler which I have honestly no idea on how it\'s done.</p></li>\n</ol>\n\n<p>The final option is using an <a href="http://en.wikipedia.org/wiki/Inversion_of_control" rel="noreferrer">IoC framework</a>. Maybe it\'s not the perfect solution as most IoC frameworks works by defining entry points which allow methods to be hooked but, depending on what you want to achive, that might be a fair aproximation.</p>\n'}, {'answer_id': 25825, 'author': 'Antoine Aubry', 'author_id': 2680, 'author_profile': 'https://Stackoverflow.com/users/2680', 'pm_score': 6, 'selected': False, 'text': '<p>The simplest way to achieve that is probably to use <a href="http://www.postsharp.net" rel="noreferrer">PostSharp</a>. It injects code inside your methods based on the attributes that you apply to it. It allows you to do exactly what you want.</p>\n\n<p>Another option is to use the <a href="http://msdotnetsupport.blogspot.com/2006/08/net-profiling-api-tutorial.html" rel="noreferrer">profiling API</a> to inject code inside the method, but that is really hardcore.</p>\n'}, {'answer_id': 94192, 'author': 'Stacy A', 'author_id': 17824, 'author_profile': 'https://Stackoverflow.com/users/17824', 'pm_score': 1, 'selected': False, 'text': "<p>You could potentially use the GOF Decorator Pattern, and 'decorate' all classes that need tracing.</p>\n\n<p>It's probably only really practical with an IOC container (but as pointer out earlier you may want to consider method interception if you're going to go down the IOC path).</p>\n"}, {'answer_id': 1774731, 'author': 'Liao', 'author_id': 136089, 'author_profile': 'https://Stackoverflow.com/users/136089', 'pm_score': 1, 'selected': False, 'text': '<p>you need to bug Ayende for an answer on how he did it:\n<a href="http://ayende.com/Blog/archive/2009/11/19/can-you-hack-this-out.aspx" rel="nofollow noreferrer">http://ayende.com/Blog/archive/2009/11/19/can-you-hack-this-out.aspx</a></p>\n'}, {'answer_id': 5345043, 'author': 'Jay', 'author_id': 390720, 'author_profile': 'https://Stackoverflow.com/users/390720', 'pm_score': 3, 'selected': False, 'text': '<p>I have found a different way which may be easier...</p>\n\n<p>Declare a Method InvokeMethod</p>\n\n<pre><code>[WebMethod]\n    public object InvokeMethod(string methodName, Dictionary&lt;string, object&gt; methodArguments)\n    {\n        try\n        {\n            string lowerMethodName = \'_\' + methodName.ToLowerInvariant();\n            List&lt;object&gt; tempParams = new List&lt;object&gt;();\n            foreach (MethodInfo methodInfo in serviceMethods.Where(methodInfo =&gt; methodInfo.Name.ToLowerInvariant() == lowerMethodName))\n            {\n                ParameterInfo[] parameters = methodInfo.GetParameters();\n                if (parameters.Length != methodArguments.Count()) continue;\n                else foreach (ParameterInfo parameter in parameters)\n                    {\n                        object argument = null;\n                        if (methodArguments.TryGetValue(parameter.Name, out argument))\n                        {\n                            if (parameter.ParameterType.IsValueType)\n                            {\n                                System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(parameter.ParameterType);\n                                argument = tc.ConvertFrom(argument);\n\n                            }\n                            tempParams.Insert(parameter.Position, argument);\n\n                        }\n                        else goto ContinueLoop;\n                    }\n\n                foreach (object attribute in methodInfo.GetCustomAttributes(true))\n                {\n                    if (attribute is YourAttributeClass)\n                    {\n                        RequiresPermissionAttribute attrib = attribute as YourAttributeClass;\n                        YourAttributeClass.YourMethod();//Mine throws an ex\n                    }\n                }\n\n                return methodInfo.Invoke(this, tempParams.ToArray());\n            ContinueLoop:\n                continue;\n            }\n            return null;\n        }\n        catch\n        {\n            throw;\n        }\n    }\n</code></pre>\n\n<p>I then define my methods like so</p>\n\n<pre><code>[WebMethod]\n    public void BroadcastMessage(string Message)\n    {\n        //MessageBus.GetInstance().SendAll("&lt;span class=\'system\'&gt;Web Service Broadcast: &lt;b&gt;" + Message + "&lt;/b&gt;&lt;/span&gt;");\n        //return;\n        InvokeMethod("BroadcastMessage", new Dictionary&lt;string, object&gt;() { {"Message", Message} });\n    }\n\n    [RequiresPermission("editUser")]\n    void _BroadcastMessage(string Message)\n    {\n        MessageBus.GetInstance().SendAll("&lt;span class=\'system\'&gt;Web Service Broadcast: &lt;b&gt;" + Message + "&lt;/b&gt;&lt;/span&gt;");\n        return;\n    }\n</code></pre>\n\n<p>Now I can have the check at run time without the dependency injection...</p>\n\n<p>No gotchas in site :)</p>\n\n<p>Hopefully you will agree that this is less weight then a AOP Framework or deriving from MarshalByRefObject or using remoting or proxy classes.</p>\n'}, {'answer_id': 5985377, 'author': 'Nitro', 'author_id': 751485, 'author_profile': 'https://Stackoverflow.com/users/751485', 'pm_score': 1, 'selected': False, 'text': '<p>AOP is a must for clean code implementing, however if you want to surround a block in C#, generic methods have relatively easier usage. (with intelli sense and strongly typed code) Certainly, it can NOT be an alternative for AOP.</p>\n\n<p>Although <a href="http://www.sharpcrafters.com/postsharp#be-non-invasive" rel="nofollow">PostSHarp</a> have little buggy issues (i do not feel confident for using at production), it is a good stuff.</p>\n\n<p>Generic wrapper class, </p>\n\n<pre><code>public class Wrapper\n{\n    public static Exception TryCatch(Action actionToWrap, Action&lt;Exception&gt; exceptionHandler = null)\n    {\n        Exception retval = null;\n        try\n        {\n            actionToWrap();\n        }\n        catch (Exception exception)\n        {\n            retval = exception;\n            if (exceptionHandler != null)\n            {\n                exceptionHandler(retval);\n            }\n        }\n        return retval;\n    }\n\n    public static Exception LogOnError(Action actionToWrap, string errorMessage = "", Action&lt;Exception&gt; afterExceptionHandled = null)\n    {\n        return Wrapper.TryCatch(actionToWrap, (e) =&gt;\n        {\n            if (afterExceptionHandled != null)\n            {\n                afterExceptionHandled(e);\n            }\n        });\n    }\n}\n</code></pre>\n\n<p>usage could be like this (with intelli sense of course)</p>\n\n<pre><code>var exception = Wrapper.LogOnError(() =&gt;\n{\n  MessageBox.Show("test");\n  throw new Exception("test");\n}, "Hata");\n</code></pre>\n'}, {'answer_id': 13812748, 'author': 'GeekzSG', 'author_id': 899578, 'author_profile': 'https://Stackoverflow.com/users/899578', 'pm_score': 2, 'selected': False, 'text': '<p>You can use open source framework <a href="http://codeinject.codeplex.com" rel="nofollow">CInject</a> on CodePlex.  You can write minimal code to create an Injector and get it to intercept any code quickly with CInject. Plus, since this is Open Source you can extend this as well.  </p>\n\n<p>Or you can follow the steps mentioned on this article on <a href="http://www.codetails.com/punitganshani/intercepting-method-calls-using-il/20121202" rel="nofollow">Intercepting Method Calls using IL</a> and create your own interceptor using Reflection.Emit classes in C#.</p>\n'}, {'answer_id': 31364170, 'author': 'irriss', 'author_id': 684004, 'author_profile': 'https://Stackoverflow.com/users/684004', 'pm_score': -1, 'selected': False, 'text': '<p>The best you can do before C# 6 with \'nameof\' released is to use slow StackTrace and linq Expressions.</p>\n\n<p>E.g. for such method </p>\n\n<pre class="lang-cs prettyprint-override"><code>    public void MyMethod(int age, string name)\n    {\n        log.DebugTrace(() =&gt; age, () =&gt; name);\n\n        //do your stuff\n    }\n</code></pre>\n\n<p>Such line may be produces in your log file</p>\n\n<pre><code>Method \'MyMethod\' parameters age: 20 name: Mike\n</code></pre>\n\n<p>Here is the implementation:</p>\n\n<pre><code>    //TODO: replace with \'nameof\' in C# 6\n    public static void DebugTrace(this ILog log, params Expression&lt;Func&lt;object&gt;&gt;[] args)\n    {\n        #if DEBUG\n\n        var method = (new StackTrace()).GetFrame(1).GetMethod();\n\n        var parameters = new List&lt;string&gt;();\n\n        foreach(var arg in args)\n        {\n            MemberExpression memberExpression = null;\n            if (arg.Body is MemberExpression)\n                memberExpression = (MemberExpression)arg.Body;\n\n            if (arg.Body is UnaryExpression &amp;&amp; ((UnaryExpression)arg.Body).Operand is MemberExpression)\n                memberExpression = (MemberExpression)((UnaryExpression)arg.Body).Operand;\n\n            parameters.Add(memberExpression == null ? "NA" : memberExpression.Member.Name + ": " + arg.Compile().DynamicInvoke().ToString());\n        }\n\n        log.Debug(string.Format("Method \'{0}\' parameters {1}", method.Name, string.Join(" ", parameters)));\n\n        #endif\n    }\n</code></pre>\n'}, {'answer_id': 32238417, 'author': 'Ibrahim ben Salah', 'author_id': 1906989, 'author_profile': 'https://Stackoverflow.com/users/1906989', 'pm_score': 2, 'selected': False, 'text': '<p>First you have to modify your class to implement an interface (rather than implementing the MarshalByRefObject).</p>\n\n<pre><code>interface ITraced {\n    void Method1();\n    void Method2()\n}\nclass Traced: ITraced { .... }\n</code></pre>\n\n<p>Next you need a generic wrapper object based on RealProxy to decorate any interface to allow intercepting any call to the decorated object.</p>\n\n<pre><code>class MethodLogInterceptor: RealProxy\n{\n     public MethodLogInterceptor(Type interfaceType, object decorated) \n         : base(interfaceType)\n     {\n          _decorated = decorated;\n     }\n\n    public override IMessage Invoke(IMessage msg)\n    {\n        var methodCall = msg as IMethodCallMessage;\n        var methodInfo = methodCall.MethodBase;\n        Console.WriteLine("Precall " + methodInfo.Name);\n        var result = methodInfo.Invoke(_decorated, methodCall.InArgs);\n        Console.WriteLine("Postcall " + methodInfo.Name);\n\n        return new ReturnMessage(result, null, 0,\n            methodCall.LogicalCallContext, methodCall);\n    }\n}\n</code></pre>\n\n<p>Now we are ready to intercept calls to Method1 and Method2 of ITraced</p>\n\n<pre><code> public class Caller \n {\n     public static void Call() \n     {\n         ITraced traced = (ITraced)new MethodLogInterceptor(typeof(ITraced), new Traced()).GetTransparentProxy();\n         traced.Method1();\n         traced.Method2(); \n     }\n }\n</code></pre>\n'}, {'answer_id': 41128743, 'author': 'plog17', 'author_id': 1180998, 'author_profile': 'https://Stackoverflow.com/users/1180998', 'pm_score': 4, 'selected': False, 'text': '<p>You could achieve it with <a href="https://github.com/castleproject/Windsor/blob/master/docs/orphan-introduction-to-aop-with-castle.md" rel="noreferrer">Interception</a> feature of a DI container such as <a href="https://github.com/castleproject/Windsor" rel="noreferrer">Castle Windsor</a>. Indeed, it is possible to configure the container in such way that every classes that have a method decorated by a specific attribute would be intercepted.</p>\n\n<p>Regarding point #3, OP asked for a solution without AOP framework. I assumed in the following answer that what should be avoided were Aspect, JointPoint, PointCut, etc. According to <a href="https://github.com/castleproject/Windsor/blob/master/docs/orphan-introduction-to-aop-with-castle.md" rel="noreferrer">Interception documentation from CastleWindsor</a>, none of those are required to accomplish what is asked.</p>\n\n<h3>Configure generic registration of an Interceptor, based on the presence of an attribute:</h3>\n\n<pre><code>public class RequireInterception : IContributeComponentModelConstruction\n{\n    public void ProcessModel(IKernel kernel, ComponentModel model)\n    {\n        if (HasAMethodDecoratedByLoggingAttribute(model.Implementation))\n        {\n            model.Interceptors.Add(new InterceptorReference(typeof(ConsoleLoggingInterceptor)));\n            model.Interceptors.Add(new InterceptorReference(typeof(NLogInterceptor)));\n        }\n    }\n\n    private bool HasAMethodDecoratedByLoggingAttribute(Type implementation)\n    {\n        foreach (var memberInfo in implementation.GetMembers())\n        {\n            var attribute = memberInfo.GetCustomAttributes(typeof(LogAttribute)).FirstOrDefault() as LogAttribute;\n            if (attribute != null)\n            {\n                return true;\n            }\n        }\n\n        return false;\n    }\n}\n</code></pre>\n\n<h3>Add the created IContributeComponentModelConstruction to container</h3>\n\n<pre><code>container.Kernel.ComponentModelBuilder.AddContributor(new RequireInterception());\n</code></pre>\n\n<h3>And you can do whatever you want in the interceptor itself</h3>\n\n<pre><code>public class ConsoleLoggingInterceptor : IInterceptor\n{\n    public void Intercept(IInvocation invocation)\n    {\n        Console.Writeline("Log before executing");\n        invocation.Proceed();\n        Console.Writeline("Log after executing");\n    }\n}\n</code></pre>\n\n<h3>Add the logging attribute to your method to log</h3>\n\n<pre><code> public class Traced \n {\n     [Log]\n     public void Method1(String name, Int32 value) { }\n\n     [Log]\n     public void Method2(Object object) { }\n }\n</code></pre>\n\n<p>Note that some handling of the attribute will be required if only some method of a class needs to be intercepted. By default, all public methods will be intercepted.</p>\n'}, {'answer_id': 41130198, 'author': 'Tony THONG', 'author_id': 7193293, 'author_profile': 'https://Stackoverflow.com/users/7193293', 'pm_score': 3, 'selected': False, 'text': '<p>If you want to trace after your methods without limitation (no code adaptation, no AOP Framework, no duplicate code), let me tell you, you need some magic...</p>\n\n<p>Seriously, I resolved it to implement an AOP Framework working at runtime.</p>\n\n<p>You can find here : <a href="http://aspectize.codeplex.com" rel="noreferrer">NConcern .NET AOP Framework</a></p>\n\n<p>I decided to create this AOP Framework to give a respond to this kind of needs. it is a simple library very lightweight. You can see an example of logger in home page.</p>\n\n<p>If you don\'t want to use a 3rd party assembly, you can browse the code source (open source) and copy both files <a href="http://aspectize.codeplex.com/SourceControl/latest#NConcern/NConcern/Aspect/Directory/Aspect.Directory.cs" rel="noreferrer">Aspect.Directory.cs</a> and <a href="http://aspectize.codeplex.com/SourceControl/latest#NConcern/NConcern/Aspect/Directory/Aspect.Directory.Entry.cs" rel="noreferrer">Aspect.Directory.Entry.cs</a> to adapted as your wishes. Theses classes allow to replace your methods at runtime. I would just ask you to respect the license. </p>\n\n<p>I hope you will find what you need or to convince you to finally use an AOP Framework.</p>\n'}, {'answer_id': 63240528, 'author': 'Javier Contreras', 'author_id': 5508250, 'author_profile': 'https://Stackoverflow.com/users/5508250', 'pm_score': 0, 'selected': False, 'text': '<p>Maybe it\'s to late for this answer but here it goes.</p>\n<p>What you are looking to achieve is built in MediatR library.</p>\n<p>This is my RequestLoggerBehaviour which intercepts all calls to my business layer.</p>\n<pre><code>namespace SmartWay.Application.Behaviours\n{\n    public class RequestLoggerBehaviour&lt;TRequest, TResponse&gt; : IPipelineBehavior&lt;TRequest, TResponse&gt;\n    {\n        private readonly ILogger _logger;\n        private readonly IAppSession _appSession;\n        private readonly ICreateLogGrain _createLogGrain;\n\n        public RequestLoggerBehaviour(ILogger&lt;TRequest&gt; logger, IAppSession appSession, IClusterClient clusterClient)\n        {\n            _logger = logger;\n            _appSession = appSession;\n            _createLogGrain = clusterClient.GetGrain&lt;ICreateLogGrain&gt;(Guid.NewGuid());\n        }\n\n        public async Task&lt;TResponse&gt; Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate&lt;TResponse&gt; next)\n        {\n            var name = typeof(TRequest).Name;\n            _logger.LogInformation($&quot;SmartWay request started: ClientId: {_appSession.ClientId} UserId: {_appSession.UserId} Operation: {name} Request: {request}&quot;);\n\n            var response = await next();\n\n            _logger.LogInformation($&quot;SmartWay request ended: ClientId: {_appSession.ClientId} UserId: {_appSession.UserId} Operation: {name} Request: {request}&quot;);\n\n            return response;\n        }\n    }\n}\n</code></pre>\n<p>You can also create performance behaviours to trace methods that take too long to execute for example.</p>\n<p>Having clean architecture (MediatR) on your business layer will allow you to keep your code clean while you enforce SOLID principles.</p>\n<p>You can see how it works here:\n<a href="https://youtu.be/5OtUm1BLmG0?t=1" rel="nofollow noreferrer">https://youtu.be/5OtUm1BLmG0?t=1</a></p>\n'}]
['https://Stackoverflow.com/questions/25803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2800/']