Reputation: 651
I am using NLog to log errors into a file when they occur and I also log the payload in the body request. But I don't want to log the payload if, for example, an error occurred while authenticating, because I have a username and password there.
What are your solutions for this issue?
I use a generic class to handle my HttpClient requests.
private static async Task<ApiMethodResult<string>> SendGenericRequestAsync(this HttpClient client,
HttpMethod method,
string requestString, object payload = null)
{
HttpRequestMessage requestMessage = new HttpRequestMessage
{
RequestUri = new Uri(ConnectionUrl.ExternalUrl + requestString),
Method = method
};
if (payload != null && method != HttpMethod.Get)
{
HttpContent requestContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8,
"application/json");
requestMessage.Content = requestContent;
}
ApiMethodResult<string> result = new ApiMethodResult<string>();
HttpResponseMessage responseMessage;
try
{
responseMessage = await client.SendAsync(requestMessage);
}
catch (Exception)
{
string errorMessage = $"Cannot connect to external data API. Requested url: {requestString}";
result.SetErrorMessage(errorMessage);
StaticLogger.LogError(errorMessage);
return result;
}
string httpContent = await responseMessage.Content.ReadAsStringAsync();
result.ApiData = httpContent;
return result;
}
This is my nlog.config
<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Trace"
internalLogFile="C:\Users\albug\source\repos\orgill-vendor-portal-v2\InnerLog.txt">
<extensions>
<add assembly="NLog.Web.AspNetCore" />
</extensions>
<targets>
<target name="default" xsi:type="File"
fileName="LogFolderPath"
layout="Logger: ${logger}${newline}
Date: ${shortdate}${newline}
Time: ${time}${newline}
LogType: ${level}${newline}
URL: ${aspnet-request-url:IncludeQueryString=true}${newline}
Payload: ${aspnet-request-posted-body}${newline}
Controller: ${aspnet-mvc-controller}${newline}
Endpoint: ${aspnet-mvc-action}${newline}
Message: ${message}${newline}"/>
</targets>
<rules>
<logger name="*" minlevel="Warn" writeTo="default" />
</rules>
</nlog>
Upvotes: 1
Views: 518
Reputation: 651
Ok, so after a random search I actually found out that you can use a conditional operator-ish in the NLog layout.
What I did is this:
Payload: ${when:when='${aspnet-mvc-controller}'=='Account':inner=restricted:else=${aspnet-request-posted-body}}${newline}
So basically if the controller inside which the log action was triggered is "Account", it will put "restricted", else it will put the actual request body.
Here is the actual documentation.
${when:when=[condition to be verified]:inner=[what to log if true]:else=[what to print if not]}
Upvotes: 1