recherche
Maisondéveloppement back-endtutoriel php简单的php自定义异常日志

简单的php自定义错误日志

平时经常看php的错误日志,很少有机会去自己动手写日志,看了王健的《最佳日志实践》觉得写一个清晰明了,结构分明的日志还是非常有必要的。

在写日志前,我们问问自己:为什么我们有时要记录自定义的日志呢?而不用系统默认的日志记录方式呢?

我认为有两个原因:

1.团队需要一个统一格式的日志方便管理

2.大量无用错误日志占据硬盘空间,仅需记录有意义的日志

那么,实践一下。


1.打开你的php.ini

2.打开日志记录,将

log_errors = Off

改成

log_errors = On

3.将php.ini保存退出并重启web服务器

4.在你的代码最前面加上如下代码

<span style="color: #008080;"> 1</span> <span style="color: #000000;">php</span><span style="color: #008080;"> 2</span> <span style="color: #008080;"> 3</span> <span style="color: #008000;">//</span><span style="color: #008000;">错误处理函数</span><span style="color: #008080;"> 4</span> <span style="color: #0000ff;">function</span> myErrorHandler(<span style="color: #800080;">$errno</span>, <span style="color: #800080;">$errstr</span>, <span style="color: #800080;">$errfile</span>, <span style="color: #800080;">$errline</span><span style="color: #000000;">)</span><span style="color: #008080;"> 5</span> <span style="color: #000000;">{</span><span style="color: #008080;"> 6</span>     <span style="color: #800080;">$log_file</span> = "./php_%s_log_".<span style="color: #008080;">date</span>("Ymd").".log";<span style="color: #008000;">//</span><span style="color: #008000;">定义日志文件存放目录和文件名</span><span style="color: #008080;"> 7</span>     <span style="color: #800080;">$template</span> = ''<span style="color: #000000;">;</span><span style="color: #008080;"> 8</span>     <span style="color: #0000ff;">switch</span> (<span style="color: #800080;">$errno</span><span style="color: #000000;">) {</span><span style="color: #008080;"> 9</span>     <span style="color: #0000ff;">case</span> <span style="color: #ff00ff;">E_USER_ERROR</span>:<span style="color: #008080;">10</span>         <span style="color: #800080;">$template</span> .= "用户ERROR级错误,必须修复 错误编号[<span style="color: #800080;">$errno</span>] <span style="color: #800080;">$errstr</span> "<span style="color: #000000;">;</span><span style="color: #008080;">11</span>         <span style="color: #800080;">$template</span> .= "错误位置 文件<span style="color: #800080;">$errfile</span>,第 <span style="color: #800080;">$errline</span> 行\n"<span style="color: #000000;">;</span><span style="color: #008080;">12</span>         <span style="color: #800080;">$log_file</span> = <span style="color: #008080;">sprintf</span>(<span style="color: #800080;">$log_file</span>,'error'<span style="color: #000000;">);</span><span style="color: #008080;">13</span>         <span style="color: #0000ff;">exit</span>(1);<span style="color: #008000;">//</span><span style="color: #008000;">系统退出</span><span style="color: #008080;">14</span>         <span style="color: #0000ff;">break</span><span style="color: #000000;">;</span><span style="color: #008080;">15</span> <span style="color: #008080;">16</span>     <span style="color: #0000ff;">case</span> <span style="color: #ff00ff;">E_USER_WARNING</span>:<span style="color: #008080;">17</span>         <span style="color: #800080;">$template</span> .= "用户WARNING级错误,建议修复 错误编号[<span style="color: #800080;">$errno</span>] <span style="color: #800080;">$errstr</span> "<span style="color: #000000;">;</span><span style="color: #008080;">18</span>         <span style="color: #800080;">$template</span> .= "错误位置 文件<span style="color: #800080;">$errfile</span>,第 <span style="color: #800080;">$errline</span> 行\n"<span style="color: #000000;">;</span><span style="color: #008080;">19</span>         <span style="color: #800080;">$log_file</span> = <span style="color: #008080;">sprintf</span>(<span style="color: #800080;">$log_file</span>,'warning'<span style="color: #000000;">);</span><span style="color: #008080;">20</span>         <span style="color: #0000ff;">break</span><span style="color: #000000;">;</span><span style="color: #008080;">21</span> <span style="color: #008080;">22</span>     <span style="color: #0000ff;">case</span> <span style="color: #ff00ff;">E_USER_NOTICE</span>:<span style="color: #008080;">23</span>         <span style="color: #800080;">$template</span> .= "用户NOTICE级错误,不影响系统,可不修复 错误编号[<span style="color: #800080;">$errno</span>] <span style="color: #800080;">$errstr</span> "<span style="color: #000000;">;</span><span style="color: #008080;">24</span>         <span style="color: #800080;">$template</span> .= "错误位置 文件<span style="color: #800080;">$errfile</span>,第 <span style="color: #800080;">$errline</span> 行\n"<span style="color: #000000;">;</span><span style="color: #008080;">25</span>     <span style="color: #800080;">$log_file</span> = <span style="color: #008080;">sprintf</span>(<span style="color: #800080;">$log_file</span>,'notice'<span style="color: #000000;">);</span><span style="color: #008080;">26</span>         <span style="color: #0000ff;">break</span><span style="color: #000000;">;</span><span style="color: #008080;">27</span> <span style="color: #008080;">28</span>     <span style="color: #0000ff;">default</span>:<span style="color: #008080;">29</span>         <span style="color: #800080;">$template</span> .= "未知错误类型: 错误编号[<span style="color: #800080;">$errno</span>] <span style="color: #800080;">$errstr</span>  "<span style="color: #000000;">;</span><span style="color: #008080;">30</span>         <span style="color: #800080;">$template</span> .= "错误位置 文件<span style="color: #800080;">$errfile</span>,第 <span style="color: #800080;">$errline</span> 行\n"<span style="color: #000000;">;</span><span style="color: #008080;">31</span>         <span style="color: #800080;">$log_file</span> = <span style="color: #008080;">sprintf</span>(<span style="color: #800080;">$log_file</span>,'unknown'<span style="color: #000000;">);</span><span style="color: #008080;">32</span>         <span style="color: #0000ff;">break</span><span style="color: #000000;">;</span><span style="color: #008080;">33</span> <span style="color: #000000;">    }</span><span style="color: #008080;">34</span>     <span style="color: #008080;">file_put_contents</span>(<span style="color: #800080;">$log_file</span>,<span style="color: #800080;">$template</span>,<span style="color: #000000;">FILE_APPEND);</span><span style="color: #008080;">35</span> <span style="color: #008080;">36</span>     <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #000000;">;</span><span style="color: #008080;">37</span> <span style="color: #000000;">}</span><span style="color: #008080;">38</span> <span style="color: #008080;">39</span> <span style="color: #800080;">$error_handler</span> = <span style="color: #008080;">set_error_handler</span>("myErrorHandler");<span style="color: #008000;">//</span><span style="color: #008000;">开启自定义错误日志</span>

