简体   繁体   English

Serilog记录到控制台但不记录

[英]Serilog logs to console but not to file

I have the below logger configuration and associated classes as below. 我有以下记录器配置和相关的类,如下所示。 The expected log messages are below: 预期的日志消息如下:

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

I see both the log messages in console. 我在控制台中看到了两条日志消息。 But I see only the first log in the file. 但我只看到文件中的第一个日志。

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

Thanks 谢谢

You will need to enable multi-process shared log files, set shared to true 您需要启用多进程共享日志文件,将shared设置为true

.WriteTo.File("log.txt", outputTemplate: logTemplate, shared: true)

Also no need to crate logger each time you need to log, Just create it one time on application start and use it everywhere in your application (Check below example). 每次需要记录时也不需要创建记录器,只需在应用程序启动时创建一次,并在应用程序的任何位置使用它(请查看下面的示例)。

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

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM