我具有以下记录器配置和相关的类,如下所示。预期的日志消息如下:
2019-03-06 19:49:56.417 +05:30 [INFORMATION] [Main] Start
2019-03-06 19:49:56.435 +05:30 [INFORMATION] [Test1] Test1 logg
我在控制台中看到两个日志消息。但是我只看到文件中的第一个日志。
namespace SerilogTest
{
public static class MyLogger
{
public static ILogger getLogger(String className)
{
string logTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u}] [{SourceContext}] {Message}{NewLine}{Exception}";
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(outputTemplate: logTemplate)
.WriteTo.File("log.txt", outputTemplate: logTemplate)
.CreateLogger()
.ForContext("SourceContext", className);
return Log.Logger;
}
}
public class Program
{
private static ILogger Log = MyLogger.getLogger("Main");
private static void Main(String[] args)
{
Log.Information("Start");
Test1 t1 = new Test1();
Console.ReadKey();
}
}
public class Test1
{
private static ILogger Log = MyLogger.getLogger(typeof(Test1).Name);
public Test1()
{
Log.Information("Test1 logg");
}
}
}
谢谢
答案 0 :(得分:3)
您将需要启用多进程共享日志文件,将shared
设置为true
.WriteTo.File("log.txt", outputTemplate: logTemplate, shared: true)
此外,您无需在每次登录时都创建板条记录器,只需在应用程序启动时创建一次即可,并在应用程序中的任何地方使用它(请参见下面的示例)。
public static class MyLogger
{
public static void CreateLogger()
{
String logTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u}] [{SourceContext}] {Message}{NewLine}{Exception}";
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console(outputTemplate: logTemplate)
.WriteTo.File("log.txt", outputTemplate: logTemplate)
.CreateLogger();
}
}
class Program
{
static void Main(String[] args)
{
MyLogger.CreateLogger();
Log.ForContext("SourceContext", "Main").Information("Start");
Test1 t1 = new Test1();
Console.ReadKey();
}
}
class Test1
{
public Test1()
{
Log.ForContext("SourceContext", typeof(Test1).Name).Information("Test1 logg");
}
}