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 below.
<?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']);
}
}
We add use Plenty\Plugin\Log\Loggable
and $this→getLogger("CreateToDoTable_run")→debug('ToDoList::migration.successMessage',
['tableName' ⇒ 'ToDo'])
.
After the dependency injection in line 7, employ the getLogger()
method in line 14 to introduce the log. In line 23, employ getLogger; it automatically identifies the integration key, in this case the plugin namespace. In the getLogger()
method, you have to specify the log identifier for display in the back end. In this example, this is the class CreateToDoTable
with the added method run
. As an alternative, you can use a php magic method, e.g. METHOD
or FUNCTION
.
The employed log level is debug. In the debug method, the first parameter is the path to the message (which will be provided by the migration.properties
file in the next step), the second parameter can provide additional information, in this case, the table name.
Creating the translations
To display messages in all selected languages, we have to set these up in the correct file structure.
-
Create the resources/lang folder.
-
Create the en sub-folder.
-
Create a sub-folder for any language you want to add, e.g. de for German.
-
In each folder, create a
.properties
file that will contain all the translations, e.gmigration.properties
. -
Add the following code.
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.
<?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)
{
}
}
}
We introduce the reference container and reference type exception classes in line 8 and 9. Then we boot a reference container in line 28 to use in the ContentController.
We want to log the id of a to do task, so we use the add
function to provide a toDoId
in an array. If needed, you can add more data.
We employ try
and catch
to make sure the reference type isn’t used yet. If it is used, this will result in an exception. To avoid this, choose a specific reference type.
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.
<?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);
}
}
We use the the Loggable class as in the CreateToDoTable.php
file. To ensure that we log the creation of the to do, we have to enter the code in the createToDo
, after the task has been created, but before the return. As above, enter the identifier or a magic method. Set the reference type and value as in the service provider - in this case, the ID of the to do - and store both in the reference container. Choose a different log level, e.g. info. You can offer additional information in an array; in this example, we provide the userId
of the task creator.
Conditions for log messages to be displayed
Log messages have to fulfill certain conditions to be shown to the customer in the plentymarkets back end:
-
Log codes must have translations. If no translation is provided the log message will be ignored.
-
Log codes must be activated in the Log settings back end. Logs that are not activated will be ignored.
-
The above conditions do not apply if the log level is set to
error
,critical
,alert
oremergency
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.
<?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:
-
Go to Data exchange » Log.
-
Click on Configure.
→ The log configuration window will open. -
Select the ToDoList plugin.
-
Select a time from the Duration drop-down menu.
→ This is the time for which the plugin will be logged. -
Select a log level from the Log level drop-down menu.
-
Save the settings.
In choosing a log level, you set the minimum level to be triggered; any higher level occurrence will be triggered as well. If you choose debug, the lowest level, every event that occurs will also be logged. If you choose critical, only critical, alert, and emergency will be logged. You can find a detailed description here.
Finally, you can log your newly created tasks in your back end.
-
Enter
http://your-plentystore.co.uk/todo
in your browser to open the ToDoList plugin. -
Enter one or more tasks.
-
Return to your plentymarkets back end.
-
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.
$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 |
Reference type (optional) |
This part has to be clearly defined and as specific as possible to avoid doublings. In case of a doubling, the
|
Reference value (optional) |
Add the specific value for the reference type, In our example, we store the ID of the new task using |
Debug level |
The chosen debug level, in our example |
Code |
This element uses the key-value pairs from the |
Additional information (optional) |
After the code element, you can add further information. In this example, we have chosen |
Available log levels
In this table, find all the available log levels and explanations of the individual level.
Level | Description |
---|---|
|
Report information. Will always be logged without prior log key activation. |
|
Detailed debug information |
|
Interesting events |
|
Normal but significant events |
|
Exceptional occurrences that are not errors |
|
Runtime errors that do not require immediate action but should typically be logged and monitored |
|
Critical conditions |
|
Action must be taken immediately |
|
System is unusable |