Adding log functionality to your plugin

In this tutorial, you will learn how to integrate log functionality in your plugin.

Step 1: Cloning the ToDoList plugin

We will extend the functionality of the ToDoList plugin by integrating a log function. We then use this log to retrieve certain information.

The ToDoList plugin structure

Below, you find an overview of the existing structure of our ToDoList plugin.

ToDoList/
    ├── resources/
    │   ├── css/
    │   │   └── main.css
    │   │
    │   ├── js/
    │   │   └── todo.js
    │   │
    │   └── views/
    │       └── content/
    │           └── todo.twig
    │
    ├── src/
    │   ├── Contracts
    │   │   └── ToDoRepositoryContract.php
    │   │
    │   ├── Controllers/
    │   │   └── ContentController.php
    │   │
    │   ├── Migrations/
    │   │   └── CreateToDoTable.php
    │   │
    │   ├── Models/
    │   │   └── ToDo.php
    │   │
    │   ├── Providers/
    │   │   ├── ToDoServiceProvider.php
    │   │   └── ToDoRouteServiceProvider.php
    │   │
    │   ├── Repositories
    │   │   └── ToDoRepository.php
    │   │
    │   └── Validators
    │       └──ToDoValidators.php
    │
    ├── plugin.json // plugin information
    └── // additional files (Readme, license, etc.)

Step 2: Extending the plugin structure

In order to integrate the Loggable trait, we have to make changes to the following existing files. We also have to create two new folders with two new files:

  • Extend the CreateToDoTable.php.
  • Create the resources/lang/en and resources/lang/de folder and add the respective migration.properties file to each one.
  • Extend the ToDoServiceProvider.php.
  • Extend the ContentController.php.

Extending the CreateToDoTable

In order to log the creation of a to do table, we need to enter the functionality in the CreateToDoTable.php file. This example shows a simple log; you can find a reference type log here.

ToDoList/src/Migrations/CreateToDoTable.php
<?php

namespace ToDoList\Migrations;

use ToDoList\Models\ToDo;
use Plenty\Modules\Plugin\DataBase\Contracts\Migrate;
use Plenty\Plugin\Log\Loggable;

/**
 * Class CreateToDoTable
 */
class CreateToDoTable
{
    use Loggable;

    /**
     * @param Migrate $migrate
     */
    public function run(Migrate $migrate)
    {
        $migrate->createTable(ToDo::class);

        $this->getLogger("CreateToDoTable_run")->debug('ToDoList::migration.successMessage', ['tableName' => 'ToDo']);

    }
}

Creating the translations

To display messages in all selected languages, we have to set these up in the correct file structure.

  1. Create the resources/lang folder.
  2. Create the en sub-folder.
  3. Create a sub-folder for any language you want to add, e.g. de for German.
  4. In each folder, create a .properties file that will contain all the translations. E.g migration.properties.
  5. Add the following code.
ToDoList/resources/lang/en/migration.properties
successMessage = "Table created"
createToDoInformation = "Task created"

Extending the ToDoServiceProvider

We have to boot a reference container in the ToDoServiceProvider to store the reference type and value.

ToDoList/src/Providers/ToDoServiceProvider.php
<?php

namespace ToDoList\Providers;

use Plenty\Plugin\ServiceProvider;
use ToDoList\Contracts\ToDoRepositoryContract;
use ToDoList\Repositories\ToDoRepository;
use Plenty\Log\Services\ReferenceContainer;
use Plenty\Log\Exceptions\ReferenceTypeException;

/**
 * Class ToDoServiceProvider
 * @package ToDoList\Providers
 */
class ToDoServiceProvider extends ServiceProvider
{

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->getApplication()->register(ToDoRouteServiceProvider::class);
        $this->getApplication()->bind(ToDoRepositoryContract::class, ToDoRepository::class);
    }


    public function boot(ReferenceContainer $referenceContainer)
    {
        // Register reference types for logs.
        try
        {
            $referenceContainer->add([ 'toDoId' => 'toDoId' ]);
        }
        catch(ReferenceTypeException $ex)
        {
        }
    }
}

Extending the ContentController

The ContentController manages the creation, update and deletion of our to dos. In order to log the creation of a new to do, we have to enter the necessary code here.

