Logging in C#: Getting the class/method name performance - c#

I've recently been tasked with adding logging statements to every method call in a solution. These log entries need to contain the class and method name.
I know I can use MethodBase.GetCurrentMethod() and the StackFrame.GetMethod() methods. Which is better? Is there a better (or more performant) way to get the class and method name?

Well, the best/fastest way is to include a string in every function. That may not appear the most practical solution, but MethodBase.GetCurrentMethod() requires coding inside every method that using it anyway. i.e. You can write
string funcName = "MyClass.MyFunction(int, int)";
or you can write
string funcName = MethodBase.GetCurrentMethod().Name
Now, if you want to get the Name of the function that called the current function (i.e., you want to do this in one spot in your logging function), then your only option is reading through the StackFrame.

I have two suggestions:
Use ready-made AOP frameworks (like http://www.sharpcrafters.com/ ) they can handle this easily
Do a custom prebuild action where you replace some kind of stub in the beginning of every method:
void PerformSomeAction()
{
//PUT_LOGGING_HERE
}
then in custom tool replace those stubs with method names. This is guaranteed fastest method, but requires some investments.

this.getType().toString() should get you the class
About the method it seems stackFrame and methodbase are the most obvouis solutions, I cant comment on which is more efficient.

Related

Proper approach to interfaces in C#

I've created an interface which looks like this:
interface ICsvReader
{
List<string> ReadFromStream(Stream csvStream);
}
My question is about return type List<string>. In tutorials I can see a lot of examples where methods are just void. In that cases interface looks natural:
interface ILogger
{
void LogError(string error);
}
you don't have any specific destination of logging or method how to log errors. Like I said it looks natural for me, but what about specific types to return? Isn't it bad approach? When I'm using interface I want to create some abstraction over my methods - 'You should do this, but I don't care how'. So do you have any better idea for interface for file reader or something? I would like to read CSV from different sources but always return List<string>. Good or bad approach?
Logger is kind of writer so void; ICsvReader as name suggests it is reader meaning it is going to read something for you and give it in return.
Have you ever seen a read method with return type void? I can't remember one!
Only thing I can suggest is use IEnumerable<string> Always promise less than what you can deliver. That will help you to switch to deferred execution if required in future.
There is nothing wrong here. Since Logger does write operation it is void that's not your case you need to yield something saying "this is what I read for you".
Well, returning List<string> means that you have the whole structure in your memory. For CSV files larger that 2 G this may be not appropriate.
Another choice would be returning IEnumerable<string> — that would let a CSV-reader to decide whether it want to read the whole file at once, or do incremental loading and parsing. Or you would be able to have two different classes, one that would try to load whole file at once, and another would work step-by-step.
Of course, List<T> has methods and properties that IEnumerable<T> doesn't have, so you would have to decide whether this added flexibility is worth it. But I've seen a number of server-side plugins that would read gigantic files into memory in order to send them to the client, so I recommend at least think about this.
Regarding void vs List return type in interface
I think what approach you are taking is absolutely correct. In your case you are returning List is not incorrect, actually that is need of your application. And to do so your are declaring interface. Interface method declaration can be anything that suits your code.
As many answers suggested here for code optimization purpose use IEnumerable.
From Question:
So do you have any better idea for interface for file reader or
something?
Just suggestion, do you really need to create interface. Because definition of your ReadFromStream method in your case looks like going to be same, so you may end up writing same code in various classes. And solution will be write method in base class/ in abstract class(in which you will achieve abstraction)

unit testing a file writer function

I have a function which will take student details as input and write their report card into a xml file. When i tried to create unit tests in vs2008 i saw the message - "A method that does not return a value cannot be verified." My function does not return a value it merely writes into a file and returns.
How do i write tests for this function?
[TestMethod()]
public void StoreInformationTest()
{
StudentSettings target = new StudentSettings(); // TODO: Initialize to an appropriate
StudentSettings settings = null; // TODO: Initialize to an appropriate value
target.StoreInformation(settings);
Assert.Inconclusive("A method that does not return a value cannot be verified.");
}
Thanks in advance,
Regards,
John
With good separation of responsibilities, it would be easy to replace your file with something like a memorystream. Write into a memory stream instead of a file. Then you can test against the content of that. But as mentioned by others, a code example would maybe reveal other needs.
UPDATE:
Thanks for the code. It looks like your StudentSettings class is doing to much. Separate xml writing functions into its own class, extract an interface from it, and inject this into your class as a constructor argument. Then you can replace it with your own mock during tests.
First of all, if the big uncle Visual Studio tells you that your method cannot be tested, it does not have to be true.
You should return the output to be written in the file as a string, or your method should take TextWriter as a parameter. In the former case you may use mocking framework, as mentioned in the other answer, to give the method under test a fake TextWriter object.
You can use an mocking framework to do this. An good example is Moq. Simply put you can create fake-objects and you tell them to behave like another. You can also verify how often and method is called, if it is called and how often it should be called.
EDIT:
The quick startguide shown here has some good examples which probably will put you in the right direct. In your case you could create an moq of your class containing the function which writes your file. Using the verify function you can check/verify how often the function is called and if it runs without any exceptions.
The code generator is merely suggesting that it can't verify your test based on its return value (void) which makes perfect sense. I think someone else mentioned that this is more of a placeholder. When it comes to actually writing the test, you need to decide what your passing criteria really is. You can go as easy as;
Assert.IsTrue(File.Exists(filePath));
If all you care about is the file existing, or you can get deeper down into it, verify its contents and so forth. It is really up to you.

Any reason not to use `new object().foo()`?

When using extremely short-lived objects that I only need to call one method on, I'm inclined to chain the method call directly to new. A very common example of this is something like the following:
string noNewlines = new Regex("\\n+").Replace(" ", oldString);
The point here is that I have no need for the Regex object after I've done the one replacement, and I like to be able to express this as a one-liner. Is there any non-obvious problem with this idiom? Some of my coworkers have expressed discomfort with it, but without anything that seemed to be like a good reason.
(I've marked this as both C# and Java, since the above idiom is common and usable in both languages.)
This particular pattern is fine -- I use it myself on occasion.
But I would not use this pattern as you have in your example. There are two alternate approaches that are better.
Better approach: Use the static method Regex.Replace(string,string,string). There is no reason to obfuscate your meaning with the new-style syntax when a static method is available that does the same thing.
Best approach: If you use the same static (not dynamically-generated) Regex from the same method, and you call this method a lot, you should store the Regex object as a private static field on the class containing the method, since this avoids parsing the expression on each call to the method.
I don't see anything wrong with this; I do this quite frequently myself.
The only exception to the rule might be for debugging purposes, it's sometimes necessary to be able to see the state of the object in the debugger, which can be difficult in a one-liner like this.
If you don't need the object afterwards, I don't see a problem - I do it myself from time to time as well. However, it can be quite hard to spot, so if your coworkers are expressing discomfort, you might need to put it into a variable so there are no hard feelings on the team. Doesn't really hurt you.
You just have to be careful when you're chaining methods of objects that implement IDisposable. Doing a single-line chain doesn't really leave room for calling Dispose or the using {...} block.
For example:
DialogResult result = New SomeCfgDialog(some_data).ShowDialog();
There is no instance variable on which to call Dispose.
Then there is potential to obfuscate intent, hurt rather than improve readability and make it tougher to examine values while debugging. But those are all issues particular to the object and the situation and the number of methods chained. I don't think that there is a single reason to avoid it. Sometimes doing this will make the code more concise and readable and other times it might hurt for some of the reasons mentioned above.
As long as you're sure that the object is never needed again (or you're not creating multiple instances of an identical object), then there's no problem with it.
If the rest of your team isn't comfortable with it, though, you might want to re-think the decision. The team should set the standards and you should follow them. Be consistent. If you want to change the standard, discuss it. If they don't agree, then fall in line.
I think thats ok, and would welcome comments/reasons to the contrary. When the object is not short lived (or uses unmanaged resources - ie COM) then this practice can get you into trouble.
The issue is readability.
Putting the "chained" methods on a separate line seems to be the preferred convention with my team.
string noNewlines = new Regex("\\n+")
.Replace(" ", oldString);
One reason to avoid this style is that your coworkers might want to inspect the object in a debug mode. If you compound the similar instantiation the readability goes down a lot. For example :
String val = new Object1("Hello").doSomething(new Object2("interesting").withThis("input"));
Generally I prefer using a static method for the specific example you have mentioned.
The only potential problem I could see is - if, for some reason, new Regex were NULL because it was not instantiated correctly, you would get a Null Pointer Exception. However, I highly doubt that since Regex is always defined...
If you don't care about the object you invoke the method on, that's a sign that the method should probably be static.
In C#, I'd probably write an extension method to wrap the regex, so that I could write
string noNewlines = oldString.RemoveNewlines();
The extension method would look something like
using System.Text.RegularExpressions;
namespace Extensions
{
static class SystemStringExtensions
{
public static string RemoveNewlines(this string inputString)
{
// replace newline characters with spaces
return Regex.Replace(inputString, "\\n+", " ");
}
}
}
I find this much easier to read than your original example. It's also quite reusable, as stripping newline characters is one of the more common activities.

Reflection, invoke

I have a dll file, and I took an object from it and called the functions inside this dll by the object, like this:
Command testClass = (Command)assembly.CreateInstance(creatObject);
testClass.Execute();
I used reflection for some reason. So I need to use invoke function & set values for variables, then calling the basic function Execute.
Previously I wrote the following:
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
testClass.Execute();
but it wasn't useful for me.
I used the following:
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
object returnValue1 = objectType.GetMethod("Execute").Invoke(classObject, null);
I just want to ask if this is right, to calling the execute in this way, and by the way it works!
Calling methods using Reflection the way you use it is "okay" as long as you know what you're doing. There are quite a few things to consider when using Reflection:
It is unsafe - you can very easily make a mistake - if you change the method name, you won't be notified by the compiler and you'll discover that at runtime
It is slow - Reflection is simply inefficient - calling a method is slower by orders of magnitude.
If you need to do this only rarely, then it may be fine. However, your initial approach using a shared base class Command appears to be a much better idea to me. Could you clarify why you decided to use Reflection, so that we can (perhaps) suggest a better way?
If you need dynamic invocation, you could also consider using C# 4.0 dynamic, which does all this stuff behind the scene for you and is more efficient than simple Reflection. However, you should still have a very good reason for doing this.
It's not right, why do you use Reflection, provide a common interface and call the method directly. If you don't know why you use reflection then it's wrong :)
If you are implementing a extensible system, perhaps MEF would be better?
Thanks for your answers, sure i know why i used Reflection.
Because i need to set the values for a function setValues(i, j..etc) in run time, and these parameters and their names are different from dll to another.
then i have to invoke this function with its current values, & finally run another function named Execute() with the same current values, which could be changed from execute to another for the program!
so when i just used:
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
testClass.Execute();
the execute didnt work with the run time values which been entered.
But by this :
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
object returnValue1 = objectType.GetMethod("Execute").Invoke(classObject, null);
it works.
So i just want to be sure, that my work is right and not only suitable for my case!

Use Attributes To Check Whether to Access a Method

I have a method that is only accessible if a certain criteria is fulfilled, if it's not, then the method won't be executed. Currently, this is how I code the thing:
public void CanAccessDatabase()
{
if(StaticClass.IsEligible())
{
return;
}
// do the logic
}
Now, this code is ugly because out of no where there is this if(StaticClass.IsEligible()) condition that is not relevant to the concern of the method.
So I am thinking about putting the IsEligible method in the attribute, so that my code will look like this. If the condition is not fulfilled, then this method will just return without executing the logic below.
[IsEligibleCheck]
public void CanAccessDatabase()
{
// do the logic
}
Eligibility is a runtime decision, of course.
Any idea on how to code up the logic for IsEligibleCheck ? Thanks
Edit: I know PostSharp can do this, but I am looking at something that works out of box, not depending on any third party library.
Any idea on how to code up the logic for IsEligibleCheck?
This is a perfect spot for AOP.
Edit: I know PostSharp can do this, but I am looking at something that works out of box, not depending on any third-party library.
Is Microsoft considered third-party? If not, you could look at Unity from their Patterns & Practices team. Look at the Interceptor mechanism in Unity.
Otherwise, you effectively have to roll your own implementation using reflection. Effectively what you have to do is wrap your objects in a proxy wherein the proxy uses reflection to check the attributes and interpret them appropriately. If IsEligibleCheck succeeds then the proxy invokes the method on the wrapped object. Really, it's easier to just reuse an already existing implementation.
My advice is just use Unity (or another AOP solution).
Unfortunately, attributes doesn't get executed at runtime. A handful of built-in attributes modify the code that gets compiled, like the MethodImpl attributes and similar, but all custom attributes are just metadata. If no code goes looking for the metadata, it will sit there and not impact the execution of your program at all.
In other words, you need that if-statement somewhere.
Unless you can use a tool like PostSharp, then you cannot get this done in out-of-the box .NET, without explicit checks for the attributes.
This looks like a perfect candidate for AOP. In a nutshell, this means that the CanAccessDatabase logic will live in an "aspect" or "interceptor", that is, separate from the business logic, thus achieving separation of concerns (the aspect is only responsible for security, business code is only responsible for business things).
In C#, two popular options for doing AOP are Castle.DynamicProxy and PostSharp. Each has its pros and cons. This question sums up their differences.
Here are other options for doing AOP in .Net, some of them can be done without 3rd-party libraries. I still recommend using either DynamicProxy, PostSharp, LinFu, Spring.AOP or Unity, other solutions are not nearly as flexible.
Custom attributes go hand in hand with Reflection.
You will need to create another class that is responsible for calling the methods in your CanAccessDatabase() class.
Using reflection, this new class will determine the attributes on each method. If the IsEligibleCheck attribute is found, it will perform the StatiClass.IsEligible() check and only call CanAccessDatabase() if the check passes.
Heres an introduction to doing this at MSDN. It revolves around using the MemberInfo.GetCustomAttributes() method.
Heres the pseudocode:
Get the Type of the CanAccessDatabase() class
Using this type, get all methods in this class (optionally filtering public, private etc).
Loop through the list of methods
Call GetCustomAttributes() on the current method.
Loop through the list of custom attributes
If the IsEligibleCheck attribute is found
If StaticClass.IsEligible is true
Call the current method (using MethodInfo.Invoke())
End If
End If
End Loop
End Loop
I know this is an old thread...
You can use the Conditional Attribute: http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx
"Indicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined."
#define IsEligibleCheck // or define elsewhere
[Conditional("IsEligibleCheck")]
public void CanAccessDatabase()
{
// do the logic
}
check AOP that will help you a lot in this, one of the powerful components in the market is PostSharp

Categories

Resources