![](/img/trans.png)
[英]Create object of main class which in turns instantiate its other member classes
[英]Reuse the log create in Main() in other classes
我通过以下方式在主类中定义我的日志:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.Enrich.FromLogContext()
.WriteTo.File(string.Format("log/log-{0}.txt",DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss")), outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{Method}) {Message}{NewLine}{Exception}")
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{Method}) {Message}{NewLine}{Exception}")
.CreateLogger();
但是,我的控制台应用程序的Main()
方法并不是我想记录的唯一地方。 我也想为我的其他类重用相同的日志文件,以便应用程序的每次运行都将创建一个文件,其中插入了来自该特定运行的不同类的所有日志。
我如何告诉一个类,例如DatabaseController
使用我在Main()
定义的相同日志?
1-避免拥有多个日志文件且只有全局文件的一种最佳方法是在类中声明Log.Logger
,因此类中的所有方法都将使用相同的日志,您也可以在当前的方法之外使用它如果你把它公之于众
这是一个例子:
class Program {
LoggerConfiguration ex = null; \\ or make it public if you want to call the log outside the local class
void Main(){
ex = new LoggerConfiguration()
.MinimumLevel.Information()
.Enrich.FromLogContext()
.WriteTo.File(string.Format("log/log-{0}.txt",DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss")), outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{Method}) {Message}{NewLine}{Exception}")
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{Method}) {Message}{NewLine}{Exception}")
.CreateLogger();
Method();
}
void Method() {
ex.WriteTo.File(string.Format("/"));
}
}
2-您还可以将日志文件作为参数发送到方法。
LoggerConfiguration ex = new LoggerConfiguration();
Method(ex);
并且方法参数应该是例如
int Method(LoggerConfiguration ex)
{
// rest of your code
return(0);
}
我认为 Serilog 默认使用静态全局记录器按照您想要的方式工作。 Log.Logger 进行设置,然后您就可以“使用 Serilog;” 在您的DatabaseController
类中,可以执行以下操作:
Log.Verbose("Hello World");
或者,如果您想要更多上下文:
using Serilog;
class DatabaseController
{
static ILogger logger = Log.ForContext<DatabaseController>();
public static void SomeMethod()
{
logger.Verbose("Hello World");
}
}
要么将写入已在Main()
定义的接收器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.