Tutorials: Logging

Setting Loggers

In order to be able to log messages later on, you need to open bootstrap index.php file and add this event listener:

$object->addEventListener(::APPLICATION, "LoggingListener");

then create a tag (which will hold your logger settings), child of DEVELOPMENT ENVIRONMENT tag (because logging policies may be different on another environment), child of tag. Example:

<local> <logger class="FileLogger" path="C:\xampp\htdocs\messages" format="%d %f %l %m"/> ... </local> </loggers>

This configures logging into a C:\xampp\htdocs\messages.log file for local DEVELOPMENT ENVIRONMENT. Each class attribute points to a class name in application/loggers that must extend . Framework comes with two implementations by default:

Formatting Log Line

If you're using implementation above, log line can be formatted via format attribute based on a combination of following placeholders:

Logging Messages

After you have completed Setting Loggers section described above, you are now able to log messages. To log a message in a controller or a subsequent event listener use:

$this->attributes->getLogger()

To return a instance that automatically distributes same message to all loggers registered on that DEVELOPMENT_ENVIRONMENT. Example:

$this->attributes->getLogger()->info("hello");

Assuming XML is same as in previous section, a new line is appended in file C:\xampp\htdocs\messages.log. Example:

2021-04-15 20:50:33 application/controllers/TestController 10 hello

Writing New Loggers

Rarely, developers may need a solution for message logging other than the one that comes with framework already, defined by Setting Loggers section. To do so, they must first register a new tag @ stderr.xml. Example:

<local> ... <logger class="SQLLoggingWrapper" table="logs"/> </local> ... </loggers>

Above is set to log messages in table logs via class SQLLogger that must extend and be located in application/loggers folder. Example:

require_once("SQLLogger.php"); class SQLLoggingWrapper extends { protected function setLogger(\SimpleXMLElement $xml): { $table = (string) $xml["table"]; if (!$table) { throw new \("Attribute 'path' is mandatory"); } return new SQLLogger($table); } }

Now that a XML binder for logger is made, you will need to create (in same folder) the driver:

class SQLLogger extends { private $table; public function __construct(string $tableName) { $this->table = $tableName; } protected function log($message, int $level): void; { $info = debug_backtrace()[1]; try { SQL("INSERT INTO ".$this->tableName." (message, file, line) VALUES (:message, :file, :line)", array(":message"=>$message, ":file"=>$info["file"], ":line"=>$info["line"])); } catch(\Exception $e) {} } }

assuming following MySQL table structure:

CREATE TABLE logs ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, message TEXT NOT NULL, file VARCHAR(255) NOT NULL, line VARCHAR(255) NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id) )
×