简体   繁体   中英

Setup error logging for Kohana

I have exception class:

class MartbooksException extends Exception 
{
    public function __construct($msg)
    {
        parent::__construct($msg, 0, null);
        echo $msg;
        Kohana::$log->add(Log::ERROR, $msg);
    }
}

Kohana::$log->add(Log::ERROR, $msg);

Is this all I should do to write logs in application/logs files?

Is this good solution?

To follow the Kohana style I would recommend that you use:

Class Martbooks_Exception Extends Kohana_Exception

as declaration and place the file with name exception.php in classes/martbooks . This follows the style of Kohana.

Extending Kohana_Exception instead of Exception allows you to use variable substitution along the lines of

throw new Martbooks_Exception ('this is a :v', array (':v' => 'variable', ));

As for the defining a __construct() -method, the echo $msg; part would not be my preferred way of solving error handling, any echoing should be done in the block that catches the exception. The same could be argued for in the case of calling Kohana::$log->add() , but if you want log every Martbooks_Exception , your solution is perfectly valid. In that case I would rewrite your code to:

Class Martbooks_Exception Extends Kohana_Exception
{
   public function __construct($message, array $variables = NULL, $code = 0)
   {
     parent::__construct ($message, $variables, $code);
     Kohana::$log->add (Log::ERROR, __ ($message, $variables));
   }
}

with a definition of __construct() that conforms to Kohana_Exception 's __construct() .

The only objection that I would have against logging with Log::ERROR level in the constructor is that it assumes that every exception is an application level error, which might be true of some exception types, but it could also be used to signal other meanings. The exact meaning of an exception should be left to the exception handling block.

To add a log message all you need is a single line indeed; Kohana::$log->add($level, $message[, $values]) see the api

Besides that, I don't think this is a valid solution. You had better create your own exception handler, as you can see on this page of the userguide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM