I don't think what you're describing is necessarily tightly coupled
This of course couples the logging library with other code - other code still has to be aware of how the logging library works (that it wants the string, name, & level)
Not exactly. The consuming code won't need to know how the logging library works. It'll simply need to know what is expected of a logging library. In other words, consuming code only needs to know about the logging library's public interface.
If your language supports it, you can guarantee looser coupling by forcing the consuming code to work against a Logger Interface (as opposed to the Logger implementation).
This is considered loosely coupled because there is only one --clearly defined-- point of contact between the Logger library and the consuming code. This is the Logger Interface.
If in the future you decided to swap out your Logger for a new-fangled modern logger, then all you would need to do is code a compatibility layer between your new Logger lib and your existing Logger Interface. Loose coupling to the max ;)
In C#:
Your logger interface:
public interface ILogger
{
void Log(String filename, String message, Level level);
void Log(String filename, Exception exception, Level level);
void Log(String message, Level level);
void Log(Exception exception, Level level);
void LogInfo(String message);
void LogWarning(String message);
void LogError(String error);
void LogError(Exception error);
// etc...
}
A specific implementation of ILogger
public class AbcLogger : ILogger
{
// Implements all of ILogger
public void LogWarning(String message)
{
this.abcTarget.Write(message, AbcLevelsEnum.Warning)
}
}
Code consuming a Logger
public void SomeMethod(int a)
{
if (a < 1000)
{
String message = "Quantities of fewer than 1000 bananas are not accepted";
ILogger logger = ServiceLocator.GetMeMyLogger();
logger.LogWarning(message);
throw new BananaException(message);
}
// do more...
}
As you can see, the consuming code isn't aware it's dealing with AbcLogger
. All it knows is that a logger is available and that it can be used by going throw the ILogger
interface.
And this way, if you ever want to switch to another logger like this one...
public class XyzLogger : ILogger
{
// Implements all of ILogger
public void LogWarning(String message)
{
this.xyzTarget.Flush();
this.xyzTarget.OtherPreRequisites();
this.xyzTarget.Write(message, XyzLevel.NonCritical)
this.xyzTarget.Flush();
this.xyzTarget.OtherPostRequisites();
}
}
...it's just a matter of changing your application's bootstrapping code to use XyzLogger
instead of AbcLogger
.
public Bootstrapping()
{
ServiceLocator.SetLogger(new XyzLogger());
ServiceLocator.SetBananaManager(new BananaManaga());
// ... etc
}