C ++ RAII Replication in C #

I run my own log class and want to introduce a log hierarchy as the application moves through the various steps:

log start
    loading
        loaded 400 values
    processing
         couldn't process var "x"

and etc.

In C ++ (yes, I know), I would use RAII class classes, which pushed themselves to the log stack when it was created and popped up when they left the area. Then you can leave the functions at any time and still have a consistent registration.

Obviously, in C # any variable must be new'd, so it will not be deleted until the next garbage collection cycle, and if you immediately create a new classlet, you can have a non-root logger.

How will people try to solve this problem in C #? I want the logger syntax to be as unobtrusive as possible for the current function and still support multi-exit functions.

The only solution I can think of about my head is because closeHeirarchy () calls every return statement - and you know that I will skip it somewhere.


Edit: I should clearly indicate that what interests me mainly is how you will replicate RAII behavior in C #. Is there a mechanism that provides identical behavior?

+3
source share
3 answers

You can get the behavior you are asking for if you use the statement with the IDisposable class.

- :

public class LogContext: IDisposable
{
  private readonly Logger _logger;
  private readonly string _context;

  public LogContext(Logger logger, string context){
    _logger = logger;
    _context = context;
    _logger.EnterContext(_context);
  }

  public void Dispose(){
    _logger.LeaveContext(_context);
  }
}

//...

public void Load(){
  using(new LogContext(logger, "Loading")){
    // perform load
  }
}
+5

OffTopic: , , Aspect Oriented Programming, . , , , (log4Net, NLog, System.Trace Spring.Commonlogging).

+3

System.Diagnostics.Traceworth a look. For example, it supports things like the indentation level. The log4net project is also worth checking out.

+1
source

Source: https://habr.com/ru/post/1702146/


All Articles