Umbraco 8 comes with a new logging framework, serilog. In this tutorial, you will learn all about Serilog, how to access the logs, and how to write your custom messages to the logs. Historically, Umbraco V7 and earlier used Log4Net. Log4Net is a great logger, however, it is very limited in terms of searching the logs. Everything was stored within a text file with a .log extension. To search the logs you would need to manually scroll through the logs to find things yourself, painful!

Out of the box, V8 now writes to a JSON log file. As logs are stored in JSON, you will have more power when searching them. It is now possible to search logs within the CMS. The default log file location can be found within 'App_Data/Logs' and contains the name of the machine that created the log and its entry date:

We can write code to query JSON simply. The same can not be said when querying data within a flat-file structure. Compare this file to its JSON equivalent.

In this JSON file, we can filter logs on properties like SourceContext, ProcessName and Log4NetLevel

Within the dashboard of V8, there is now a log viewer that will allow you to do just this. You can now view all your logs and errors inside of the CMS rather than having to access the server manually.

How To Hook Into The Umbraco Logs

As you would expect, you can also write to the Umbraco Logs. The code to write a custom message to the logs is shown below:

One tip that you should be aware of when writing log messages with Serilog is around parameters. Avoid using string interpolation, or string concatenation when you write to the log. Using either method will result in the parameter not being added to the log file correctly. To see what I mean, let us compare= these different approaches of writing to the log file:

All these approaches are simply writing a parameter to the log files. All will work, however, the outputted logs will vary. The good practice techniques will give you better logging. Using string interpolation, or string concatenation will result in two log files being generated within your logs:

Compare this with this example:

Comparing the results, you can see the second approach contains more information. By using the + operator, all the parameters will be logged separately with the name in the correct format. This will greatly help you whenever you are debugging. It is much easier to find parameters by their actual name, rather than an unhelpful parameter name of '@1'.

Another useful thing to note is that all the Umbraco controllers expose the logger. If you are using either RenderMvcController, SurfaceController, UmbracoApiController, or, UmbracoAuthorizedApiController then you can use the 'Logger' property anywhere in your code:

If you are working in a class that is not inheriting from one of these types, then you can access the logger via dependency injection:

Happy Coding!