Home Backend Development PHP Tutorial Summary of using different methods to log error reports

Summary of using different methods to log error reports

Nov 01, 2021 pm 05:30 PM
php Error handling error log

In the previous article, I brought you "Take you to understand the error types and error levels of PHP", which introduced the error types and error levels in PHP in detail. In this article we Let’s take a look at the configuration and use of error logs in PHP. I hope everyone has to help!

Summary of using different methods to log error reports

In our previous article, we introduced the exception handling, error types and error levels of PHP errors. Next, let’s introduce the configuration of error logs in PHP. and how to use it. For PHP developers, once a project is put into use, the display_errors option in the configuration file php.ini should be turned off immediately to avoid revealing paths, database connections, data tables and other information due to these errors.

In any project that is put into use, errors will inevitably occur. Some error reports are useful to developers. At this time, we can log the error reports through separate text files. . In this way, developers can more easily check whether there are problems with the system. If you enable log_errors in the PHP configuration file, you can write the error report in the program into the error log.

This error report will be automatically recorded to the server's log file. You can also send it to the system's syslog, that is, the system log. Next, let’s take a look at how to implement such error handling.

Record error reports by specifying files

If you want to use a target file to record error report logs, it is important to What is needed is that the location of the specified file needs to be outside the document root directory. In this case, the possibility of being attacked is low, and the specified file needs to have certain permissions. First, let's take a look at what we need to target php. How to modify the configuration directive of ini:

  • <strong>log_errors = On</strong>; Determine the location of log statement recording

  • <strong>log_errors_max_len = 1024</strong> ;Set the maximum length of each log entry

  • <strong>error_reporting = E_ALL</strong> ;Every error that occurs will be reported to PHP

  • <strong>display_errors = Off</strong> ;Do not display all error reports that meet the rules defined in the previous command

  • ##error_log = /usr/local/error.log<strong></strong> ;Specify the location of the log file where the generated error report is written

After modifying the php.ini file as described above, after successful setting, run the PHP script file , the error report will no longer be displayed in the browser. At this time, the error report will be displayed in the target file we set, which is the error log.


In addition, it should be noted that the errors defined by

error_reporting can be recorded in this target file, and the error information can be placed in the target file through the error_log() function. The error log in the server or this target file.

error_log() The syntax format of the function is as follows:

error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] ) : bool
Copy after login

What needs to be noted is:


$message represents the error message that needs to be recorded; $destination represents the destination, which is the destination to which the error message is sent. Its meaning is described above and is determined by the $message_type parameter; $extra_headers represents additional headers. Used when $message_type is set to 1. This message type uses the same built-in function of mail().

$message_type indicates where setting errors should be sent. Possible message types are the following:

  • 0: (Default value) Send $message to the PHP system log, use The operating system's logging mechanism or a file, depending on what error_log is set in the configuration file;

  • 1: Send $message to The email address set by the parameter $destination. The fourth parameter $extra_headers will only be used in this type; (2 has been deprecated)

  • 3$message is sent to the file located at $destination. The character $message will not be treated as a new line by default;

  • 4: Send $message directly to the SAPI log handler .

Next, let’s take a look at logging in to the Mysql database as an example. When the login fails, error information is logged. The example is as follows:

<?php
    $link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
    if (!$link) {
        error_log(&#39;Mysql 数据库连接失败!&#39;,0);
        exit();
    }
?>
Copy after login

If we take the problem of logging into the Oracle database as an example, the usage example of this function is as follows:

<?php
if(!Ora_Logon($username, $password)){
error_log("Oracle数据库不可用!", 0); //将错误消息写入到操作系统日志中
 }
if(!($foo=allocate_new_foo()){
 error_log("不行!", 1, ". mydomain.com"); //发送到管理员邮箱中
 }
error_log("不行!", 2, "localhost:5000"); //发送到本机对应5000端口的服务器中
error_log("不行!", 3, "/usr/local/errors.log"); //发送到指定的文件中
?>
Copy after login

代码运行之后就会在php.ini 配置文件中 error_log 一项所设置的目录中生成对应的错误日志文件。接下来我们看一下错误信息记录到操作系统的日志里是什么情况。

通过系统日志记录错误报告

上文中我们讲到了将使用目标文件来记录错误报告日志,接下来我们就来看一下将错误信息放到操作系统的日志里面,这是可以实现的,其中不同的操作系统,它们的日志管理也是不一样的,下面我们都是使用常见的windows举例,Windows 上错误将发送到事件日志里,可以通过事件查看器来查看。

通过什么样的方法才能够在操作系统的日志里有错误信息呢?这时候我们可以通过php.ini 配置文件中 error_log,接下来我们看一下应该怎样修改php.ini中的配置文件。

修改error_reporting = E_ALL用来报告所发生的每个错误;修改display_errors = Off 用来不显示满足上条指令所定义规则的所有错误报告;修改log_errors = On用于决定日志语句记录的位置;修改log_errors_max_len = 1024用于设置每个日志项的最大长度;修改error_log = syslog用于指定产生的错误报告写入操作系统的日志里 。

虽然通过前面介绍的 error_log() 函数,可以向 syslog 中发送定制的消息,想要实现将错误信息放到操作系统的日志里面,我们还需要三个函数的帮助,下面我们就来简单的介绍一下:

  • <strong>openlog()</strong>函数

该函数是用来打开连接的,用于向系统中写入日志信息做的准备。并且每个日志的消息中都有它的一个参数是字符串形式的。

  • <strong>syslog()</strong>函数

该函数拥有两个参数,它的作用是用来给系统中的日志给一个特定消息,第一个参数就是用来设置这个消息的优先级,第二个参数即使提供字符串,这个字符串就是这个特定的消息。

  • <strong>closelog()</strong>函数

该函数就是用来关闭连接的,这个连接就是上文中openlog() 函数打开的。

那么接下来我们通过示例来看一下实际操作吧,示例如下:

<?php
    openlog("PHP中文网", LOG_PID, LOG_USER);
    syslog(LOG_WARNING, "向 syslog 中发送定时消息,发送时间:".date("Y/m/d H:i:s"));
    closelog();
?>
Copy after login

以windows系统为例,打开“此电脑”右键选择“管理”选项,进入计算机管理界面,找到图示中应用程序的选项,就能够看到我们自己定制的警告信息了。如下所示:

Summary of using different methods to log error reports

Summary of using different methods to log error reports

其中我们需要注意的是:

你所使用的Web服务器环境决定了是使用指定文件还是使用syslog记录错误日志。可以控制服务器的话就可以利用解析工具来查看和分析日志,推荐使用syslog 激励错误日志,网站在共享服务器的虚拟主机中运行,推荐使用单独的文本文件记录错误日志了。

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

The above is the detailed content of Summary of using different methods to log error reports. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles