Search code examples
c#.netmongodbserilog

Unable to log using Serilog MongoDb sink


We have our dev mongodb server in AWS. I'm able to insert data using Mongo Shell and the C# driver. However, i'm unable to do so using the Serilog MongoDb sink.

Working code using direct 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);

Non-working code using 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);

Moreover, i'm not getting any exception which is not helping.

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

Solution

  • 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.

    This means, whenever possible, Serilog will swallow exceptions. If you need your logger to throw when it fails, you can use new LoggerConfiguration().AuditTo… instead of new LoggerConfiguration().WriteTo….

    In your case I'd guess the problem is this: .WriteTo.MongoDB(…, period: TimeSpan.Zero). The PeriodicBatchingSink that the MongoDB sink inherits from throws when its period is less than or equal to zero.

    Then if it still doesn't work I would check your batchPostingLimit argument. By default it's 50, meaning you have to emit 50 log messages before it will send them. Set it to 1 to send each log message immediately.