使用 Cyber​​source .Net Client Library 执行事务搜索时出现 NLOG 错误

Getting NLOG Error when performing transaction search with Cybersource .Net Client Library

当 运行 .createSearch 时出现以下错误。

{System.Exception:错误:在 NLog.config 中找不到名称为 'file' 的目标 在 AuthenticationSdk.util.LogUtility..ctor(字符串 enableLog、字符串 logDirectory、字符串 logFileName、字符串 logFileMaxSize)

我正在尝试在 2019 年 7 月 31 日之前迁移到新的 REST API 系统。虽然我已经设置了一个工作系统,但无法克服这个错误,因为我从一天回来离开。我已将我的代码缩减为大部分可以在此处找到的示例:

https://github.com/CyberSource/cybersource-rest-samples-csharp/tree/master/src/Samples/TransactionSearch/CoreServices

public List<CyberSourceTransaction> GetTransactionsRest(DateTime? startDate, DateTime? endDate)
        {
            try
            {
                var requestObj = new CreateSearchRequest()
                {
                    Save = false,
                    Name = "ADS",
                    Timezone = "America/Chicago",
                    Query = "submitTimeUtc:[NOW/DAY-7DAYS TO NOW/DAY+1DAY}",
                    Offset = 0,
                    Limit = 10,
                    Sort = "id:asc, submitTimeUtc:asc"
                };

                var configDictionary = new Configuration().GetConfiguration();
                var clientConfig = new CyberSource.Client.Configuration(merchConfigDictObj: configDictionary);
                var apiInstance = new SearchTransactionsApi(clientConfig);
                var result = apiInstance.CreateSearch(requestObj);


            }
            catch (Exception e)
            {
                Console.WriteLine("Exception on calling the API: " + e.Message);
            }

            List<CyberSourceTransaction> list = new List<CyberSourceTransaction>()
            return list;
        }
public class Configuration
    {
        // initialize dictionary object
        private readonly Dictionary<string, string> _configurationDictionary = new Dictionary<string, string>();

        public Dictionary<string, string> GetConfiguration()
        {

            if (!GlobalVariables.InDebugMode)
            {
                _configurationDictionary.Add("merchantID", "test");
                _configurationDictionary.Add("merchantsecretKey", "/key=");
                _configurationDictionary.Add("merchantKeyId", "code");
                _configurationDictionary.Add("runEnvironment", "cybersource.environment.sandbox");
            }
            else
            {
                _configurationDictionary.Add("merchantID", "pro");
                _configurationDictionary.Add("merchantsecretKey", "/key=");
                _configurationDictionary.Add("merchantKeyId", "code");
                _configurationDictionary.Add("runEnvironment", "cybersource.environment.production");
            }
            _configurationDictionary.Add("authenticationType", "HTTP_SIGNATURE");
            _configurationDictionary.Add("enableLog", "FALSE");
            _configurationDictionary.Add("logDirectory", string.Empty);
            _configurationDictionary.Add("logFileName", string.Empty);
            _configurationDictionary.Add("logFileMaxSize", "5242880");
            _configurationDictionary.Add("timeout", "300000");
            _configurationDictionary.Add("proxyAddress", string.Empty);
            _configurationDictionary.Add("proxyPort", string.Empty);




            return _configurationDictionary;
        }
    }

期待 200 响应,但尝试捕获以下错误:

{System.Exception: Error:  No Target with the name 'file' found in NLog.config
   at AuthenticationSdk.util.LogUtility..ctor(String enableLog, String logDirectory, String logFileName, String logFileMaxSize)
   at AuthenticationSdk.util.LogUtility.InitLogConfig(String enableLog, String logDirectory, String logFileName, String logFileMaxSize)
   at AuthenticationSdk.core.MerchantConfig..ctor(IReadOnlyDictionary`2 merchantConfigDictionary)
   at CyberSource.Client.ApiClient.CallAuthenticationHeaders(String requestType, String requestTarget, String requestJsonData)
   at CyberSource.Client.ApiClient.PrepareRequest(String path, Method method, Dictionary`2 queryParams, Object postBody, Dictionary`2 headerParams, Dictionary`2 formParams, Dictionary`2 fileParams, Dictionary`2 pathParams, String contentType)
   at CyberSource.Client.ApiClient.CallApi(String path, Method method, Dictionary`2 queryParams, Object postBody, Dictionary`2 headerParams, Dictionary`2 formParams, Dictionary`2 fileParams, Dictionary`2 pathParams, String contentType)
   at CyberSource.Api.SearchTransactionsApi.CreateSearchWithHttpInfo(CreateSearchRequest createSearchRequest)
   at CyberSource.Api.SearchTransactionsApi.CreateSearch(CreateSearchRequest createSearchRequest)
   at ARCANA.ObjectLibrary.CyberSourceConnect.GetTransactionsRest(Nullable`1 startDate, Nullable`1 endDate) in C:\aogcode15\ARCANA Project\ARCANA\ARCANA.ObjectLibrary\Library\CyberSourceConnect.cs:line 131}

编辑(添加 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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <variable name="myvar" value="myvalue"/>

  <targets>

    <target xsi:type="File" name="file" fileName="${basedir}/logs/${shortdate}.log"
                layout="${longdate} ${uppercase:${level}} ${message}" />

  </targets>

  <rules>

  </rules>
</nlog>

编辑(根据以下内容将行添加到 app.config:) https://github.com/CyberSource/cybersource-rest-client-dotnet/issues/42#issuecomment-514780709

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" ... />
    <sectionGroup name="applicationSettings" ...>
      <section name="ARCANA.ObjectLibrary.Properties.Settings"... />
    </sectionGroup>
    <section name="MerchantConfig" type="System.Configuration.NameValueFileSectionHandler" />
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <applicationSettings>
    <ARCANA.ObjectLibrary.Properties.Settings>
      <setting name="ARCANA_ObjectLibrary_com_cvent_api_V200611" serializeAs="String">
       ...
      </setting>
    </ARCANA.ObjectLibrary.Properties.Settings>
  </applicationSettings>
  <MerchantConfig>
    <!--HTTP_SIGNATURE and JWT-->
    <add key="authenticationType" value="HTTP_SIGNATURE" />
    <add key="merchantID" value="..." />
    <add key="runEnvironment" value="api.cybersource.com" />
    <add key="timeout" value="100000" /><!--In Millisec-->
    <!--Log Related-->
    <add key="enableLog" value="true" />
    <add key="logFileMaxSize" value="835435" />
    <!--In bytes-->
    <!--<add key="logDirectory" value=""/>-->
    <!--<add key="logFileName" value="cybs.log"/>-->
    <!--Proxy Settings-->
    <!--<add key="proxyAddress" value="userproxy.com"/>
      <add key="proxyPort" value=""/>-->
    <!--JWT Parameters-->
    <add key="keyAlias" value="testrest" />
    <add key="keyPass" value="testrest" />
    <!--P12 File Parameters-->
    <add key="keysDirectory" value="Resource" />
    <add key="keyFilename" value="testrest" />
    <!--HTTP_Signature Parameters-->
    <add key="merchantsecretKey" value="/...=" />
    <add key="merchantKeyId" value="..." />
  </MerchantConfig>

  <nlog 
    xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" 
    autoReload="true" throwExceptions="false" internalLogLevel="Off" 
    internalLogFile="c:\temp\nlog-internal.log">


    <variable name="myvar" value="myvalue" />

    <targets>


      <target name="file" xsi:type="File" layout="${longdate} ${message}" fileName="${basedir}/logs/cybs.log" keepFileOpen="false" archiveAboveSize="5242880" archiveNumbering="Date" archiveDateFormat="yyyymmddhhmmss" encoding="iso-8859-2" />
   </targets>

    <rules>
      <logger name="*" minlevel="Trace" writeTo="file" />
    </rules>
  </nlog>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="RestSharp" ..." culture="neutral" />
        <bindingRedirect oldV.="0.0.0.0-106.6.10.0" newV.="106.6.10.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

同样的问题仍然存在。

事实证明我们为 NLog 设置了一个配置。我只是找不到它。对于那些可能有类似设置的人,我做了以下操作。

在我的 Nlog 解决方案中搜索。我发现我们的日志记录设置使用的是 Nlog:

提供的 loggingConfiguration class

https://nlog-project.org/documentation/v4.0.0/html/T_NLog_Config_LoggingConfiguration.htm

然后我使用配置 class 添加了以下内容:

 FileTarget fileTarget = new FileTarget();
 fileTarget.Name = "file";
 fileTarget.Layout = "${longdate} ${message}";
 fileTarget.FileName = "${basedir}/logs/cybs.log";
 fileTarget.KeepFileOpen = false;
 fileTarget.ArchiveAboveSize = 5242880;
 fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date;
 fileTarget.ArchiveDateFormat = "yyyymmddhhmmss";
 fileTarget.Encoding = Encoding.ASCII;
 config.AddTarget("file", fileTarget);

我们设置了一个日志以转到数据库。我不确定我是否可以告诉 Cyber​​source SDK 我想将日志发送到哪个目标,但上述解决方法至少让我可以继续前进。完成我的项目后(紧迫的期限)。如果我找到指向特定目标而不是使用默认 'file' 目标的方法,我将对此进行更新。