asp.net-mvcresttransactionsnlogcybersource

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


When running .createSearch I get the following error.

{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)

I am attempting to move to new REST API systems by drop off date 31 July 2019. I though I had a working system set up but unable to get past this error since I got back from a day off. I have reduced my code to the example that can be found here for the most part:

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

Expecting a 200 response but the try is catching the following error:

{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:\aogcode\2015\ARCANA Project\ARCANA\ARCANA.ObjectLibrary\Library\CyberSourceConnect.cs:line 131}

EDIT (Added 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>

Edit (Added line to app.config per the following:) 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>

Same issue is still occurring.


Solution

  • It turns out we had a configuration set up for NLog. I just had issue finding it. For those who might have a similar set up I did the following.

    Search my solution for Nlog. I found that our logging set up was using loggingConfiguration class provided by Nlog:

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

    I then added the following using the the configuration 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);
    
    

    We have a logs set up to go to a database. I am not sure if I could tell the Cybersource SDK what target I want to send logs to but the above work around at least allows me to move forward. After I finish my project (Tight deadline) . I will update this on if I found a way to point at a specific target instead of using the default 'file' target.