2

I have tons of functions in my WinForms project and i'm using NLog for logging. I want to have an ability to wrap each function with nlogger.Info("start") and nlogger.Info("end") so i will know in which place actual exception occurred or where the code currently runs.

Is there a smart way to do it or i will need to place lines from above in all of my functions ?

ccellar
  • 10,326
  • 2
  • 38
  • 56
eugeneK
  • 10,750
  • 19
  • 66
  • 101
  • 2
    The stack-trace will tell you where an exception happens... Just sayin' – Marc Gravell Nov 20 '11 at 08:21
  • You right but some of exceptions are without full stack and there are exceptions without stack at all. Moreover if some function is called twice during the run you wouldn't know which run caused an exception. – eugeneK Nov 20 '11 at 08:23

2 Answers2

3

I believe that PostSharp can do this for you, and can apply at the assembly level (via assembly-level attributes). However, I would be cautious of the potential performance impact. Writing the "aspect" should be pretty minimal.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Even you can do it for the external assemblies where you dont have source code http://stackoverflow.com/questions/3196865/postsharp-on-assemblies-i-dont-have-source-for – Surjit Samra Nov 20 '11 at 08:45
2

Ifyou don't want to do it manually - you could consider Aspect Oriented Programming.

To summarise what it is, it matches functions which run and offers 'advice' before, after or around. So you can easily make one which runs at all functions and adds to the log. Never used it for C# but I used it for Java.

You can find a class for .NET. Read this for more info:

http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/

Haedrian
  • 4,240
  • 2
  • 32
  • 53