我想在 PHP 中实现日志记录机制:
- 日志文件路径将在配置文件 config.php
- 在几个类中,我想将一些事件记录到日志文件中
例如:
Class A {
public function f_A {
log_to_file($message);
}
}
Class B {
public function f_B {
log_to_file($message);
}
}
我将非常感谢任何提示。我想实现一些简单而优雅的解决方案。
我正在考虑它(谢谢你的回答),我想我会这样做(也许,有一些错误,我是从头开始写的):
interface Logger {
public function log_message($message);
}
class LoggerFile implements Logger {
private $log_file;
public function __construct($log_file) {
$this->log_file = $log_file;
}
public function log_message($message) {
if (is_string($message)) {
file_put_contents($this->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->logger = $l;
}
public function f_A {
$this->logger->log_message($message);
}
}
Class B {
private $logger;
public function __construct(Logger $l) {
$this->logger = $l;
}
public function f_B {
$this->logger->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);