まず、php.iniの場所
$ php -r “echo phpinfo();” | grep “php.ini”
Configuration File (php.ini) Path => /etc/php/7.4/cli
Loaded Configuration File => /etc/php/7.4/cli/php.ini
$ cat /etc/php/7.4/cli/php.ini | grep error_log
; server-specific log, STDERR, or a location specified by the error_log
; Set maximum length of log_errors. In error_log information about the source is
;error_log = php_errors.log
;error_log = syslog
; to syslog. Only used when error_log is set to syslog.
; the message. Only used when error_log is set to syslog.
; OPcache error_log file name. Empty string assumes “stderr”.
;opcache.error_log=
あれ、コメントアウトされていて、出力されていない…?
$ sudo vi /etc/php/7.4/cli/php.ini
$ G
$ error_log = /var/log/php.log
ini_set('display_errors', "On");
$num1 = 2;
$num2 = 0;
try {
echo calc1($num1, $num2);
} catch (Exception $e){
echo $e->getMessage();
error_log("[". date('Y-m-d H:i:s') . "]". "保存に失敗しました。\n", 3, "/var/www/html/debug.log");
}
function calc1($a, $b){
if ($b == 0){
throw new Exception("エラー");
}
return $a/$b;
}
$ sudo touch debug.log
$ sudo chmod 777 /var/www/html/debug.log
$ cat /var/www/html/debug.log
[2022-04-09 23:37:07]保存に失敗しました。
これで、エラーログを出力できる。
error_log("[". date('Y-m-d H:i:s') . "]". "保存に失敗しました。\n", 3, "/var/log/php.log");
なるほど、理解した。