Best way to write any id in every log entry in my .net standard library

92 Views Asked by At

My fully developed library has multiple logging entries for debug , error and info etc. Now I want to append any id say <12asdf> in all of my log entries for specific methods:

Library:

public class YourLibrary{
    public void Test(){
        log.entry();
         .
         .
        log.debug();
         .
         .
        log.exit();
    }
}

Application:

var mylib = new YourLibrary();
mylib.Test();

So now whenever any log is entered it should append the id in all the logs for my specific methods. Suggest a possible way so as to not change any of the log entries in the library. Any idea if this can be achieved using callback. Thanks in advance.

1

There are 1 best solutions below

0
Olivier Jacot-Descombes On

You can use the CallerMemberNameAttribute to automatically get the name of the calling method and use it as id.

In your logging class:

public void Entry([CallerMemberName]string caller = default)
{
    // TODO: write to the log.
}

At the call sites you don't have to supply this parameter which is optional (because of = default). The C# compiler will supply it for you.