Serilog记录到控制台但不记录

问题描述 投票:1回答:1

我有以下记录器配置和相关的类,如下所示。预期的日志消息如下:

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");
        }
    }
}

谢谢

c# serilog
1个回答
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");

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.