Hi, I've been looking for information regarding extending CI 4 logger to customize log levels, file path, filename, etc.
I read about extending FileHandler, but it is a bit over my head.
So far, I was able to achieve adding custom log levels using file handler and an extended Logger class.
Currently working with CodeIgniter 4.5.5. Here is the code for anyone interested in similar functionality.
app/Log/AuditLogger.php
PHP Code:
<?php
namespace App\Log;
use CodeIgniter\Log\Logger as BaseLogger;
class AuditLogger extends BaseLogger {
public function __construct($config, bool $debug = CI_DEBUG)
{
parent::__construct($config, $debug);
$this->logLevels = [
...$this->logLevels,
'audit' => 9
];
$this->loggableLevels = is_array($config->threshold) ? $config->threshold : range(1, (int) $config->threshold);
// Now convert loggable levels to strings.
// We only use numbers to make the threshold setting convenient for users.
if ($this->loggableLevels !== []) {
$temp = [];
foreach ($this->loggableLevels as $level) {
$temp[] = array_search((int) $level, $this->logLevels, true);
}
$this->loggableLevels = $temp;
unset($temp);
}
}
}
app/Config/Services.php
PHP Code:
namespace Config;
+ use App\Log\AuditLogger;
+ use Config\Logger as LoggerConfig;
use CodeIgniter\Config\BaseService;
...
public static function logger(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('logger');
}
return new AuditLogger(config(LoggerConfig::class));
}
app/Config/Logger.php
PHP Code:
<?php
...
* - 8 = Debug - Detailed debug information.
- * - 9 = All Messages
+ * - 9 = Audit - entity registration and update logging (user actions)
+ * - 10 = All Messages
...
- public $threshold = (ENVIRONMENT === 'production') ? 4: 9;
+ public $threshold = (ENVIRONMENT === 'production') ? 4: 10;
...
FileHandler::class => [
// The log levels that this handler will handle.
'handles' => [
'critical',
'alert',
'emergency',
'debug',
'error',
'info',
'notice',
'warning',
+ 'audit'
],
Now you can use the custom log level in your code:
PHP Code:
log_message('audit', $msg);
Log file:
PHP Code:
...
INFO - 2024-12-16 09:53:41 --> CSRF token verified.
AUDIT - 2024-12-16 09:53:54 --> [CLIENT REGISTER] by [admin] ID 9 username = -> Tomas, email = -> xxx@xxxxx.xxx, company_name = -> XXXXX, company_ctry_id = -> 28
INFO - 2024-12-16 09:53:55 --> Session: Class initialized using 'CodeIgniter\Session\Handlers\FileHandler' driver.
...
If anyone knows how to extend logger to customize filename and location, any information is appreciated.