Log object's aggregation path using System.Diagnostics

64 Views Asked by At

Imagine, there is a dependency between objects (and classes =) ):

class IrrelevantClass
{
    public IrrelevantClass(UserClass user)
    {
        _user = user;
    }

    public void InvokeUserClassMethod()
    {
        _user.UseDependencyClass();
    }

    private UserClass _user;
}

[Root]  // Log should trace all the dependencies since that root.
class UserClass
{
    public A(DependencyClass dependency)
    {
        _dependency = dependency;
    }

    public void UseDependencyClass()
    {
        // some computation...
        _dependency.MethodWithLogging();
    }

    private DependencyClass _dependency;
}

class DependencyClass
{
    public void MethodWithLogging()
    {
        Trace.TraceInformation("Very clever logging message.");
    }
}

How can I make the following code

DependencyClass dependency = new DependencyClass();
UserClass user = new UserClass(dependency);
IrrelevantClass irrelevantObject = new IrrelevantClass(user);
irrelevantObject.InvokeUserClassMethod();

result in a log message that looks like that:

17:12:04 - [UserClass] - [DependencyClass] - Information: Very clever logging message.

I have vague thoughts about the solution — probably it can be constructed from the stack trace.

1

There are 1 best solutions below

3
On

You have to call GetType().Name to get the class name that's it

  System.Diagnostics.EventLog appLog = 
        new System.Diagnostics.EventLog() ;
    appLog.Source = "My super program";
    appLog.WriteEntry(String.format("17:12:04 - [{0}] - [{1}] - Information: Very clever logging message.", this.GetType().Name, _dependency.GetType().Name));