Search code examples
c#unity-containerunity-interception

How to use C# Unity Interception to log inbetween calls


I am currently using Unity Interceptor to implement a logging mechanism, but I cannot correctly log the information.

When I call MethodA, MethodA and MethodB is logged, but i cannot tell whether the MethodB log is due to MethodA, or some other MethodB call.

My question is how can i implement some sort of Id to link them together

expected:

[Id: 001] Method A is called

[Id: 001] Method B is called

[Id: 001] Method B completed

[Id: 001] Method A completed

current:

[Id: 001] Method A is called

[Id: 002] Method B is called

[Id: 002] Method B completed

[Id: 001] Method A completed

public class A() {
    [Log]
    public void MethodA() {
        var b = new B();
        b.MethodB();
    }
}

public class B() {
    [Log]
    public void MethodB () {
         // some action B
    }
}

Solution

  • You can use the CallContext to store some id and output it in the logs. The main problem will be to identify the root of a call, if you don't want to always log the id of public static void main...

    If MethodA is always root, it works like this:

    public class A() {
        [Log]
        public void MethodA() {
            CallContext.SetLogicalData( "log-id", Guid.New().ToString() )
            var b = new B();
            b.MethodB();
        }
    }
    
    public class B() {
        [Log]
        public void MethodB () {
        // some action B
        }
    }
    
    //...
    public void Log( string message )
    {
        _backEnd.Write( $"[Id: {CallContext.GetLogicalData( "log-id" )}] {message}" );
    }