Added request logger

This commit is contained in:
Alex
2025-01-16 13:09:38 +00:00
parent 62f917b325
commit 8284c17855
10 changed files with 104 additions and 38 deletions
+7
View File
@@ -0,0 +1,7 @@
namespace Core.Servers.Http;
// This is a dummy class to use for SourceContext in Serilog, do not remove!
public class RequestLogger
{
}
+26 -21
View File
@@ -18,6 +18,7 @@ public class SptHttpListener : IHttpListener
protected readonly HttpRouter _router;
protected readonly IEnumerable<ISerializer> _serializers;
protected readonly ISptLogger<SptHttpListener> _logger;
protected readonly ISptLogger<RequestLogger> _requestLogger;
protected readonly HttpResponseUtil _httpResponseUtil;
protected readonly LocalisationService _localisationService;
protected readonly JsonUtil _jsonUtil;
@@ -25,7 +26,7 @@ public class SptHttpListener : IHttpListener
HttpRouter httpRouter, // TODO: delay required
IEnumerable<ISerializer> serializers,
ISptLogger<SptHttpListener> logger,
// TODO: requestsLogger: ISptLogger,
ISptLogger<RequestLogger> requestsLogger,
JsonUtil jsonUtil,
HttpResponseUtil httpHttpResponseUtil,
LocalisationService localisationService
@@ -34,6 +35,7 @@ public class SptHttpListener : IHttpListener
_router = httpRouter;
_serializers = serializers;
_logger = logger;
_requestLogger = requestsLogger;
_httpResponseUtil = httpHttpResponseUtil;
_localisationService = localisationService;
_jsonUtil = jsonUtil;
@@ -135,7 +137,8 @@ public class SptHttpListener : IHttpListener
SendZlibJson(resp, output, sessionID);
}
// Console.WriteLine($"Response: {output}");
// TODO: this.LogRequest(req, output);
LogRequest(req, output);
}
/**
@@ -152,28 +155,17 @@ public class SptHttpListener : IHttpListener
* @param req Incoming message request
* @param output Output string
*/
/* TODO: log requests
protected logRequest(req: IncomingMessage, output: string): void {
//
if (ProgramStatics.ENTRY_TYPE !== EntryType.RELEASE) {
const log = new Response(req.method, output);
this.requestsLogger.info(`RESPONSE=${this.jsonUtil.serialize(log)}`);
}
protected void LogRequest(HttpRequest req, string output)
{
// TODO: when do we want to log these?
//if (ProgramStatics.ENTRY_TYPE !== EntryType.RELEASE) {
var log = new Response(req.Method, output);
_requestLogger.Info($"RESPONSE={_jsonUtil.Serialize(log)}");
//}
}
*/
public string GetResponse(string sessionID, HttpRequest req, string? body)
{
/* TODO: REQUEST LOGGER
if (ProgramStatics.ENTRY_TYPE !== EntryType.RELEASE) {
// Parse quest info into object
const data = typeof info === "object" ? info : this.jsonUtil.deserialize(info);
const log = new Request(req.method, new RequestData(req.url, req.headers, data));
this.requestsLogger.info(`REQUEST=${this.jsonUtil.serialize(log)}`);
}
*/
var output = _router.GetResponse(req, sessionID, body, out var deserializedObject);
/* route doesn't exist or response is not properly set up */
if (string.IsNullOrEmpty(output)) {
@@ -181,6 +173,14 @@ public class SptHttpListener : IHttpListener
_logger.Info(_jsonUtil.Serialize(deserializedObject));
output = _httpResponseUtil.GetBody<object?>(null, 404, $"UNHANDLED RESPONSE: {req.Path}");
}
/* TODO: REQUEST LOGGER
if (ProgramStatics.ENTRY_TYPE !== EntryType.RELEASE) {
*/
// Parse quest info into object
var log = new Request(req.Method, new RequestData(req.Path, req.Headers, deserializedObject));
_requestLogger.Info($"REQUEST={_jsonUtil.Serialize(log)}");
//}
return output;
}
@@ -209,5 +209,10 @@ public class SptHttpListener : IHttpListener
resp.StartAsync().Wait();
resp.CompleteAsync().Wait();
}
record Response(string Method, string jsonData);
record Request(string Method, object output);
record RequestData(string Url, object Headers, object Data);
}
+3 -2
View File
@@ -1,5 +1,6 @@
namespace Core.Utils.Cloners;
public interface ICloner {
public T Clone<T>(T obj);
public interface ICloner
{
public T? Clone<T>(T? obj);
}
+1 -1
View File
@@ -10,7 +10,7 @@ public class JsonCloner : ICloner
{
_jsonUtil = jsonUtil;
}
public T Clone<T>(T obj)
public T? Clone<T>(T? obj)
{
return _jsonUtil.Deserialize<T>(_jsonUtil.Serialize(obj));
}
+1 -2
View File
@@ -128,9 +128,8 @@ public class DatabaseImporter : OnLoad
{
_logger.Info(_localisationService.GetText("importing_database"));
var dataToImport = (DatabaseTables) await _importerUtil.LoadRecursiveAsync(
var dataToImport = await _importerUtil.LoadRecursiveAsync<DatabaseTables>(
$"{filePath}database/",
typeof(DatabaseTables),
OnReadValidate
);
+10 -1
View File
@@ -20,12 +20,21 @@ public class ImporterUtil
_jsonUtil = jsonUtil;
}
public Task<T> LoadRecursiveAsync<T>(
string filepath,
Action<string, string>? onReadCallback = null,
Action<string, object>? onObjectDeserialized = null
)
{
return LoadRecursiveAsync(filepath, typeof(T), onReadCallback, onObjectDeserialized).ContinueWith(res => (T) res.Result);
}
/**
* Load files into js objects recursively (asynchronous)
* @param filepath Path to folder with files
* @returns Promise<T> return T type associated with this class
*/
public Task<object> LoadRecursiveAsync(
protected Task<object> LoadRecursiveAsync(
string filepath,
Type loadedType,
Action<string, string>? onReadCallback = null,
+1
View File
@@ -60,6 +60,7 @@ public static class Program
}
catch (Exception ex)
{
Console.WriteLine(ex);
logger.LogCritical(ex, "Critical exception, stopping server...");
// throw ex;
}
+1
View File
@@ -37,6 +37,7 @@
</ItemGroup>
<ItemGroup>
<Folder Include="user\logs\" />
<Folder Include="user\mods\" />
</ItemGroup>
+46 -10
View File
@@ -14,9 +14,53 @@
"Args": {
"configure": [
{
"Name": "Console",
"Name": "Logger",
"Args": {
"formatter": "Server.Logger.ConsoleFormatter::Default, Server"
"configureLogger": {
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "StartsWith(SourceContext, 'Core.Servers.Http.RequestLogger')"
}
}
],
"WriteTo": [
{
"Name": "Console",
"Args": {
"formatter": "Server.Logger.ConsoleFormatter::Default, Server"
}
}
]
}
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "StartsWith(SourceContext, 'Core.Servers.Http.RequestLogger')"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"formatter": "Server.Logger.FileFormatter::Default, Server",
"path": "./user/logs/requests.txt",
"fileSizeLimitBytes": "20971520",
"rollOnFileSizeLimit": true,
"rollingInterval": "Day"
}
}
]
}
}
},
{
@@ -33,14 +77,6 @@
}
}
],
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "StartsWith(SourceContext, 'TADAADA')"
}
}
],
"Enrich": [
"FromLogContext",
"WithExceptionDetails"
+8 -1
View File
@@ -2,7 +2,6 @@
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
@@ -20,4 +19,12 @@
<ProjectReference Include="..\Core\Core.csproj"/>
</ItemGroup>
<ItemGroup>
<Folder Include="Tests\Mock\" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Tests\Mock\MockSptLogger.cs" />
</ItemGroup>
</Project>