PHP error_log () writes error messages to the log file

Source: Internet
Author: User
Tags create directory set time zend

Error_log () is a function that sends an error message to a place, which is more common in program programming, especially in the debugging phase of the program.

This article will use an example to explain the use of the Error_log () and some issues to be noted.

The code is as follows Copy Code

<?php

$str = ' This is an error message. ';

Error_log ($STR, 3, ' Errors.log ');

?>

This is the most commonly used error_log () example, which is to write a piece of information into the Errors.log file, which is automatically created if it does not exist. In this example, we see a parameter "3", noting that the number "3" cannot be changed or removed.

Here's a list of possible problems with the Error_log () function:

(1) The error of the program prompts: Warning:error_log () [Function.error-log]: failed to open stream:permission denied ... on ...

The above error occurs because the file does not have write permissions and opens the file write permission for the directory.

(3) The information written to the log file cannot be wrapped.

Using Error_log () to write to the log file, you will find that the text is not wrapped, you can make the following improvements to the code:

The code is as follows Copy Code

<?php

$str = "This is an error message. RN ";

Error_log ($STR, 3, ' Errors.log ');

?>

Note that the $STR is in double quotes (the difference between PHP single and double quotes), and the RN is added to the end of the string. This is different from the first example.

Next I'll share two more custom logging instances of error logging

The code is as follows Copy Code

