无法使用 Serilog MongoDb 接收器进行记录

Unable to log using Serilog MongoDb sink

我们在 AWS 中有我们的开发 mongodb 服务器。我可以使用 Mongo Shell 和 C# 驱动程序插入数据。但是,我无法使用 Serilog MongoDb 接收器。

使用直接 MongoDb C# 的工作代码 API:

var client = new MongoClient("mongodb://<server>");
var database = client.GetDatabase("logs");

var collection = database.GetCollection<BsonDocument>("prj");

List<string> LogData = new List<string>();
LogData.Add("requestxml");
LogData.Add("responsexml");
var document = new BsonDocument {
    { "TraceID", "123" },
    { "ModuleName", "Booking" },
    { "MethodName", "" },
    { "LogFormat", "JSON" },
    { "LogDescription", "Sample description" },
    { "LogType", "RequestResponse" },
    { "LogData", string.Join(",", LogData) }
};

collection.InsertOne(document);

使用 Serilog 的非工作代码:

var log = new LoggerConfiguration()
    .WriteTo.MongoDB("mongodb://<server>/logs", collectionName: "prj", period: TimeSpan.Zero)
    .CreateLogger();

List<string> LogData = new List<string>();
LogData.Add("requestxml");
LogData.Add("responsexml");

log.Information("{TraceID} {ModuleName} {ClassName} {MethodName} {LogFormat} {LogDescription} {LogType} {@LogData}", "2431", "CT", "", "", "JSON", "Booking", "RequestResponse", LogData);

此外,我没有收到任何没有帮助的异常。

.NET Framework: 4.5.2
Serilog: 2.8.0
MongoDb Driver: 2.9.2
Serilog MongoDb Sink: 4.0.0

Serilog takes the view that, all things considered, logging is a lower priority than other application code and should never avoidably impact the operation of a running application.

这意味着,只要有可能,Serilog 就会吞下异常。如果你需要你的记录器在失败时抛出,你可以使用 new LoggerConfiguration().AuditTo… 而不是 new LoggerConfiguration().WriteTo….

在你的情况下,我猜问题是这样的:.WriteTo.MongoDB(…, period: TimeSpan.Zero)。 MongoDB 接收器从 throws when its period is less than or equal to zero.

继承的 PeriodicBatchingSink

然后,如果它仍然不起作用,我将检查您的 batchPostingLimit 参数。默认情况下它是 50,这意味着您必须发出 50 条日志消息才能发送它们。将其设置为 1 以立即发送每条日志消息。