5.试着在刚才的代码后写下一段错误代码

<span style="color: #0000ff;">echo</span> 1/0;

看看你定义的路径下是否多了一个日志文件呢?:)

以下级别的错误不能由用户定义的函数来处理: E_ERROR、 E_PARSE、 E_CORE_ERROR、 E_CORE_WARNING、 E_COMPILE_ERROR、 E_COMPILE_WARNING,和在 调用 set_error_handler() 函数所在文件中产生的大多数 E_STRICT。

不过当你开启了错误日志系统(php.ini中的log_error = on)并且指定了系统日志文件(同样也是php.ini中的error_log=路径名),并且error_reporting开启了全部后,以上的错误都会作为系统错误日志而记录在你定义的文件中。

Déclaration
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Comment PHP identifie-t-il la session d'un utilisateur?Comment PHP identifie-t-il la session d'un utilisateur?May 01, 2025 am 12:23 AM

Phpidentifiesauser'sessionusingssse cookiesand sessionids.1) whenSession_start () est calculé, phpgeneratesauquesseSessionIdStoredInacookIenameDPhpSesssIdonUser'sbrowser.2) thisIdallowsphptoreTrrieSeSessionDatafromTeserver.

Quelles sont les meilleures pratiques pour sécuriser les séances PHP?Quelles sont les meilleures pratiques pour sécuriser les séances PHP?May 01, 2025 am 12:22 AM

