简体   繁体   中英

Log object's aggregation path using System.Diagnostics

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.

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));

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