提问人:Amitava Karan 提问时间:4/17/2017 最后编辑:marc_sAmitava Karan 更新时间:3/8/2022 访问量:5777
NLog with AutoFac - 如何为记录器命名
NLog with AutoFac - How to give logger name
问:
我在我的项目中用作 DI 工具并用于日志记录。Autofac
NLog
我在使用 时遇到指定记录器名称的问题。NLog
Autofac
这是我的代码的链接。
如您所见,在 LoggerService.cs 中,第 11 行
我正在构造函数中创建记录器的实例。如何在那里注入记录器对象并获取记录器名称作为类名?
任何帮助将不胜感激。
更新:我以前见过这个问题。这是关于记录消息中的错误信息。我想知道如何在类中注入具有正确记录器名称的记录器。callsite
更新:在问题本身中添加相关代码。
全局.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);
}
}
记录器服务 .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);
}
}
}
答:
0赞
Rehan Shaikh
7/1/2020
#1
在注册您的服务时使用,如下所示。RegisterGeneric
builder.RegisterGeneric(typeof(LoggerService<>)).As(typeof(ILoggerService<>)).InstancePerRequest();
-1赞
Alan_Jin
3/8/2022
#2
您可以随时使用 LogManager 获取记录器。看起来像这样
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
评论
private static readonly Log = LogManager.GetLogger(typeof(CurrentType));