La sécurité des sessions PHP peut être obtenue grâce aux mesures suivantes: 1. Utilisez Session_RegeReate_ID () pour régénérer l'ID de session lorsque l'utilisateur se connecte ou est une opération importante. 2. Cryptez l'ID de session de transmission via le protocole HTTPS. 3. Utilisez session_save_path () pour spécifier le répertoire sécurisé pour stocker les données de session et définir correctement les autorisations.

Où les fichiers de session PHP sont-ils stockés par défaut?Où les fichiers de session PHP sont-ils stockés par défaut?May 01, 2025 am 12:15 AM

PhpSessionFilesArestorentheDirectorySpecifiedSession.save_path, généralement / tmponunix-likesystemsorc: \ windows \ temponwindows.tocustomzethis: 1) usession_save_path () tosetacustomDirectory, astumeit'swrit

Comment récupérer les données d'une session PHP?Comment récupérer les données d'une session PHP?May 01, 2025 am 12:11 AM

ToretrrievedatafromaphpSession, startTheSessionwithSession_start () et accessvariablesInthe $ _sessionArray.forexample: 1) startTheSession: session_start (). 2) récupéré: $ username = $ _ session ['userSeger']; echo "bienvenue,". $ Username;..

Comment pouvez-vous utiliser des sessions pour mettre en œuvre un panier?Comment pouvez-vous utiliser des sessions pour mettre en œuvre un panier?May 01, 2025 am 12:10 AM

Les étapes pour construire un système de panier d'achat efficace à l'aide de sessions comprennent: 1) Comprendre la définition et la fonction de la session. La session est un mécanisme de stockage côté serveur utilisé pour maintenir l'état de l'utilisateur entre les demandes; 2) Implémenter la gestion de session de base, comme l'ajout de produits au panier; 3) développer une utilisation avancée, soutenant la gestion de la quantité de produits et la suppression; 4) Optimiser les performances et la sécurité, en persistant les données de session et en utilisant des identifiants de session sécurisés.

Comment créez-vous et utilisez-vous une interface dans PHP?Comment créez-vous et utilisez-vous une interface dans PHP?Apr 30, 2025 pm 03:40 PM

L'article explique comment créer, mettre en œuvre et utiliser des interfaces dans PHP, en se concentrant sur leurs avantages pour l'organisation du code et la maintenabilité.

Quelle est la différence entre crypte () et mot de passe_hash ()?Quelle est la différence entre crypte () et mot de passe_hash ()?Apr 30, 2025 pm 03:39 PM

L'article traite des différences entre crypt () et mot de passe_hash () dans PHP pour le hachage de mot de passe, en se concentrant sur leur implémentation, leur sécurité et leur aptitude aux applications Web modernes.

Comment pouvez-vous prévenir les scripts inter-sites (XSS) en PHP?Comment pouvez-vous prévenir les scripts inter-sites (XSS) en PHP?Apr 30, 2025 pm 03:38 PM

L'article discute de la prévention des scripts inter-sites (XSS) dans PHP par validation d'entrée, en codage de sortie et en utilisant des outils comme OWASP ESAPI et Purificateur HTML.

See all articles

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Outils chauds

DVWA

DVWA

Damn Vulnerable Web App (DVWA) est une application Web PHP/MySQL très vulnérable. Ses principaux objectifs sont d'aider les professionnels de la sécurité à tester leurs compétences et leurs outils dans un environnement juridique, d'aider les développeurs Web à mieux comprendre le processus de sécurisation des applications Web et d'aider les enseignants/étudiants à enseigner/apprendre dans un environnement de classe. Application Web sécurité. L'objectif de DVWA est de mettre en pratique certaines des vulnérabilités Web les plus courantes via une interface simple et directe, avec différents degrés de difficulté. Veuillez noter que ce logiciel

Navigateur d'examen sécurisé

Navigateur d'examen sécurisé

Safe Exam Browser est un environnement de navigation sécurisé permettant de passer des examens en ligne en toute sécurité. Ce logiciel transforme n'importe quel ordinateur en poste de travail sécurisé. Il contrôle l'accès à n'importe quel utilitaire et empêche les étudiants d'utiliser des ressources non autorisées.

SublimeText3 Linux nouvelle version

SublimeText3 Linux nouvelle version

Dernière version de SublimeText3 Linux

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

PhpStorm version Mac

PhpStorm version Mac

Le dernier (2018.2.1) outil de développement intégré PHP professionnel