Integration Platform

Microservice Management

Connect your code to Copyl

Code from a API controller

This article is for developers who wants to connect Copyl to their code for centralized logging in the Microservice Management and to publish trigger events to the Integration Platform. This is how we manage our own logging and integrations between all the different microservices.

Please contact suppo[email protected] if you have any questions. We are here to help you.

1. Install CopylHelper

First we need to install the CopylHelper from Nuget. CopylHelper is simplifying the communication with Copyl so you don’t need to write more code than nessecary.

  1. You need to have special credentials to download the package. Please contact [email protected] to get a nuget.config file that you put in the project root in Visual Studio.
  2. Install CopylHelper from Nuget:
nuget install CopylHelper

2. Add configurations to appsettings.json

You need to define the Microservice id and the App id from Copyl into the appsettings-files.

Please observe that you have two settings files in your API project; appsettings.json and appsettings.Development.json. The latter should have the microservice id for the Development environment. The OcpApimSubscriptionKey is your key to our API Manager.

{
  "ConnectionStrings": {
  },
  "AppSettings": {
    "ServiceId": "1234549b-e903-abcd-efgh-1234f98778c3",
    "AppId": "123456DC-1234-1234-1234-D49D3891234A",
    "OcpApimSubscriptionKey" : "12345678910"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Warning",
      "CopylAPI_Users": "Information"
    },
    "CopylLoggerProvider": {
      "IncludeScopes": true,
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Error",
      }
    }
  },
  "AllowedHosts": "*"
}

3. Set up Centralized Logging

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
        .ConfigureLogging((hostingContext, logging) => 
        // Configuring logging using a delegate that takes hostingContext and logging.
        {
            logging.ClearProviders(); // Clearing all existing logging providers.
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); 
            // Adding logging configuration from appsettings.json

            // Getting AppSettings from the configuration
           var copylSettings = hostingContext.Configuration.GetSection("AppSettings").Get<CopylSettings>();

            Guid? appId = null; // Initialize nullable Guid for AppId.

            // Check if AppId is not null or empty in the configuration. 
            // If AppId exists, create a new Guid from AppId.
            if (!string.IsNullOrEmpty(copylSettings?.AppId))
            {
                appId = new System.Guid(copylSettings.AppId);
            }

            // Adding a custom logging provider with specific configuration
            logging.AddProvider(new CopylLoggerProvider(
                new CopylLoggerConfiguration
                {
                    // Assigning ServiceId from configuration
                    ServiceId = new System.Guid(copylSettings.ServiceId),

                    // Assigning AppId from configuration or null if not provided
                    AppId = appId,

                    // UserId is always null in this configuration
                    UserId = (Guid?)null,

                    // Setting the logging level to Information
                    LogLevel = LogLevel.Information
                }));
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>(); // Setting the startup class for the web application
        });
}

Error, warning and information logging

  1. Inject the ILogger into your controller / code
  2. use try{} catch{} to register errors to Copyl Microservice logging.
public class UsersController : ControllerBase
{
    private readonly ILogger<UsersController> _logger;

    public UsersController(ILogger<UsersController> logger)
    {
        _logger = logger;
    }
    
    [HttpPost]
    public async Task<ActionResult<User>> PostUser(User user)
    {
        try
        {
            _logger.LogInformation("Processing request");
            _logger.LogWarning("This is a warning and will be orange in the Copyl logging window.");
            ...
        }
        catch (Exception err)
        {
            _logger.LogError(err, "Error in {method}", MethodBase.GetCurrentMethod().Name);
            throw;
        }
    }
}

4. Set up a new Trigger

A Trigger is an event that your API is generating, and that event can trigger an Integration to be started.

(To define integrations, we first need to define Triggers in Copyl).

Create/edit Trigger event in Copyl

Use the code generator

Here comes the beauty of using Copyl for integrations and the CopylHelper library. We get all the code we need to report the event as a Trigger in Copyl.

Copyl's code generator writes all the code for you - all you have to do is to paste in your code.
All you need to do is paste this code in your code and add values to the id and name properties.
(the secrets has been replaced with ‘123456’ in the screenshot, you’ll see your real values there)

To implement the Trigger in your code, you need to attach your OcpApimSubscriptionKey. The easiest way is to use the configuration value.

  1. Expose the configuration in Startup.cs so your API Controller can inject it:
    var appSettingsSection = Configuration.GetSection("AppSettings");
    services.Configure(appSettingsSection);

  2. Inject the configuration in your controller:
    public class UsersController : ControllerBase {
    private readonly ILogger<UsersController> _logger;
    private readonly CopylHelper.Entities.AppSettings _appSettings;


    public UsersController(ILogger<UsersController> logger)
    {
    _logger = logger;

    _appSettings = appSettings.Value;
    }
  3. Use the value when sending the trigger to Copyl:
    _ = await CopylHelper.Trigger.PublishTriggerToCopylAsync(_triggerEvent, _appSettings.OcpApimSubscriptionKey);