使用System.Diagnostics记录对象的聚合路径

时间:2015-08-06 15:16:22

标签: c# logging aggregation system.diagnostics tracelistener

想象一下,对象(和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.");
    }
}

如何制作以下代码

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

会生成如下所示的日志消息:

  

17:12:04 - [UserClass] - [DependencyClass] - 信息:非常聪明的记录消息。

我对解决方案有一些模糊的想法 - 可能它可以从堆栈跟踪中构建。

1 个答案:

答案 0 :(得分:0)

你必须调用GetType()。Name来获取它的类名

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