SerilogFactory不记录我的消息,但记录异常

时间:2019-07-03 16:23:23

标签: servicestack serilog

我想使用SerilogFactory,在初始化AppHost之前初始化LogFactory。 这是我的startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        var logger = new LoggerConfiguration().WriteTo.File("log.txt").CreateLogger();
        LogManager.LogFactory = new SerilogFactory(logger);

        app.Map("/api", api =>
        {
            api.UseServiceStack(new AppHost(env.ApplicationName, Configuration));
        });
   }
}

这是我的示例服务:

public class TestService : ServiceStack.Service
{
    public static ILog Log = LogManager.GetLogger(typeof(TestService));

    public bool Get(GetTest request)
    {
        Log.Info("foo");
        Log.Warn("???");

        throw new System.Exception("plop");

        return true;
    }
}

调用“ GetTest”请求后,我可以在“ log.txt”文件中看到异常的详细信息,但是看不到信息“ foo”或“ Warm” ????在文件中。

2019-07-03 18:07:55.597 +02:00 [INF] Initializing Application Tmpi.PocketTournee took 352.2006ms. No errors detected.
2019-07-03 18:08:07.446 +02:00 [ERR] ServiceBase<TRequest>::Service Exception
System.Exception: plop
at Tmpi.PocketTournee.ServiceInterface.TestService.Get(GetTest request) in C:\Projects\VS2017\PocketTournee\WebService\Sources\Tmpi.PocketTournee.ServiceInterface\TestService.cs:line 15

如果在初始化AppHost之后初始化LogFactory,则可以看到自己的日志,但是这次异常详细信息和servicestack初始化信息已消失:

2019-07-03 18:25:05.420 +02:00 [INF] foo
2019-07-03 18:25:05.434 +02:00 [WRN] ???

1 个答案:

答案 0 :(得分:1)

因此,我设置了一些断点来观察LogManager.LogFactory的类型:
注册第一个LogFactory之前,LogManager.LogFactory的类型为 ServiceStack.Logging.NullLogFactory
*注册第一个LogFactory后,LogManager.LogFactory的类型当然是 ServiceStack.Logging.Serilog.SerilogFactory ,这里没有错
*但是在AppHost初始化之后,LogManager.LogFactory的类型将还原为 ServiceStack.NetCore.NetCoreLogFactory

类似于此代码:

        var logFactory = new SerilogFactory(new LoggerConfiguration()
            .WriteTo.File("log.txt")
            .CreateLogger());

// Here LogManager.LogFactory is {ServiceStack.Logging.NullLogFactory}

        LogManager.LogFactory = logFactory;

// Here LogManager.LogFactory is {ServiceStack.Logging.Serilog.SerilogFactory}

        app.Map("/api", api =>
        {
            api.UseServiceStack(new AppHost(env.ApplicationName, Configuration));
        });

// Here LogManager.LogFactory is {ServiceStack.NetCore.NetCoreLogFactory}

        LogManager.LogFactory = logFactory;