<?php
function Exceptionhandler () {
Error_reporting (e_all ^ e_notice);
Date_default_timezone_set (' etc/gmt-8 '); Set time zone

Ini_set (' Display_errors ', 0); Record errors to log
Ini_set (' error_log ', ' d:\ '. Date (' y-m-d '). " _weblog.txt ');
Ini_set (' log_errors ', 1); Turn On Error logging
Ini_set (' ignore_repeated_errors ', 1); Do not repeat error messages on the same line of code that appear in the same file.

$user _defined_err = Error_get_last ();
if ($user _defined_err[' type '] > 0)
{
Switch ($user _defined_err[' type ']) {
Case 1:
$user _defined_errtype = ' Fatal run-time error (e_error) ';
Break
Case 2:
$user _defined_errtype = ' non-fatal run-time error (e_warning) ';
Break
Case 4:
$user _defined_errtype = ' Compile-time parsing error (e_parse) ';
Break
Case 8:
$user _defined_errtype = ' run-time hint (e_notice) ';
Break
Case 16:
$user _defined_errtype = ' php internal error (e_core_error) ';
Break
Case 32:
$user _defined_errtype = ' php internal warning (e_core_warning) ';
Break
Case 64:
$user _defined_errtype = ' Zend Script engine internal error (e_compile_error) ';
Break
Case 128:
$user _defined_errtype = ' Zend Script engine Internal Warning (e_compile_warning) ';
Break
Case 256:
$user _defined_errtype = ' User custom error (e_user_error) ';
Break
Case 512:
$user _defined_errtype = ' user-defined warning (e_user_warning) ';
Break
Case 1024:
$user _defined_errtype = ' user-defined prompt (E_user_notice) ';
Break
Case 2048:
$user _defined_errtype = ' code hint (e_strict) ';
Break
Case 4096:
$user _defined_errtype = ' fatal error that can be caught (e_recoverable_error) ';
Break
Case 8191:
$user _defined_errtype = ' All Error warning (e_all) ';
Break
Default
$user _defined_errtype = ' unknown type ';
Break
}
$msg = sprintf ('%s%s%s '%s '%s ', date ("Y-m-d h:i:s"), $user _defined_errtype, $user _defined_err[' message '), $user _defined_ err[' file '], $user _defined_err[' line ']);
Error_log ($msg, 0);
}
}

Register_shutdown_function (' Exceptionhandler ');
?>

Call method

<meta charset= "Utf-8" >
<?php
Document 2: "test.php"
Include (' error.class.php ');
echo $_cookie[' Aaaaadfa ']; This cookie does not exist to produce an error that is used to test
echo $_session[' Aaaaadfa ']; This session does not exist to produce an error that is used to test
?>

Example 2 Logging class

The code is as follows Copy Code

<?php
/**********************************************************
* File name:LogsClass.class.php
* Class Name: Logging Class
* Create DATE:2008/05/14
* Update DATE:2008/09/28
* Author:blue
* Description: Logging class
* Example://set path and filename
* $dir = "a/b/". Date ("y/m", Time ());
* $filename =date ("D", Time ()). Log ";
* $logs =new logs ($dir, $filename);
* $logs->setlog ("Test". Time ());
*//Use default
* $logs =new logs ();
* $logs->setlog ("Test". Time ());
*//Record information array
* $logs =new logs ();
* $arr =array (
* ' type ' => ' info ',
* ' Info ' => ' test ',
* ' Time ' =>date ("y-m-d h:i:s", Time ())
* );
* $logs->setlog ($arr);
**********************************************************/
Class Logs {
Private $_filepath; File path
Private $_filename; Log file name
Private $_filehandle; File handle

/**
* Function: Initialize record class
* Input: The path to the file, the file name to write
* Output: None
*/
Public Function Logs ($dir = null, $filename = null) {
The default path is the current path
$this->_filepath = Empty ($dir)? ': $dir;

Default to time +.log file file
$this->_filename = Empty ($filename)? Date (' y-m-d ', Time ()). '. Log ': $filename;

Generate a path string
$path = $this->_createpath ($this->_filepath, $this->_filename);
Determine if the file exists
if (! $this->_isexist ($path)) {//Does not exist
If there is no path, the current directory is assumed
if (! empty ($this->_filepath)) {
Create a table of contents
if (! $this->_createdir ($this->_filepath)) {//Create directory unsuccessful processing
Die ("Create directory failed!");
}
}
Create a file
if (! $this->_createlogfile ($path)) {//Create unsuccessful processing of files
Die ("Create file failed!");
}
}

Generate a path string
$path = $this->_createpath ($this->_filepath, $this->_filename);
Open File
$this->_filehandle = fopen ($path, "A +");
}

/**
* Function: Write record
* Input: The record to write
* Output: None
*/
Public function Setlog ($log) {
Array records passed in
$str = "";
if (Is_array ($log)) {
foreach ($log as $k => $v) {
$str. = $k. " : " . $v. "N";
}
} else {
$str = $log. "N";
}

Write log
if (! fwrite ($this->_filehandle, $str)) {//write log failed
Die ("Write log Failed");
}
}

/**
* Role: To determine whether the file exists
* Input: The path to the file, the file name to write
* Output: TRUE | False
*/
Private Function _isexist ($path) {
return file_exists ($path);
}

/**
* Role: Create a directory (refer to someone else's super strong code-_-;;)
* Input: The directory to be created
* Output: TRUE | False
*/
Private Function _createdir ($dir) {
Return Is_dir ($dir) or ($this->_createdir (dirname ($dir)) and mkdir ($dir, 0777));
}

/**
* Function: Create log file
* Input: The directory to be created
* Output: TRUE | False
*/
Private Function _createlogfile ($path) {
$handle = fopen ($path, "w"); Create a file
Fclose ($handle);
return $this->_isexist ($path);
}

/**
* Role: Build path
* Input: The path to the file, the file name to write
* Output: Build a good path string
*/
Private Function _createpath ($dir, $filename) {
if (empty ($dir)) {
return $filename;
} else {
Return $dir. "/" . $filename;
}
}

/**
* Function: destructor, releasing file handle
* Input: None
* Output: None
*/
function __destruct () {
Close File
Fclose ($this->_filehandle);
}
}
?>

Correction:
1, do not have to write a log on the second file IO operation, in the object declaration open file handle
2, support for the array type of log record
3, you can use the default path and default file for the Yyyy-mm-dd.log file in the current directory

Summarize

Individuals prefer the system's own functions, if the system's own logging function can not meet the use of the following custom functions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.