PHP Network closelog() Function
The PHP Network closelog() function is used to close the system logger connection. The system logger is a tool that helps to log important messages or errors. This function is used to clean up resources when you have finished logging messages. No input parameter is required.
The connection was properly ended because it always returns true. All of the main PHP versions, including PHP 4, 5, 7, and 8, support this feature.
Syntax
Below is the syntax of the PHP Network closelog() function −
bool closelog()
Parameters
This function does not required any parameter.
Return Value
The closelog() function returns TRUE on success. And FALSE on failure.
PHP Version
First introduced in core PHP 4, the closelog() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
This program demonstrates the most basic use of the PHP Network closelog() function. It disconnects after communicating with the system logger.
<?php
// Open system logger
openlog("BasicLogger", LOG_PID | LOG_PERROR, LOG_USER);
// Log a basic message
syslog(LOG_INFO, "This is a basic log message.");
// Close the system logger
closelog();
?>
Output
Here is the outcome of the following code −
Jan 8 13:09:29 BasicLogger[1831] <Info>: This is a basic log message.
Example 2
In the below PHP code we will try to use the closelog() function and logging multiple messages. So this program logs multiple messages to the system logger and then closes the connection with the help of closelog().
<?php
// Open system logger
openlog("MultiLogger", LOG_PID | LOG_PERROR, LOG_USER);
// Log different types of messages
syslog(LOG_INFO, "Information message logged.");
syslog(LOG_WARNING, "Warning message logged.");
syslog(LOG_ERR, "Error message logged.");
// Close the system logger
closelog();
?>
Output
This will generate the below output −
Jan 8 13:11:37 MultiLogger[1858] <Info>: Information message logged. Jan 8 13:11:37 MultiLogger[1858] <Warning>: Warning message logged. Jan 8 13:11:37 MultiLogger[1858] <Error>: Error message logged.
Example 3
Now the below code defines a function for logging messages. The function uses openlog() and closelog() function dynamically for each call.
<?php
function logMessage($message, $level = LOG_INFO) {
// Open system logger inside the function
openlog("FunctionLogger", LOG_PID | LOG_PERROR, LOG_USER);
// Log the message with the given level
syslog($level, $message);
// Close the system logger
closelog();
}
// Use the function to log messages
logMessage("This is an info message.");
logMessage("This is an error message.", LOG_ERR);
?>
Output
This will create the below output −
Jan 8 13:15:36 FunctionLogger[1903] <Info>: This is an info message. Jan 8 13:15:36 FunctionLogger[1903] <Error>: This is an error message.