ToDoList/src/Controllers/ContentController.php
<?php

 namespace ToDoList\Controllers;

 use Plenty\Plugin\Controller;
 use Plenty\Plugin\Http\Request;
 use Plenty\Plugin\Templates\Twig;
 use ToDoList\Contracts\ToDoRepositoryContract;
 use Plenty\Plugin\Log\Loggable;

 /**
  * Class ContentController
  * @package ToDoList\Controllers
  */
 class ContentController extends Controller
 {
     use Loggable;

     /**
      * @param Twig                   $twig
      * @param ToDoRepositoryContract $toDoRepo
      * @return string
      */
     public function showToDo(Twig $twig, ToDoRepositoryContract $toDoRepo): string
     {
         $toDoList = $toDoRepo->getToDoList();
         $templateData = array("tasks" => $toDoList);
         return $twig->render('ToDoList::content.todo', $templateData);
     }

     /**
      * @param  \Plenty\Plugin\Http\Request $request
      * @param ToDoRepositoryContract       $toDoRepo
      * @return string
      */
     public function createToDo(Request $request, ToDoRepositoryContract $toDoRepo): string
     {
         $newToDo = $toDoRepo->createTask($request->all());

         $this
             ->getLogger('ContentController_createToDo')
             ->setReferenceType('toDoId') // optional
             ->setReferenceValue($newToDo->id) // optional
             ->info('ToDoList::migration.createToDoInformation', ['userId' => $newToDo->userId ]);

         return json_encode($newToDo);
     }

     /**
      * @param int                    $id
      * @param ToDoRepositoryContract $toDoRepo
      * @return string
      */
     public function updateToDo(int $id, ToDoRepositoryContract $toDoRepo): string
     {
         $updateToDo = $toDoRepo->updateTask($id);
         return json_encode($updateToDo);
     }

     /**
      * @param int                    $id
      * @param ToDoRepositoryContract $toDoRepo
      * @return string
      */
     public function deleteToDo(int $id, ToDoRepositoryContract $toDoRepo): string
     {
         $deleteToDo = $toDoRepo->deleteTask($id);
         return json_encode($deleteToDo);
     }
 }

Using the Reportable trait

There are certain cases where we need to display logs even if they are not activated in the Log settings back end, e.g. at the end of every order import process to let users know how many new orders were imported or skipped.

For these cases we use the Reportable trait. This one is similar to the Loggable trait described above.

ToDoList/src/Controllers/ContentController.php
<?php

 namespace ToDoList\Controllers;

 use Plenty\Plugin\Controller;
 use Plenty\Plugin\Http\Request;
 use Plenty\Plugin\Templates\Twig;
 use ToDoList\Contracts\ToDoRepositoryContract;
 use Plenty\Plugin\Log\Reportable;

 /**
  * Class ContentController
  * @package ToDoList\Controllers
  */
 class ContentController extends Controller
 {
     use Reportable;

     ...

     /**
      * @param  \Plenty\Plugin\Http\Request $request
      * @param ToDoRepositoryContract       $toDoRepo
      * @return string
      */
     public function createToDo(Request $request, ToDoRepositoryContract $toDoRepo): string
     {
         $newToDo = $toDoRepo->createTask($request->all());

         $this-report('ContentController_createToDo', 'ToDoList::migration.createToDoInformation', ['userId' => $newToDo->userId ], ['toDoId' => $newToDo->id]);

         return json_encode($newToDo);
     }

     ...
 }

See what you did there

To see the log functionality at work, you have to go to your plentymarkets back end. There, you go through the following steps:

  1. Go to Data exchange » Log.
  2. Click on Configure.
    → The log configuration window will open.
  3. Select the ToDoList plugin.
  4. Select a time from the Duration drop-down menu.
    → This is the time for which the plugin will be logged.
  5. Select a log level from the Log level drop-down menu.
  6. Save the settings.

Finally, you can log your newly created tasks in your back end.

  1. Enter http://your-plentystore.co.uk/todo in your browser to open the ToDoList plugin.
  2. Enter one or more tasks.
  3. Return to your plentymarkets back end.
  4. Go to Data exchange » Log.
    → Find the logs to the tasks you just created.

Log structure

This code shows the Loggable trait in the ContentController.php file.

ToDoList/src/Controllers/ContentController
$this
     ->getLogger('ContentController_createToDo')
     ->setReferenceType('toDoId')
     ->setReferenceValue($newToDo->id)
     ->info('ToDoList::migration.createToDoInformation', ['userId' => $newToDo->userId ]);

The following table contains explanations of the individual code elements.

Element Description
Integration key The Loggable trait automatically identifies the plugin it is used in and displays the namespace under Configure and Integration in the menu Data exchange » Log in the plentymarkets back end.
Identifier The identifier will be shown under Identifier in the menu Data exchange » Log in the plentymarkets back end. In our example, it is ContentController_createToDo.
Reference type (optional) This part has to be clearly defined and as specific as possible to avoid doublings. In case of a doubling, the try and catch method in the ServiceProvider will throw an exception. We chose toDoId.
Reference value (optional) Add the specific value for the reference type, In our example, we store the ID of the new task using $newToDo->id.
Debug level The chosen debug level, in our example info.
Code This element uses the key-value pairs from the migrations.properties file, in this example, the createToDoInformation key. It is shown under Code in the plentymarkets back end.
Additional information (optional) After the code element, you can add further information. In this example, we have chosen ['userId' => $newToDo->userId ] to get the ID of the user who created the to do task.

Available log levels

In this table, find all the available log levels and explanations of the individual level.

Level Description
report Report information. Will always be logged without prior log key activation.
debug Detailed debug information
info Interesting events
notice Normal but significant events
warning Exceptional occurrences that are not errors
error Runtime errors that do not require immediate action but should typically be logged and monitored
critical Critical conditions
alert Action must be taken immediately
emergency System is unusable

Is this article helpful?

 

Thank you for your Feedback

you can close this field now!