我想在我的网站上记录错误。日志类需要IHostingEnvironment来获取日志文件路径。DI只工作构造函数,但是静态类没有构造函数。
我删除了静态构造函数和添加构造函数,但是现在当我启动日志类时,构造函数正在询问IHostingEnvironment参数。最后,我需要使用IHostingEnvironment所有控制器来使用日志类?
.net核心调用没有浏览器参数的Controller类。我怎样才能对日志课做同样的事呢?
目前的情况就是这样。
public class LogServices
{
public static void Log(string logMessage, IHostingEnvironment env)
{
string logName = env.WebRootPath + "\\Log\\Log_" + DateTime.Now.ToString("dd_MM_yyyy") + ".txt";
using (StreamWriter w = File.AppendText(logName))
{
w.Write("\r ");
w.WriteLine($" :{logMessage}");
}
}
}但我想要这样的东西:
public class LogServices
{
public static void Log(string logMessage,[FromServices] IHostingEnvironment env)
{
string logName = env.WebRootPath + "\\Log\\Log_" + DateTime.Now.ToString("dd_MM_yyyy") + ".txt";
using (StreamWriter w = File.AppendText(logName))
{
w.Write("\r ");
w.WriteLine($" :{logMessage}");
}
}
}如果这样做有效,我可以像这样调用日志文件
LogServices.Log("Error bal balblaa");但是很明显,它不能工作,因为LogServices.Log再次询问IHostingEnvironment参数。和第一个相似。
发布于 2019-08-23 22:05:36
不要使用静态类。将类注册为单例,并在构造函数中请求IHostingEnvironment。
public class LogServices
{
private readonly IHostingEnvironment _env;
public LogServices(IHostingEnvironment env)
{
_env = env;
}
public void Log(string logMessage)
{
string logName = _env.WebRootPath + "\\Log\\Log_" + DateTime.Now.ToString("dd_MM_yyyy") + ".txt";
using (StreamWriter w = File.AppendText(logName))
{
w.Write("\r ");
w.WriteLine($" :{logMessage}");
}
}
}然后在ConfigureServices方法中使用Startup.cs
services.AddSingleton<LogServices>();然后,在需要它的任何地方,都可以在构造函数中请求LogServices,然后它就会被注入。
但是您也可以考虑让它继承ILogger,并使用内置的日志框架。你可以读到它,这里。最大的好处是,每当您记录某件事时,它都会写到每个已注册的记录器上,而不仅仅是一个。因此,它仍然可以写入调试窗口以及您的自定义记录器,而不需要任何额外的代码。
不过,它涉及得更多一些。有一个完整的示例说明如何创建自己的日志记录提供程序来写入文件这里。
https://stackoverflow.com/questions/57633368
复制相似问题