How To use AppSettings for a Production Ready Configuration of Serilog

For all the examples I showed you so far I wrote the configuration for Serilog directly in the code. That worked very well and only took a few lines of calls to the fluent API. This approach is great for a demo or a simple little application that doesn’t need to change.

In a more realistic setting your production is separated from your test environment. Not only are the servers different, but you need a different configuration as well. But changing the configuration in this case means recompile your application. A better way is the topic of today’s post.

 

Install AppSettings

Serilog has a package that will use your app.config or web.config file to store its configuration. Following this proven way to store the configuration makes it easy to change your settings whenever the need arise – without the need to recompile your application.

You can write your own code to read values from the configuration files. But Serilog has a prebuild package that will do all this work for you. You can install it using the NuGet frontend in Visual Studio or directly enter this command in the package manager console:

 

Use web.config

One last time you need to modify the code for your Serilog configuration. Only installing the package doesn’t tell Serilog that it should use it. You can remove all the specific configuration for Serilog and replace it with a call to the ReadAppSettings method:

In the web.config file you now need to add the same configuration as you had before in your code based configuration. To use your local Seq server as a sink you add the following lines to the appSettings section of your web.config (or app.config) file:

If you need to know more about the different keys you can use or how the system exactly works you should read the official documentation on AppSettings.

 

Change it for production

All the work we have done had a purpose: Being able to change the configuration without the need to recompile the application. To prove that this is possible you can follow this few steps:

  1. Stop your application
  2. Replace the localhost address with the IP of another machine running Seq
  3. Save the web.config file
  4. Start your application

Your log messages will now be written to the other Seq server. Should they not immediately show up you may have a firewall that blocks your messages.

 

Conclusion

Using the AppSettings package may be a little bit more work for the initial configuration. But as soon as you need to change the configuration this little extra work pays its dividend. Without the need to recompile you now that you have the same application in production that you had in your test environment. To know that is a value in itself.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.