tags:

views:

44

answers:

2

Hello I have the following problem:

ComponentA with Unique Name
   ChildComponent
      ChildChild
   AnotherChild

Everytime a new instance of ComponentA is created I want to redirect the output to a unique file named ComponentA-UniqueName including all child component log entries.

How can this be achieved?

Daniel

+1  A: 

Out of the box, dynamically changing appenders is hard to do. I would consider logging to a different medium, like a database table, that enables filtering and grouping log data.

Update:

Using contexts you can provide per-instance information across instance boundaries. Consider the following implementations:

class ComponentA
{
    public void DoStuff()
    {
        using(log4net.ThreadContext.Stacks["component"].Push(this.Id))
        {
            childComponent.DoStuff();
        }
    }
}

class ChildComponent
{
    public void DoStuff()
    {
        using(log4net.ThreadContext.Stacks["component"].Push(this.Id))
        {
            childChild.DoStuff();
        }
    }
}

Whenever messages are logged (regardless of which component does the logging), the current context stacks are included. In your appender configuration, use the %property{component} formatter to output the content of the component stack which will include ids of both the ComponentA instance and the ChildComponent instance.

Peter Lillevold
See my link below
Daniel Marbach
@Daniel: nice. Though I'm still not sure why you cannot do this using the logger hierarchy that is already built-in. Of course, output to unique files is a challenge. But again, I would rather consider a database for this job since it would be trivial to select and group on whatever data you choose to log.
Peter Lillevold
Hy peter,When using a database the problem remains the same. I need to uniquely identify the log source according to a component. So I need to give the loggers in my component hierarchy meaningful names according to their instance data to distinguish them in the database. Logger per class wouldn't work.
Daniel Marbach
I see. Think I misunderstood your problem initially. See my updated answer, I believe you could use the context stuff, though I understand you have something working now..
Peter Lillevold
A: 

I have a solution which works pretty fine for us:

http://gist.github.com/387423

Daniel

Daniel Marbach