To read more about basics of serilog and setting up project and SQL logging using Serilog please see my previous post Serilog SQL logging
Further in the same solution we will add below setting for file logging.
We will have to add one more setting to write to file in Serilog section in appsettings.json as below
{ "Name": "File", "Args": { "path": "c:\\Serilogs\\\\NkSerilogDemoLogs.log" } }
as we can see from above setting that we need to provide path of the log file along with filename in path parameter. Here I have provided absolute path. This path can be an absolute or relative path.
Now we have kept both SQL and File logging setting in appsettings.json so after running the application & generating error condition it will write logs to both SQL table & file as well. Below is the screenshot of logs written to the file.
Structure Logging
As you can see from above post it add logs in plain text. If you want structured logging in JSON format you just need to add formatter to setting defined above in appsettings.json.
Instead of modifying existing file setting let me add one more section so that we will have both logging to file in simple format and logging to file in JSON format.
{ "Name": "File", "Args": { "path": "C:\\Serilogs\\\\NkSerilogDemoLogs.log" } }, { "Name": "File", "Args": { "path": "C:\\Serilogs\\\\NkSerilogDemoJSONLogs.log", "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog" } }
Now if we run application and observe the second file log you can see it is logged as json as below.
You can also see the source code for this demo project on github source code
Hope it helps you.
If you have any queries/suggestions feel free to comment.
No comments:
Post a Comment