feature/logging #3

Merged
ProfessionalUwU merged 2 commits from feature/logging into main 2023-06-29 19:01:40 +02:00
4 changed files with 55 additions and 2 deletions

View File

@ -44,3 +44,18 @@ Run executable
```bash ```bash
./Chksum ./Chksum
``` ```
## Enabling verbose output for troubleshooting
1. Open the file called chksum.cs with your editor of choice.
2. At the top there will be the logger configuration which you can change. Should look like this.
```cs
private ILogger logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Error)
.WriteTo.File("chksum.log")
.CreateLogger();
```
3. Change the minimum level of the logger to Verbose.
4. Compile the program
5. Profit. Now you will be able to see how what the program is doing in detail.

View File

@ -18,6 +18,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="7.0.8" /> <PackageReference Include="Microsoft.Data.Sqlite" Version="7.0.8" />
<PackageReference Include="Serilog" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -2,11 +2,20 @@ using System.Collections.Concurrent;
using System.Reflection; using System.Reflection;
using System.Security.Cryptography; using System.Security.Cryptography;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Serilog;
using Serilog.Events;
namespace Chksum.Utils; namespace Chksum.Utils;
public class ChksumUtils { public class ChksumUtils {
private ILogger logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Error)
.WriteTo.File("chksum.log")
.CreateLogger();
private int getTotalFileCount() { private int getTotalFileCount() {
int totalFileCount = Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories).Length; int totalFileCount = Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories).Length;
logger.Debug("Total file count is {totalFileCount}", totalFileCount);
return totalFileCount - 3; // Remove the program, datbase and library from the totalFileCount return totalFileCount - 3; // Remove the program, datbase and library from the totalFileCount
} }
@ -14,12 +23,14 @@ public class ChksumUtils {
string[] indexedFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories); string[] indexedFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories);
string[] filesToExclude = { "Chksum", "chksum.db", "libe_sqlite3.so" }; string[] filesToExclude = { "Chksum", "chksum.db", "libe_sqlite3.so" };
indexedFiles = indexedFiles.Where(file => !filesToExclude.Contains(Path.GetFileName(file))).ToArray(); indexedFiles = indexedFiles.Where(file => !filesToExclude.Contains(Path.GetFileName(file))).ToArray();
logger.Information("All files were indexed");
return indexedFiles; return indexedFiles;
} }
public string DatabaseRoot { get; set; } = string.Empty; public string DatabaseRoot { get; set; } = string.Empty;
public void getBaseDir() { public void getBaseDir() {
DatabaseRoot = AppDomain.CurrentDomain.BaseDirectory; DatabaseRoot = AppDomain.CurrentDomain.BaseDirectory;
logger.Debug("DatabaseRoot is {DatabaseRoot}", DatabaseRoot);
} }
public string libraryPath { get; set; } = string.Empty; public string libraryPath { get; set; } = string.Empty;
@ -31,7 +42,9 @@ public class ChksumUtils {
byte[] buffer = new byte[resourceStream.Length]; byte[] buffer = new byte[resourceStream.Length];
resourceStream.Read(buffer, 0, buffer.Length); resourceStream.Read(buffer, 0, buffer.Length);
File.WriteAllBytes(libraryPath, buffer); File.WriteAllBytes(libraryPath, buffer);
logger.Debug("libe_sqlite3.so was successfully created");
} else { } else {
logger.Error("libe_sqlite3.so could not be loaded");
throw new Exception(libraryPath + " could not be loaded"); throw new Exception(libraryPath + " could not be loaded");
} }
} }
@ -39,6 +52,7 @@ public class ChksumUtils {
public void initializeDB() { public void initializeDB() {
if (File.Exists("chksum.db")) { if (File.Exists("chksum.db")) {
logger.Information("A database already exits");
return; return;
} }
@ -57,6 +71,7 @@ public class ChksumUtils {
); );
"; ";
command.ExecuteNonQuery(); command.ExecuteNonQuery();
logger.Information("Database was successfully created");
} }
} }
@ -68,6 +83,7 @@ public class ChksumUtils {
vacuum; vacuum;
"; ";
command.ExecuteNonQuery(); command.ExecuteNonQuery();
logger.Debug("Database was successfully vacuumed");
} }
} }
@ -87,12 +103,14 @@ public class ChksumUtils {
} }
}); });
logger.Debug("All files were checksummed");
return new Dictionary<string, string>(checksums); return new Dictionary<string, string>(checksums);
} }
public void doTheThing() { public void doTheThing() {
using (var connection = new SqliteConnection("Data Source=" + DatabaseRoot + "chksum.db;Mode=ReadWrite")) { using (var connection = new SqliteConnection("Data Source=" + DatabaseRoot + "chksum.db;Mode=ReadWrite")) {
if (getTotalFileCount() < 1) { if (getTotalFileCount() < 1) {
logger.Information("There were no files to checksum");
return; return;
} }
connection.Open(); connection.Open();
@ -115,8 +133,10 @@ public class ChksumUtils {
command.Parameters.AddWithValue("$filename", fileName); command.Parameters.AddWithValue("$filename", fileName);
command.Parameters.AddWithValue("$pathtofile", pathToFile); command.Parameters.AddWithValue("$pathtofile", pathToFile);
command.ExecuteNonQuery(); command.ExecuteNonQuery();
logger.Verbose("{fileName} which is located at {pathToFile} relative to the database with the hash {fileHash} was successfully inserted into the database", fileName, pathToFile, fileHash);
} }
} }
logger.Information("All files were successfully written to the database");
} }
} }
@ -141,9 +161,11 @@ public class ChksumUtils {
pathtofile = reader.GetString(1); pathtofile = reader.GetString(1);
} }
} }
logger.Verbose("{pathToFile} with the hash {fileHash} was successfully loaded", pathToFile, fileHash);
} }
if (fileHash == filehash) { if (fileHash == filehash) {
logger.Verbose("File with filehash {filehash} already exists in the database", filehash);
doesExist = true; doesExist = true;
} }
return doesExist; return doesExist;
@ -186,6 +208,7 @@ public class ChksumUtils {
Console.WriteLine($"\tto \t{pathtofile}\n"); Console.WriteLine($"\tto \t{pathtofile}\n");
wasMoved = true; wasMoved = true;
} }
logger.Verbose("{fileName} which is located at {pathToFile} relative to the database with the hash {fileHash} was successfully checked", fileName, pathToFile, fileHash);
} }
return wasMoved; return wasMoved;
} }
@ -207,6 +230,7 @@ public class ChksumUtils {
pathToFile = reader.GetString(0); pathToFile = reader.GetString(0);
if (File.Exists(pathToFile)) { if (File.Exists(pathToFile)) {
logger.Verbose("{pathToFile} exists", pathToFile);
continue; continue;
} }
var deleteCommand = connection.CreateCommand(); var deleteCommand = connection.CreateCommand();
@ -220,8 +244,10 @@ public class ChksumUtils {
Console.WriteLine("File deleted:"); Console.WriteLine("File deleted:");
Console.WriteLine($"\t{pathToFile}\n"); Console.WriteLine($"\t{pathToFile}\n");
logger.Verbose("File deleted: {pathToFile}", pathToFile);
} }
} }
logger.Information("All deleted files were successfully removed from the database");
} }
} }
@ -247,10 +273,16 @@ public class ChksumUtils {
} }
} }
logger.Debug("All filehashes were successfully retrived from the database");
return filehashesFromDatabase; return filehashesFromDatabase;
} }
public void compareDatabases(string filePathToOtherDatabase) { public void compareDatabases(string filePathToOtherDatabase) {
if (!File.Exists(filePathToOtherDatabase)) {
logger.Error("No database could be found at {filePathToOtherDatabase}", filePathToOtherDatabase);
throw new Exception("No database could be found at " + filePathToOtherDatabase);
}
List<string> filesThatDoNotExistsInTheRemote = getFilehashesFromDatabase("Data Source=" + DatabaseRoot + "chksum.db;Mode=ReadOnly").Except(getFilehashesFromDatabase("Data Source=" + filePathToOtherDatabase + ";Mode=ReadOnly")).ToList(); List<string> filesThatDoNotExistsInTheRemote = getFilehashesFromDatabase("Data Source=" + DatabaseRoot + "chksum.db;Mode=ReadOnly").Except(getFilehashesFromDatabase("Data Source=" + filePathToOtherDatabase + ";Mode=ReadOnly")).ToList();
foreach (string file in filesThatDoNotExistsInTheRemote) { foreach (string file in filesThatDoNotExistsInTheRemote) {
@ -272,13 +304,16 @@ public class ChksumUtils {
Console.WriteLine("File not found in remote:"); Console.WriteLine("File not found in remote:");
Console.WriteLine($"\t{filename}\n"); Console.WriteLine($"\t{filename}\n");
logger.Verbose("{filename} could not be found in the remote database", filename);
} }
} }
} }
} }
logger.Information("Compared both databases successfully");
} }
public void cleanup() { public void cleanup() {
File.Delete(libraryPath); File.Delete(libraryPath);
logger.Debug("Successfully deleted libe_sqlite3.so");
} }
} }