5
votes

I have a local MongoDb database instance (created by running mongod from the Windows command line), and a simple console program that tries to log a string to the MongoDb database using Serilog and its MongoDb sink:

        var log = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.ColoredConsole()
            .WriteTo.MongoDB("mongodb://localhost/mydb")
            .CreateLogger();

        log.Fatal("Fatal message");

The "Fatal message" message is written correctly to the console, but not to my MongoDb database.

My current MongoDb database is "mydb". According to "show collections", I only have collections system.indexes and testData, and "db.testData.find()" produces nothing.

The Serilog site says to use connection string "mongo://mydb/log", but that throws an exception "An unhandled exception of type 'System.FormatException' occurred in MongoDB.Driver.dll". The connection string I used in my code is specified on the MongoDb site, at http://docs.mongodb.org/manual/reference/connection-string/

How can I log to MongoDb using Serilog?

3

3 Answers

6
votes

It's possible that you're just experiencing the default (two second?) buffering delay - if you close a console app in Windows it hard-terminates the program so buffers can't always be flushed. Waiting a few seconds before closing the app will fix this if so.

Otherwise, the way to tackle all sink debugging in Serilog is to set SelfLog.Out:

SelfLog.Out = Console.Error;

This will print any exceptions raised by the sink, allowing you to zoom in on the error pretty quickly if that's where it is.

2
votes

I took the answers by Nicholas and redwards (thanks to both of you!), did some more experimenting, and captured the results at: http://jsnlog.com/Documentation/GetStartedLogging/StructuredLogging

1
votes

Interesting, I was getting the exact same error until I switched the connection string to be

mongodb://myMachineName/mydb

Before, I had mongo://localhost/mydb.

But while mongo vs mongodb solved the Exception problem, it wasn't inserting records into mydb! So I changed it to

.WriteTo.MongoDB("mongodb://localhost/logs", restrictedToMinimumLevel: LogEventLevel.Verbose)

and now it is working! "logs" was created with "log" as a collection which held the JSON data.