Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog: cannot log to MongoDb using MongoDb sink

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?

like image 746
user1147862 Avatar asked Jul 12 '14 15:07

user1147862


3 Answers

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.

like image 195
Nicholas Blumhardt Avatar answered Nov 16 '22 20:11

Nicholas Blumhardt


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

like image 41
user1147862 Avatar answered Nov 16 '22 21:11

user1147862


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.

like image 1
redwards510 Avatar answered Nov 16 '22 22:11

redwards510