Skip to content

Instantly share code, notes, and snippets.

@mizrael
Last active October 6, 2017 21:09
Show Gist options
  • Save mizrael/7d2adba86ec72da2217b3bf2a2881744 to your computer and use it in GitHub Desktop.
Save mizrael/7d2adba86ec72da2217b3bf2a2881744 to your computer and use it in GitHub Desktop.
using StructureMap to inject an typed NLog instance
public interface ILogger
{
void Log(LogLevel level, string text);
}
public enum LogLevel
{
Off = 0,
Trace,
Debug,
Info,
Warning,
Error
}
public class NLogLogger : ILogger
{
private readonly NLog.Logger _logger;
private readonly string _loggedClassname;
public NLogLogger(string loggedClassname)
{
_loggedClassname = loggedClassname;
_logger = LogManager.GetLogger(string.Empty);
}
public void Log(LogLevel level, string text)
{
var nlogLevel = NLog.LogLevel.Off;
switch (level)
{
case LogLevel.Error:
nlogLevel = NLog.LogLevel.Error;
break;
case LogLevel.Warning:
nlogLevel = NLog.LogLevel.Warn;
break;
case LogLevel.Info:
nlogLevel = NLog.LogLevel.Info;
break;
case LogLevel.Debug:
nlogLevel = NLog.LogLevel.Debug;
break;
case LogLevel.Trace:
nlogLevel = NLog.LogLevel.Trace;
break;
}
_logger.Log(new LogEventInfo(nlogLevel, _loggedClassname, text));
}
}
var container = new Container(cfg =>
{
cfg.For<ILogger>()
.Use<NLogLogger>()
.AlwaysUnique()
.Ctor<string>().Is(context =>
(null != context && null != context.ParentType) ? context.ParentType.FullName : string.Empty
);
});
container.AssertConfigurationIsValid();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment