You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
recyclarr/src/TrashLib/Extensions/FlurlLogging.cs

66 lines
1.9 KiB

using Flurl;
using Flurl.Http.Configuration;
using Newtonsoft.Json;
using Serilog;
namespace TrashLib.Extensions;
public static class FlurlLogging
{
public static void SetupLogging(FlurlHttpSettings settings, ILogger log, Func<Url, Url>? urlInterceptor = null)
{
urlInterceptor ??= SanitizeUrl;
settings.BeforeCall = call =>
{
var url = urlInterceptor(call.Request.Url.Clone());
log.Debug("HTTP Request: {Method} {Url}", call.HttpRequestMessage.Method, url);
LogBody(log, call.RequestBody);
};
settings.AfterCallAsync = async call =>
{
var statusCode = call.Response?.StatusCode.ToString() ?? "(No response)";
var url = urlInterceptor(call.Request.Url.Clone());
log.Debug("HTTP Response: {Status} {Method} {Url}", statusCode, call.HttpRequestMessage.Method, url);
var content = call.Response?.ResponseMessage.Content;
if (content is not null)
{
LogBody(log, await content.ReadAsStringAsync());
}
};
settings.OnRedirect = call =>
{
log.Warning("HTTP Redirect received; this indicates a problem with your URL and/or reverse proxy: {Url}",
urlInterceptor(call.Redirect.Url));
call.Redirect.Follow = false;
};
}
private static void LogBody(ILogger log, string? body)
{
if (body is null)
{
return;
}
body = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(body));
log.Debug("HTTP Body: {Body}", body);
}
public static Url SanitizeUrl(Url url)
{
// Replace hostname and API key for user privacy
url.Host = "hostname";
if (url.QueryParams.Contains("apikey"))
{
url.QueryParams.AddOrReplace("apikey", "SNIP");
}
return url;
}
}