简体   繁体   中英

Best way to add logging in existing application (windows or web) .Net

I have inherited couple of .Net (C#) application which does not have any tracing or logging added to it. This application does everything from Creating , Reading , Updating and deleting records. It sends email and calls web services.

Of course it is a nightmare to maintain it because there is no logging and no try catch mechanism (I know I could not believe it either).

So what would be the best way of implementing logging in this system. I can not go to every function call and add logging lines. Is there some way where I can have dynamic logging which can log based on the method names I provide.

IE When UpdateOrder() is called , my logger should log (updated order method was called )

Thank you

Use log4net, it is the .NET version of the Apache log4j. The library is well tested, used by programmers everywhere, and is very customizable. Since you've inherited this code, it would not be a bad thing to go through it and start adding logging support.

The customization settings are handled through a global file within the project with can specify where the logging information goes (Emailed, text files, console) and what level of verbosity is needed per output source of the logging information.

You could use an AOP framework like Postsharp to create a specific attribute to log method calls :

public class TraceAttribute : OnMethodBoundaryAspect 
{ 
  public override void OnEntry( MethodExecutionEventArgs eventArgs) 
  { Trace.TraceInformation("Entering {0}.", eventArgs.Method);  } 

  public override void OnExit( MethodExecutionEventArgs eventArgs) 
  { Trace.TraceInformation("Leaving {0}.", eventArgs.Method);   } 
}

(this code is the example from the home page)

You can then apply this attribute to the methods you want to log :

[Trace]
public void UpdateOrder()
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM