63 lines
1.8 KiB
C#
63 lines
1.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Diagnostics;
|
|
using System.Text.Json;
|
|
|
|
namespace QtCNETAPI.Services
|
|
{
|
|
public class LoggingService : IDisposable
|
|
{
|
|
private DateTime LogDate { get; set; }
|
|
private string LogFilePath { get; set; }
|
|
private StreamWriter LogFile { get; set; }
|
|
public LoggingService()
|
|
{
|
|
LogDate = DateTime.Now;
|
|
LogFilePath = $"./Logs/QtCClientLog_{LogDate:ddMMyyy-hhmm}.log";
|
|
|
|
// create log file
|
|
|
|
if (!Directory.Exists("./Logs")) Directory.CreateDirectory("./Logs");
|
|
LogFile = new StreamWriter(File.Create(LogFilePath));
|
|
|
|
Debug.WriteLine($"Log File Created At {LogFilePath}");
|
|
}
|
|
|
|
public void LogString(string message)
|
|
{
|
|
try
|
|
{
|
|
Debug.WriteLine($"({DateTime.Now.ToLocalTime():hh:mm}) {message}");
|
|
LogFile.WriteLine($"({DateTime.Now.ToLocalTime():hh:mm}) {message}");
|
|
} catch (ObjectDisposedException)
|
|
{
|
|
}
|
|
}
|
|
|
|
public void LogModel<T>(T model)
|
|
{
|
|
try
|
|
{
|
|
// serialize the model as json
|
|
string modelSerialized = JsonSerializer.Serialize(model, options: new JsonSerializerOptions { WriteIndented = true });
|
|
|
|
// log it
|
|
Debug.WriteLine($"({DateTime.Now.ToLocalTime():hh:mm}) {modelSerialized}");
|
|
LogFile.WriteLine($"({DateTime.Now.ToLocalTime():hh:mm}) {modelSerialized}");
|
|
} catch (ObjectDisposedException)
|
|
{
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
LogFile.WriteLine("--- END OF LOG ---");
|
|
LogFile.Close();
|
|
LogFile.Dispose();
|
|
}
|
|
}
|
|
}
|