I wrote my own authentication plugin for Moodle 3.10. I would just like to add a log whenever the login fails. Something like this:
$log->info('User with username XYZ could not login.');
How to do this in Moodle?
I checked the developer docs in Moodle at https://docs.moodle.org/310/en/Logs but it just states where to find the logs. Not how to add logs
According to Moodle 4 docs I tried to create a custom event in my plugin auth/myapi :
Event in /auth/myapi/user_loggedin.php :
<?php
namespace myapi\event;
defined('MOODLE_INTERNAL') || die();
class user_loggedin extends \core\event\base {
protected function init() {
$this->data['crud'] = 'r';
$this->data['edulevel'] = self::LEVEL_OTHER;
}
public static function get_name() {
return get_string('event_userloggedin', 'myapi');
}
public function get_description() {
$username = $this->other['username'];
$email = $this->other['email'];
$firstname = $this->other['firstname'];
$lastname = $this->other['lastname'];
return "The user '{$username}' with email '{$email}' named '{$firstname} {$lastname}' logged in.";
}
public function get_custom_data() {
// Add custom data accessors here, if needed.
}
}
And inside my core file in /auth/myapi/auth.php:
<?php
/**
* External API authentication plugin
*
* Validates username and password against an external API, creates a new user if necessary,
* and adds the user to a specific cohort based on the profile returned by the API.
*
* @package auth_externalapi
*/
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/user_loggedin.php');
// somewhere in my code:
$event = \myapi\event\user_loggedin::create([
'context' => \context_system::instance(),
'other' => [
'username' => $user->username,
'email' => $user->email,
'firstname' => $user->firstname,
'lastname' => $user->lastname,
],
]);
$event->trigger();
But in the moodle reports logs I just find
Unknown event (\myapi\event\user_loggedin)
The Events API creates an entry in the log
There is an existing event for a login failure
Replace
AUTH_LOGIN_XXX
with one of these constantsOr you can create your own event, they are pretty simply to set up
https://docs.moodle.org/dev/Events_API
Basically, an event class is stored in
/yourpluginname/classes/event/event_name.php
Search the existing Moodle code for
extends \core\event\base
for examples