如果特定端点发生错误,请不要记录有效负载

时间:2019-08-02 09:06:08

标签: c# .net-core asp.net-core-webapi nlog

我正在使用NLog在错误发生时将错误记录到文件中,并且还将有效负载记录在主体请求中。但是,例如,在身份验证时发生错误时,我不想记录有效负载,因为我在那里有用户名和密码。

您对此问题有什么解决方案?

我使用通用类来处理HttpClient请求。

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;
        }

这是我的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>

1 个答案:

答案 0 :(得分:1)

好吧,所以在随机搜索之后,我实际上发现您可以在NLog布局中使用条件运算符。

这是我做的:

Payload: ${when:when='${aspnet-mvc-controller}'=='Account':inner=restricted:else=${aspnet-request-posted-body}}${newline}

因此,基本上,如果在其中触发了日志操作的控制器是“ Account”,它将放置“ restricted”,否则将放置实际的请求正文。

Here是实际的文档。

${when:when=[condition to be verified]:inner=[what to log if true]:else=[what to print if not]}