Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using log4net in a multi projects solution

What is the best practice in using log4net in a multi project solution. Do I install the log4net Nuget on every project? I there a way to create a logger in the infrastructure, that uses log4net? I will appreciate any ideas.

like image 371
tal Avatar asked Sep 17 '25 17:09

tal


1 Answers

Personally I prefer injecting my loggers via an IoC container. You can but you don't need to.

Just create an interface for your logging needs and put it on a project where your all projects have references to. (ie. Core)

public interface ILogger
{
    void Trace(string message);

    void Trace(string format, params object[] args);

    void Info(string message);

    void Error(string message);

    void Error(string message, Exception exception);

    void Error(Exception exception);
}

And now you can write an implementation for each logger library you want and switch if needed. But I've never seen a project where we change logging infrastructure.

My Nlog logger implementation for ILogger interface above.

using System;
using NLog;

namespace Tvinio.Core.Logging.NLog
{
    public class NLogger : ILogger
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        public void Trace(string message)
        {
            Logger.Trace(message);
        }

        public void Trace(string format, params object[] args)
        {
            Logger.Trace(format, args);
        }

        public void Info(string message)
        {
            Logger.Info(message);
        }

        public void Error(string message)
        {
            Logger.Error(message);
        }

        public void Error(string message, Exception exception)
        {
            Logger.Error(exception, message);
        }

        public void Error(Exception exception)
        {
            Logger.Error(exception);
        }
    }
}

Now if you just create an implementation for your log4net logger and initialize an instance of it, Visual Studio will carry references for you to all referenced project if they are using that implementation.

And also I strongly recommend reading about Dependency Injection too. You can find an article here. http://martinfowler.com/articles/injection.html

like image 178
Ömer Cinbat Avatar answered Sep 19 '25 06:09

Ömer Cinbat