简体   繁体   English

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

[英]Log object's aggregation path using System.Diagnostics

Imagine, there is a dependency between objects (and classes =) ): 想象一下,对象(和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. 17:12:04-[UserClass]-[DependencyClass]-信息:非常聪明的日志消息。

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 您必须调用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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM