Welcome Guest, Not a member yet? Register   Sign In
Codeigniter 4 custom log levels
#1

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($configbool $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->logLevelstrue);
            }

            $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
...
    * - Debug Detailed debug information.
-
   * - All Messages
  * - Audit entity registration and update logging (user actions)
  * - 10 All Messages

...

-
  public $threshold = (ENVIRONMENT === 'production') ? 49;
+
  public $threshold = (ENVIRONMENT === 'production') ? 410;

...

 
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 REGISTERby [adminID 9 username =  -> Tomasemail =  -> xxx@xxxxx.xxxcompany_name =  -> XXXXXcompany_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.
Reply
#2

After some more tinkering, I found a way to override handler config for specified logging level to allow custom file extension and save path.
Extended logger->log() method with AufitLogger->customLog() method as follows. This may be hacky, but it appears to work.


app/Log/AuditLogger
PHP Code:
public function customLog($levelstring|Stringable $message, array $context = []): void
    
{
        if ($level === 'audit') {

            // assuming the first or the only handler is the correct one (FileHandler in our case)
            $handlerClassName array_keys($this->handlerConfig)[0];
            $savePath WRITEPATH 'custom_logs/';

            $this->handlerConfig[$handlerClassName]['fileExtension'] = 'tmp';
            $this->handlerConfig[$handlerClassName]['path'] = $savePath;

            // re-initialize handler with changed config
            $this->handlers[$handlerClassName] = new $handlerClassName($this->handlerConfig[$handlerClassName]);
            
            
// run parent log() method with updated handler
            parent::log($level$message$context);
        }
    
Reply




Theme © iAndrew 2016 - Forum software by © MyBB