Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP - Implement logging mechanism to file in several classes
    primarykey
    data
    text
    <p>I would like to implement logging mechanism to file in PHP:</p> <ol> <li>log file path will be in config file config.php</li> <li>in several classes I would like to log some events into the log file</li> </ol> <p>For example:</p> <pre><code> Class A { public function f_A { log_to_file($message); } } Class B { public function f_B { log_to_file($message); } } </code></pre> <p>I will be very grateful for any tips. I would like to implement some easy and elegant solution.</p> <p>I was thinking about it (thank you for your answers) and I think I will do it this way (maybe, there are some errors, I was writing it from scratch):</p> <pre><code>interface Logger { public function log_message($message); } class LoggerFile implements Logger { private $log_file; public function __construct($log_file) { $this-&gt;log_file = $log_file; } public function log_message($message) { if (is_string($message)) { file_put_contents($this-&gt;log_file, date("Y-m-d H:i:s")." ".$message."\n", FILE_APPEND); } } } //maybe in the future logging into database class LoggerDb implements Logger { private $db; public function __construct($db) { //some code } public function log_message($message) { //some code } } Class A { private $logger; public function __construct(Logger $l) { $this-&gt;logger = $l; } public function f_A { $this-&gt;logger-&gt;log_message($message); } } Class B { private $logger; public function __construct(Logger $l) { $this-&gt;logger = $l; } public function f_B { $this-&gt;logger-&gt;log_message($message); } } //usage: //in config.php: define("CONFIG_LOG_FILE", "log/app_log.log"); //in the index.php or some other files $logger = new LoggerFile(CONFIG_LOG_FILE); $instance_a = new A($logger); $instance_b = new B($logger); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload