Log guide
The Log module stores app-related events in a persistent log as they occur, aimed at providing a log of meaningful events that happened in your app, like when a user signs up, an invoice is generated, an API call is received, and whatever other events you deem important enough to be logged for future reference or analysis.
Events are stored in the
log
database table using a shared-memory buffer and a programmed Janitor commit task for optimal performance, resulting in a system capable of ingesting many events per second without a noticeable performance impact.You can create thelog
table in your database by importing thelog.sql
file you'll find in the Cherrycake skeleton repository, under theinstall/database
directory.
Imagine you would like to log an event every time a someone searches for a movie in your app. To do so, we would first create the class
LogEventMovieSearch
in the file classes/LogEventMovieSearch.class.php
like this:<?php
namespace CherrycakeApp;
class LogEventMovieSearch extends \Cherrycake\Log\LogEvent {
protected $typeDescription = "Movie search";
}
$e->Log->logEvent(new LogEventMovieSearch);
LogEvent objects can carry some additional data to better describe the event, in our case, we could add the movie title the user searched for, like this:
$e->Log->logEvent(new LogEventMovieSearch([
"additionalData" => [
"movieTitle" => "Blade Runner"
]
]));
You can further simplify the way you trigger Log events by overloading your event's loadInline method. Let's say instead of passing the whole
additionalData
hash array like we did above, we wanted to be able to just pass the movie title and let the constructor take care of it. We would do it like this:<?php
namespace CherrycakeApp;
class LogEventMovieSearch extends \Cherrycake\LogEvent {
protected $typeDescription = "Movie search";
function loadInline($movieTitle = false) {
parent::loadInline([
"additionalData" => [
"movieTitle" => $movieTitle
]
]);
}
}
So now we can trigger the event in this simplified way, and the movie title will be stored along with it:
$e->Log->logEvent(new LogEventMovieSearch("Blade Runner"));
Sometimes you might want to store ids from items in other tables from your database in your Log events.
For example, let's say that whenever a user that has logged in to your app searches for a movie like we did in the example above, its user id gets also stored in the
LogEventMovieSearch
. To do it, we would modify the LogEventMovieSearch
class like this:<?php
namespace CherrycakeApp;
class LogEventMovieSearch extends \Cherrycake\Log\LogEvent {
protected $typeDescription = "Movie search";
protected $outherIdDescription = "Logged user id";
function loadInline($movieTitle = false) {
global $e;
$e->loadCoreModule("Login");
parent::loadInline([
"outher_id" => $e->Login->isLogged() ? $e->Login->user->id : false,
"additionalData" => [
"movieTitle" => $movieTitle
]
]);
}
}
Last modified 2yr ago