Configuring NLOG 5 in kubernetes using splunk-connect in .net containers
Maybe you are using kubernetes and Splunk as your log aggregator. If your admin already installed splunk-connect-for-kubernetes you may want to log JSON to Splunk as it’s parsed automatically into browsable and editable objects.
I am going to show you how you easily can have a local nlog.config in your .net application, which logs in a human readable kind and automatically switches to JSON when you run your app in a kubernetes cluster. All this is simply done via a config map and an environment variable in your pod. Setting up nlog in your .net applicatoin is pretty simple and can be found on the projects home page:
Configmap in kubernetes
We are creating a simple configmap from an existing nlog.config file in kubernetes. The contents of your nlog.config should be configured as follows
In the end this nlog.config is pretty simple and just contains a console logger, which uses a JsonLayout to log in json format. In this example I configured some logging fields — feel free to adjust them to your needs (docs).
The rules section is configured for webapplications so it simply filters several system logs and the healthcheck logs, which are only shown if they are important.
Important is the final=”true” attribute in the both <logger name=”*”> entries. This tells nlog to not use any further logger for log entries handled by this logger. Therefore the application will just log one line of json and nothing more.
Build a deploy file via kubectl
To create a deployable configmap from this nlog.config file you can simply use kubectl and the build in features to create a new config map:
kubectl create configmap nlog --from-file=nlog.config --dry-run=client -o yaml > nlog.yaml
Now you can deploy your configmap to kubernetes
The local nlog.config in your .net application
Your .net application should have a local nlog.config, which can be adjusted via environment variables. The local nlog.config is in my case pretty simple and just logging coloured strings to the console.
The magic happens in line 9, where the environment is crawled for NLOG — this is the environment variable which we will use in our pod to point to the mapped nlog.config. If there is no environment variable present ./no.external.config would be mapped. As this file doesn’t exists the nlog configuration stays as it is.
Deploying your app and mount the json logging nlog.config
Your deployment file for kubernetes just need to mount the configfile created earlier to the local filesystem of your app and set the environement variable “NLOG” to point to the mounted file.
Therefore you have to define a volume for your new configmap “nlog” (line 21).
Mount the volume to your application via a volumeMount (line 29)
Set the environment variable NLOG to the local path of your nlog.config file (line 35)
That’s all happy logging!