使用带有 ServiceStack.Logging.Serilog 的自定义接收器?

Using a custom sink with ServiceStack.Logging.Serilog?

是否有一种非显而易见的方式(至少对我而言)来添加自定义接收器,例如MongoDB 或 MicrosoftTeams 作为在 ServiceStack 框架中实例化 Serilog 工厂的一部分,还是会滚动您自己的工厂并实施 ILog?

PM> Install-Package ServiceStack.Logging.Serilog

LogManager.LogFactory =  new SerilogFactory();

ServiceStack Logging

Serilog

Example: MongoDB Sink

这在不使用 ServiceStack 实现的情况下工作,但它被认为是错误的形式吗?

public override void Configure(Container container)
{
    Log.Logger = new LoggerConfiguration()
        .WriteTo.MongoDBCapped("mongodb://mymongourl:27017/mylogs",
            collectionName: "mycollectionoflogs", cappedMaxSizeMb: 50,
            cappedMaxDocuments: 10000)
        .CreateLogger();

    SetConfig(new HostConfig
    {
        DefaultRedirectPath = "/metadata",
        DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)              
    });
}

并且在 ServiceInterface 消息实现中:

public object Any(MyRequest request)
{
    Log.Information("I'm a lumberjack and I'm OK");

    return new MyRequestResponse
    {
        Result = $"{ results.Chop() }"
    };
}

我刚刚添加了构造函数重载以在 this commit, this change is available from v5.1.1 that's now available on MyGet 中使用自定义 Serilog 记录器。

通过此更改,您可以使用 ServiceStack 的 SerilogFactory 传递自定义 Serilog 记录器,例如:

LogManager.LogFactory = new SerilogFactory(new LoggerConfiguration()
    .WriteTo.MongoDBCapped("mongodb://mymongourl:27017/mylogs",
        collectionName: "mycollectionoflogs", cappedMaxSizeMb: 50,
        cappedMaxDocuments: 10000)
    .CreateLogger());

您可以像在您的示例中一样直接使用 Serilog 记录器,除了它无法捕获 ServiceStack 的内置日志或以后无法用任何其他 ServiceStack loggers.