无法使用Serilog MongoDb接收器记录

时间:2019-09-12 09:52:33

标签: c# .net mongodb serilog

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

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

ST_Cluster*

使用Serilog的非工作代码:

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

此外,我没有遇到任何无助的例外。

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

1 个答案:

答案 0 :(得分:1)

  

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可立即发送每条日志消息。