Zach Smith
Zach Smith

Reputation: 8961

Is it possible to listen for function calls in C# (i.e. treat C# function calls as events)?

I would like to log when functions in my app are called. Is there a way I can listen for functions called and run code on such events?

If so, where do I start looking at how to do this?

Upvotes: 2

Views: 2005

Answers (3)

ainwood
ainwood

Reputation: 1048

What do you want to do this for? Is it for performance profiling, or because you want to execute something when (for example) a function has been called x times?

If its for performance profiling, if you're using Visual Studio, the IDE has some built-in profiling functions. Under the "Debug" menu, there is the "performance Profiler" (Alt+F2). Running that on your application can give you a lot of detail about what is being called, how many time, how much CPU load etc etc. Particularly useful if you generate the "Create Detail Report" once it has run.

It's a bit hard to interpret, but if you're interested in how much time is being spent doing various functions in your application, it can be very useful.

Upvotes: 1

mason
mason

Reputation: 32694

Just do the work to insert your logging directly where you want it.

public class MyClass
{
    private ILogger _logger;

    public MyClass(ILogger logger)
    {
        _logger = logger;
    }

    public void DoSomething()
    {
        logger.Information("Something happened");
    }
}

This will allow you to customize the logging needs to your class - especially if you use something like Serilog in concert with SEQ.

I doubt the Aspect Oriented Logging approach will really allow you to get a nice useful semantic logging experience.

Upvotes: 4

Srikanth Venugopalan
Srikanth Venugopalan

Reputation: 9049

If you do not want to scatter your methods with log, consider using an AOP(Aspect Oriented Programming) library to do so.

Here is a blog illustrating this.

Upvotes: 1

Related Questions