Log whether any function is entered - c#

I have a WinForms app and I want to keep track of what buttons are clicked on. I figure I can put something like a Console.WriteLine("FUNCTION_NAME"); at the beginning of every function (of course, with FUNCTION_NAME replaced with the actual function's name). My question is: is there a better way? Some sort of programmatic way to grab the function name and do something with it when the function is run?

Usually, in WPF / MVVM, we'll have a base class for the logger that will use the CallerMemberNameAttribute , so you don't need to figure out the caller.
Instead of writing it out, you can use a logger (NLog, Log4net, etc), if you create the logger in the class, it will do part of the work automatically as well.
Here's a snippet. Note that this is done for automatic change notifications, but you can use the same for your purposes:
[NotifyPropertyChangedInvocator]
protected override void RaisePropertyChanged([CallerMemberName]string property = "")
{
base.RaisePropertyChanged(property);
}
just change the name of the functions obviously, and do what you need in it.

There is a way. Use CallerMemberNameAttribute. Example:
https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx#Anchor_7
EDIT:
Here is an example of AOP in C#:
https://msdn.microsoft.com/en-us/magazine/dn574804.aspx
But the performance will be severely degraded.

Related

C# Custom Logger - Best way to capture sending object

I am attempting to build (for learning purposes) my own event logger; I am not interested in hearing about using a non-.net frameworks instead of building my own as I am doing this to better understand .net.
The idea is to have an event system that I can write out to a log file and/or pull from while inside the program. To do this I am creating an LogEvent class that will be stored inside of a Queue<LogEvent>.
I am planning on using the following fields in my LogEvent class:
private EventLogEntryType _eventType //enum: error, info, warning...
private string _eventMessage
private Exception _exception
private DateTime _eventTime
What I am not sure is the best way to capture the object that caused the event to be called. I thought about just doing a private Object _eventObject; but I am thinking that is not thread safe or secure.
Any advice on how to best store the object that called the event would be appreciated. I am also open to any other suggestions you may have.
Thanks, Tony
First off, nothing wrong with writing your own. There are some good frameworks our there, but sometimes you reach the point where some bizarre requirement gets you rolling your own, I've been there anyway...
I don't think you should be using text messages. After doing this type of logging in several projects, I have come the the conclusion that the best approach is to have a set of event types (integer IDs) with some type of extra information field.
You should have an enum of LogEvetTypes that looks something like this:
public enum LogEventTypes
{
//1xxx WS Errors
ThisOrThatWebServiceError = 1001,
//2xxx DB access error
//etc...
}
This, from my experience will make your life much easier when trying to make use of the information you logged. You can also add an ExtraInformation field in order to provide event instance specific information.
As for the object that caused the event, I would just use something like typeof(YourClass).ToString();. If this a custom class you created, you can also implement a ToString override that will name sense in your logging context.
Edit: I am adding several details I wrote about in the comments, since I think they are important. Passing objects, which are not immutable, by ref to service methods is generally not a good idea. You might reassigne the same variable in a loop (for example) and create a bug that is near-impossible to find. Also, I would recommend doing some extra work now to decouple the logging infrastructure from the implementation details of the application, since doing this later will cause a lot of pain. I am saying this from my own very painful experience.

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

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.

What design pattern will you choose?

I want to design a class, which contains a procedure to achieve a goal.
And it must follow some order to make sure the last method, let's say "ExecuteIt", to behave correctly.
in such a case, what design patter will you use ?
which can make sure that the user must call the public method according some ordering.
If you really don't know what I am saying, then can you share me some concept of choosing a design patter, or what will you consider while design a class?
I believe you are looking for the Template Method pattern.
Template Method is what you want. It is one of the oldest, simply a formalization of a way of composing your classes.
http://en.wikipedia.org/wiki/Template_method_pattern
or as in this code sample:
abstract class AbstractParent // this is the template class
{
// this is the template method that enforces an order of method execution
final void executeIt()
{
doBefore(); // << to be implemented by subclasses
doInTheMiddle() // also to be implemented by subclasses
doLast(); // << the one you want to make sure gets executed last
}
abstract void doBefore();
abstract void doInTheMiddle();
final void doLast(){ .... }
}
class SubA extends AbstractParent
{
void doBefore(){ ... does something ...}
void doInTheMiddle(){ ... does something ...}
}
class SubB extends SubA
{
void doBefore(){ ... does something different ...}
}
But it seems you are fishing for an opportunity to use a pattern as opposed to use a pattern to solve a specific type of problem. That will only lead you to bad software development habits.
Don't think about patterns. Think about how you would go around solving that specific problem without having patterns.
Imagine there were no codified patterns (which is how it was before). How would you accomplish what you want to do here (which is what people did to solve this type of problems.) When you can do that, then you will be in a much better position to understand patterns.
Don't use them as cookie cutters. That is the last thing you want to do.
Its basically not a pattern, but: If you want to make sure, the code/methods are executes in a specific order, make the class having only one public method, which then calls the non-public methods in the right sequence.
The simple and pragmatic approach to enforcing a particular sequence of steps in any API is to define a collection of classes (instead of just one class) in such way that every next valid step takes as a parameter an object derived from the previous step, i.e.:
Fuel coal = CoalMine.getCoal();
Cooker stove = new Cooker (gas);
Filling apple = new AppleFilling();
Pie applePie = new Pie(apple);
applePie.bake(stove);
That is to say that to bake a pie you need to supply a Cooker object that in turn requires some sort of a suitable fuel to be instantiated first. Similarly, before you can get an instanse of a Pie you'd need to get some Filling ready.
In this instance the semantics of the API use are explicitly enforced by its syntax. Keep it simple.
I think you have not to really execute nothing, just prepare the statements, resources and whatever you want.
This way whatever would be the order the user invokes the methods the actual execution would be assured to be ordered; simply because you have the total control over the real execution, just before execute it.
IMHO Template Method as very little to do with your goal.
EDIT:
to be more clear. Make your class to have one public method Execute, and a number of other public methods to tell your class what to do (when to do it is a responsibility of you and not of the user); then make a number of private methods doing the real job, they will be invoked in the right order by your Execute, once the user has finished settings things.
Give the user the ability of setting, keep execution for your self. He tells what, you decide how.
Template Method is rational, if you have a class hierarchy and base class defines protected operation steps in its public template method. Could you elaborate your question?
As general concept you should choose a pattern as a standard solution to a standard problem so, I agree with Oded, the "Template Method" seems to fit your needs (but what you explained is too few maybe).
Don´t use pattern as "fetish", what you have to keep in mind is:
How can I figure my problem in a standard way?
There is a pattern for this?
Is this the simplest way?

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

Where do I put my C# delegate declaration, in a file of its own?

Out of habit I tend to put classes/structs/enumerations in separate files when not nested.
For delegates, it seems like overkill to create a seperate file for a one liner:
public delegate string MyDelegateThatIsNotNestedInAnyClass ( string par );
I usually add it to the bottom of the most closely related class file. I was just wondering what other people do?
I tend to put each type in a separate code file. Doing so will help you navigate in Solution Explorer, though ReSharper rocks with "Go To File"
(source: jetbrains.com)
and "Go To Type":
(source: jetbrains.com)
I usually add it to the .cs file of the class which implements the delegate function (at the namespace level). If there are several of these, I put it in a separate file.
If I know for sure that only one class will implement the delegate function, I nest it in the implementing class.
I personally add it before a closely related class definition. I make good use of namespaces, though, so I don't pollute!
If it's closely related enough to belong in the same file as the class, then you can probably justify nesting it in the class. Then you'll have no trouble remembering which class file it's in.
If there's no single class that's an obvious choice to nest in, creating the one-line file is probably worthwhile since you'll never waste time trying to remember which class file you decided to put it in.
I allways declare my own events, even if I don´t need them in the sence that a generic event would suffice. The reason for that is that the class name of the event gives the code so much more readability and also not seldom the declared event will be needed further down the road for some reason.
Since I have an event class, I allways put the delegate above the class declaration of the event. They are closely coupled and if you need to listen to the event then you´ll need both the event and the delegate. I don´t know if this violates some design rules of any kind, but this has worked nicely for me.
Usually, I just use:
Func<string, string>
these days

Categories

Resources