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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With