Writing logs into SQL Server with NLog and .Net 6.0 (part 3)

Matt Ghafouri
CodeBoulevard
Published in
2 min readApr 4, 2022

--

In our previous articles, We talked about writing applications’ logs into Elastic via NLog and .Net 5.0.

If you haven't read those articles, I highly recommend you to read those firstly, because All information you may need about NLog configuration is already elaborated in the articles, and also we checked some authentication exceptions when ELK requires an application to be authenticated.

For writing Logs in NLog, several targets could be defined. There are tens of targets that can be used. Check this link for all Targets.

Now, In order to write logs into a SQL Server table, firstly you need to install this package.

System.Data.SqlClient

Then a table should be defined in SQL Server (either via TSQL command or SQL Server Management Wizard).

Now time to add a new target in the NLog.config file

And as the final step set LogLevel for the new target

</rules>

<logger name=”*” minlevel=”Error” writeTo=”SQLDatabase” />

</rules>

That’s all. from now on you can have your application error logs in both ELK and SQL Server. (Just take into consideration that with this configs, only the error logs will be written into targets, in case you need to capture different types of log(Trace, Information, Critical, etc), just minLevel need to be changed

Here, is the complete version of the nlog.config

Final Thought

Log management is one of the most primitive aspects of software development, and because of the high load system, they need to be tracked and monitored in case of any failure in the system. having a central and powerful logging mechanism helps development teams and also DevOps.

Having a better understanding of the application performance. ELK with that fancy dashboard helps a lot in order to have a brief look at the application performance status.

sometimes teams need to have your applications’ logs in a relational database like SQL Server. With the help of NLog, we can prepare a good infrastructure for the logging via several logs data sources like LogStach, SQL Server, Console, etc.

If you want to support me, please share this article with your community.

--

--