Home >Backend Development >PHP Tutorial >Handling errors and logs in PHP scripts

Handling errors and logs in PHP scripts

WBOY
WBOYOriginal
2024-05-09 17:18:02386browse

Answer: In PHP, error_reporting and set_error_handler are used to handle errors, while error_log and syslog are used for logging. Detailed description: Error handling: Use error_reporting to set the error level to be reported. Use set_error_handler to customize the error handling function, which can log error information and take appropriate actions. Logging: Use error_log to record errors and log messages. Use syslog to log information messages. Practical case: Open a log file, and then set an error handling function, which writes error information to the log file.

Handling errors and logs in PHP scripts

Handling of errors and logs in PHP scripts

In PHP applications, it is crucial to be able to properly handle errors and logs important to ensure its stability and reliability. Here's how to handle errors and logs in a PHP script:

Error handling

PHP provides the use of error_reporting() and set_error_handler () How the function handles errors.

<?php
// 设置要报告的错误级别
error_reporting(E_ALL);

// 自定义错误处理函数
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    // 记录错误信息
    error_log("错误:[$errno] $errstr,在 $errfile 第 $errline 行");
    // 根据错误级别采取相应措施
    switch ($errno) {
        case E_ERROR:
        case E_PARSE:
        case E_CORE_ERROR:
        case E_COMPILE_ERROR:
            exit(1); // 退出脚本
            break;
        default:
            // 继续运行脚本
    }
});
?>

Logging

PHP provides error_log() and syslog() functions to record errors and log messages .

<?php
// 记录一个错误消息
error_log("错误:数据库连接失败");

// 记录一个信息消息
syslog(LOG_INFO, "订单创建成功");
?>

Practical Case

The following is a practical case showing how to capture errors in a PHP application and log them to a file:

<?php
// 打开日志文件
$logfile = fopen('error.log', 'a');

// 设置错误处理函数
set_error_handler(function ($errno, $errstr, $errfile, $errline) use ($logfile) {
    // 记录错误信息到日志文件
    fwrite($logfile, "错误:[$errno] $errstr,在 $errfile 第 $errline 行\n");
});

// 触发一个错误
trigger_error('测试错误', E_USER_ERROR);

// 关闭日志文件
fclose($logfile);
?>

In the above example, when trigger_error() is triggered, the custom error handling function will write the error information to the error.log file.

The above is the detailed content of Handling errors and logs in PHP scripts. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn