C
C#2mo ago
exceptive

Looking for a logging solution

I'm trying to figure out how to log my SQL or database commands into a configurable JSON file. This is for a school assignment, Ive tried adding events to each query, I don't fully understand it still this is the main criteria: Database commands shall be logged. The log file location shall be configurable in a manner similar to the database connection string. The log shall be in JSON format:
7 Replies
surf68
surf682mo ago
How are you running your SQL? EF? ADO.NET?
exceptive
exceptiveOP2mo ago
SQL is on a local sql server db, everything is already initialized besides the logging using mms if that matters
surf68
surf682mo ago
I'm more asking what your code looks like to execute SQL.
exceptive
exceptiveOP2mo ago
private void LoadData(string connectionString) { string query = "SELECT * FROM railroad"; try { using (var connection = new SqlConnection(connectionString)) using (var adapter = new SqlDataAdapter(query, connection)) { DataTable dataTable = new DataTable(); adapter.Fill(dataTable); if (dataTable.Rows.Count > 0) { dataGridView1.DataSource = dataTable; } else { MessageBox.Show("No data found in the table.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception ex) { MessageBox.Show($"Error loading data: {ex.Message}", "Data Load Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Jimmacle
Jimmacle2mo ago
serilog can be configured to log to json
surf68
surf682mo ago
Alright so that's pure ADO.NET. Unfortunately, there's no logging mechanism that you can hook into so you're going to have to add the logging yourself. Given this is for a school assignment I assume the application isn't particularly large? If so, I'd suggest tackling things in the following order. - Pick one method and get it logging its query to a hard-coded JSON file - Work on adding configuration for where to write that JSON file - Expand this out to all of the other places you're running SQL I'm not sure if you're allowed to use external packages or not but if you are you could look into using Serilog which is a very common logging package. This'll give you a pretty basic solution to the problem but it isn't particularly scalable. Taking it further you could look into adapters around a connection but only you can say whether or not that is what your class is looking for.
Jimmacle
Jimmacle2mo ago
is there a specific format required for the json?
Want results from more Discord servers?
Add your server