[英]NLog with AutoFac - How to give logger name
我在我的項目中使用Autofac
作為 DI 工具,並使用NLog
進行日志記錄。
在將NLog
與Autofac
一起使用時,我遇到了指定記錄器名稱的問題。
這是我的代碼的鏈接。
如您所見,在 LoggerService.cs 中,第 11 行
我正在構造函數中創建記錄器的實例。 如何在那里注入記錄器 object 並將記錄器名稱作為 class 名稱?
任何幫助將不勝感激。
更新:我以前看過這個問題。 那是關於記錄消息中錯誤的callsite
信息。 我想知道如何使用正確的記錄器名稱在 class 中注入記錄器。
更新:在問題本身中添加相關代碼。
全局.asax.cs
using Autofac;
using Autofac.Integration.Mvc;
using System.Web.Mvc;
using System.Web.Routing;
using WebApplication2.Utils;
namespace WebApplication2
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ConfigureAutofac();
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
private void ConfigureAutofac()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<MailService>().As<IMailService>();
//builder.RegisterModule<NLogModule>();
builder.RegisterGeneric(typeof(LoggerService<>)).As(typeof(ILoggerService<>)).InstancePerDependency();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
家庭控制器.cs
using System.Web.Mvc;
using WebApplication2.Utils;
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
public IMailService mailService { get; set; }
public ILoggerService<HomeController> loggingService;
public HomeController(IMailService mailService, ILoggerService<HomeController> loggingService)
{
this.mailService = mailService;
this.loggingService = loggingService;
}
// GET: Home
public ActionResult Index()
{
loggingService.Debug("Log message from index method");
loggingService.Info("Some info log");
mailService.Send();
return View();
}
}
}
ILoggerService.cs
namespace WebApplication2.Utils
{
public interface ILoggerService<T>
{
void Info(string message);
void Debug(string message);
}
}
LoggerService.cs
using NLog;
namespace WebApplication2.Utils
{
public class LoggerService<T> : ILoggerService<T>
{
public ILogger logger { get; set; }
public LoggerService()
{
logger = LogManager.GetLogger(typeof(T).FullName);
}
public void Debug(string message)
{
logger.Debug(message);
}
public void Info(string message)
{
logger.Info(message);
}
}
}
在注冊您的服務時使用RegisterGeneric
,如下所示。
builder.RegisterGeneric(typeof(LoggerService<>)).As(typeof(ILoggerService<>)).InstancePerRequest();
您始終可以使用 LogManager 獲取記錄器。 看起來像這樣
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.