I'm wondering if it's bad practice to use log4net directly on my domain object... I'll be using ELMAH for my exceptions on the ASP.NET MVC application side, but for some informational purposes I'd like to log some data about the domain model itself.

Given the following domain object:

   public class Buyer
{
    private int _ID;
    public int ID
    {
        get { return _ID; }
        set
        {
            _ID = value;
        }
    }

    private IList<SupportTicket> _SupportTickets=new List<SupportTicket>();
    public IList<SupportTicket> SupportTickets
    {
        get
        {
            return _SupportTickets.ToList<SupportTicket>().AsReadOnly();
        }
    }

    public void AddSupportTicket(SupportTicket ticket)
    {
        if (!SupportTickets.Contains(ticket))
        {
            _SupportTickets.Add(ticket);
        }
    }
}

Is adding logging behavior in the AddSupportTicketMethod a bad idea...so essentialy it'd look like this:

       public class Buyer
{
    protected static readonly ILog log = LogManager.GetLogger(typeof(SupportTicket));

    public Buyer()
    {
       log4net.Config.XmlConfigurator.Configure();
    }


    private int _ID;
    public int ID
    {
        get { return _ID; }
        set
        {
            _ID = value;
        }
    }

    private IList<SupportTicket> _SupportTickets=new List<SupportTicket>();
    public IList<SupportTicket> SupportTickets
    {
        get
        {
            return _SupportTickets.ToList<SupportTicket>().AsReadOnly();
        }
    }

    public void AddSupportTicket(SupportTicket ticket)
    {
        if (!SupportTickets.Contains(ticket))
        {
            _SupportTickets.Add(ticket);
        } else {
           log.Warn("Duplicate Ticket Not Added.");
        }
    }
}

Accepted Answer

If you are going to log from your domain objects and you use an IOC container which you might want to swap out, I would recommend you use the Service Locator pattern (you could look at the Sharp# architecture for a nice implementation of a SafeServiceLocator that wraps msoft's ServiceLocator with more informative error messages).

I would also like to suggest that you consider whether you want to log the type of error you show in your example. I would tend to want to have the domain object throw an exception in that case and let the caller decide whether that was something that was expected by the application (and hence shouldn't be logged) or whether that represents a situation that the caller wants to deal with in some way.

Written by Rob Scott
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki