A common, centralized method for registering parameters in C #

Consider this piece of JavaScript code:

Object.prototype.log = function() { // here, you have a centralized place to do logging stuff; console.log(this); } function fullName(firstName, lastName) { // here, using a simple one-line code, you can log all parameters; arguments.log(); } fullName('saeed', 'nemati'); 

Do we have a similar mechanism for registering all parameters passed to a method in C #?

Note What I did was use reflection, but without success:

 public static void LogParameters(this ParameterInfo[] parameters) { StringBuilder builder = new StringBuilder(); builder.Append("*****************\r\n"); builder.Append("Parameters\r\n"); parameters.ToList().ForEach(pi => { builder.AppendFormat("{0} => {1}\r\n", pi.Name, pi.DefaultValue); // The problem is that, I can't get the value of the parameter here }); builder.Append("*****************"); Log.Write(builder.ToString()); } public string GetFullName(string firstName, string lastName) { MethodBase.GetCurrentMethod().GetParameters().LogParameters(); return firstName + " - " + lastName; } GetFullName("saeed", "neamati"); 
+4
source share
2 answers

No, you cannot get parameter values ​​using reflection. You will need to pass them to the logging method explicitly.

You can do this using the debugger API, but you probably don't want this. I would just do it explicitly if you were you, and in fact it can lead to more useful logging, since you can only log what is important and also give some context in the message.

+7
source

You can do this using PostSharp and AOP. Here is an example that also logs the parameters of a method call.

http://blogs.lessthandot.com/index.php/WebDev/ServerProgramming/using-postsharp-and-log4net-to-set-up-co

+2
source

Source: https://habr.com/ru/post/1388420/


All Articles