Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the running method's name?

I'd like to write the name of the currently running method to a log. I know I can manually type the name of each method into the string being written to the log but I'd like something more automated and reusable. I assume this can be accomplished using reflection but I don't know where to start with this.

Any suggestions or code samples? Thanks!

like image 383
DenaliHardtail Avatar asked Nov 30 '25 17:11

DenaliHardtail


2 Answers

System.Reflection.MethodBase.GetCurrentMethod().Name should do the trick.

like image 155
Andrew Avatar answered Dec 03 '25 08:12

Andrew


Take a look at System.Diagnostics.StackTrace class

System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
string methodName = st.GetFrame(0).GetMethod().Name;

Keep in mind there is a performance cost here. You'll want to be careful using this in performance sensitive code.

like image 42
Zippit Avatar answered Dec 03 '25 09:12

Zippit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!