Write to PHP Log Files Easily: 5 Code Examples (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Write to Log Files in PHP

When developing applications in PHP (any language), logging is an essential tool for tracking what happens in the code. By logging errors, warnings, and other important information, developers can:

  • Identify and diagnose application issues, making locating and fixing bugs or errors easier.
  • Detect security breaches or attacks, such as unusual login attempts or suspicious network activity.
  • Identify performance issues in applications or systems, such as slow queries or memory leaks.
  • Ensure compliance with regulatory requirements or internal policies. For example, financial institutions may be required to log all financial transactions for audit purposes.
  • Track user activity or system changes, making storing, monitoring, and auditing user behavior or system changes easier.

This article will discuss some of the most common PHP methods for writing to log files.

PHP Error Logging Code Example

<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;


function divide_numbers($numerator, $denominator) {
    try {
        if ($denominator === 0) {
            throw new Exception('Cannot divide by zero.');
        }
        return $numerator / $denominator;
    } catch (Exception $e) {
        // Log the error message using Monolog
        $log = new Logger('my_logger');
        $log->pushHandler(new StreamHandler('/path/to/demo.log', Logger::ERROR));
        $log->error($e->getMessage());


        // Display a friendly error message to the user
        echo 'An error occurred. Please try again later.';
    }
}


divide_numbers(1,0); //Raises exception


?>
php logging

Article Highlights

  • Having application logs helps developers diagnose, fix and tune applications.
  • There are four types of errors in PHP: Notice, Warning, Parse Error, Fatal Error.
  • Avoid logging sensitive data or use encryption before logging.
  • Use error_log() to log errors to a destination file.
  • Alternatively, use file_put_contents() to write errors to a log file.
  • Use the PHP logging library Monolog for more serious production-grade applications.

Table of Contents

Types of PHP Errors

Notice

These are non-critical errors that do not halt the execution of the script but can indicate issues that need to be addressed. Examples of notices include undefined variables, undefined constants, and calling non-existent methods.

Notice: Undefined variable: x in /path/to/file.php on line 5

Warning

These are more serious than notices and may indicate potential problems that could cause issues later on. 

Examples of warnings include calling deprecated functions, using an uninitialized variable, or passing an incorrect number of arguments to a function.

Warning: Use of undefined constant DB_HOST - assumed 'DB_HOST' (this will throw an Error in a future version of PHP) in /path/to/file.php on line 5

Parse Error

These errors occur when the code violates the rules of the PHP syntax. These critical issues can cause the script to fail or produce unexpected results.

Examples include syntax errors, division by zero, and trying to access an undefined array index.

Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE or '$' in /path/to/file.php on line 5

Fatal Error

In PHP, a fatal error is an error that occurs when the PHP interpreter encounters a condition that prevents the script from continuing to run. Fatal errors typically indicate a code or environment problem preventing the script from running correctly.

Once a fatal error occurs, the script execution stops immediately, and no further code is executed.

Examples include invoking undefined methods or functions and exhausting execution time or memory size.

Fatal error: Uncaught Error: Call to undefined function my_function() in /path/to/my/file.php

Best Practices | PHP Logging

Here are some best practices for logging errors in PHP:

  1. Use a logging library: A logging library like Monolog provides more features and flexibility than the built-in error_log() function, making it easier to handle logging in a consistent and maintainable way.
  1. Log errors and warnings: Log errors, warnings, and other relevant information, such as debug messages or application-specific events. This can help you identify and diagnose issues more quickly.
  1. Use log levels: Use log levels to categorize log messages according to their severity or importance. This can help you filter and prioritize log messages when analyzing logs.
  1. Avoid logging sensitive information: Avoid logging sensitive information, such as passwords or credit card numbers. If sensitive information is logged, it should be encrypted or hashed.
  1. Use a log rotation strategy: Implement a log rotation strategy to prevent log files from growing too large and to ensure that older logs are archived or deleted. This can help you manage disk space and improve performance.
  1. Choose an appropriate log format: Choose a one that is easy to read and parse. Common formats include JSON, XML, or plain text with structured data.
  1. Store logs securely: Store logs securely, especially if they contain sensitive information. Use appropriate file permissions and encryption if necessary.
  1. Monitor logs regularly: Monitor logs regularly to quickly detect and respond to issues. This can help you identify patterns or trends that may indicate larger issues with your application.

Following these best practices ensures that error logging is effective, secure, and easy to maintain.

Write to a Log File using error_log() | PHP Logging

PHP’s error_log() function logs errors or other messages to a file, the system logger, or a custom error handler.

By default, error_log() writes to the PHP error log, but you can specify a custom log file destination.

 The basic syntax of the error_log() function is as follows.

error_log ( string $message, int $message_type = 0 [, string $destination [, string $extra_headers ]]] ): boolean

Parameters

  • $message: This is a required parameter that specifies the message to be logged.
  • $message_type: This parameter specifies where the error should go.
  • $destination: This optional parameter specifies where the error message should be logged. 
  • $extra_headers: This optional parameter allows you to specify additional headers to be sent with the error message (if using the email destination).

Return Values

Returns true on success; false otherwise.

Basic Usage

<?php
$error_message = "An error occurred!";
$error_log_file = "/path/to/demo.log";
error_log($error_message. PHP_EOL, 3, $error_log_file);
?>

In this example, the $error_message variable contains the error message to be logged, and the $error_log_file variable contains the path to the log file where the message should be written. 

The value 3 for the $message_type parameter indicates that the function appends the error message to the log file.

Note: It will create a new demo.log file if it doesn’t exist already.

Write to a log file using error_log() | PHP Logging

The following example defines a function divide_numbers() that takes two arguments: a numerator and a denominator. 

It throws an error if the denominator is zero. We will log this error using error_log().

<?php
function divide_numbers($numerator, $denominator) {
    try {
        if ($denominator === 0) {
            throw new Exception("Attempted to divide by zero!");
        } else {
            return $numerator / $denominator;
        }
    } catch (Exception $e) {
        $error_message = $e->getMessage();
        error_log($error_message. PHP_EOL, 3, "demo.log");
        return null;
    }
}

divide_numbers(1, 0); //Raises exception
?>

In this example, we use a try-and-catch block to handle the error. 

  1. If the $denominator equals zero, we throw a new Exception with an error message. 
  1. The catch block then catches the exception and logs the error message to the log file using the error_log().

Pros & cons

ProsCons
Easy to useSecurity concerns if logging sensitive information
Flexible with multiple parameters for customisationPotential performance impact if logging too many error messages. Mind that it has a limit on the character count of log text.
Built-in, no need to install extra libraries.Lack of centralization if multiple developers work on the same codebase
Does not offer advanced features such as log rotation

Write to a Log File using file_put_contents() | PHP Logging

Another way to write to a log file in PHP is by using the file_put_contents() function. This function takes a filename and a string message as arguments and writes the message to the file.

file_put_contents($filename, $data, $flags = 0, $context = null): int | false

Parameters

  • $filename:: The file name to write to. 
  • $data: The data to write to the file..
  • $flags (default: 0): Additional options for writing to the file. 
  • $context (optional): A stream context resource created with stream_context_create().

Return Values

This function returns the number of bytes written to the file or false on failure.

Basic Usage

<?php


$message = "An error occurred";
$logfile = "/path/to/demo.log";
file_put_contents($logfile, $message . PHP_EOL, FILE_APPEND);


?>

The example is pretty much self-explanatory. We’re using the FILE_APPEND flag to append the message to the end of the file rather than overwriting it.

Note: It will create a new demo.log file if it doesn’t exist already.

Write to a log file using file_put_contents() | PHP Logging

Let’s revisit the previous example of the divide_numbers() function.

<?php


function divide_numbers($numerator, $denominator) {
    try {
        if ($denominator === 0) {
            throw new Exception('Cannot divide by zero.');
        }
        return $numerator / $denominator;
    } catch (Exception $e) {
        // Log the error message to a file
        $message = '[' . date('Y-m-d H:i:s') . '] ' . $e->getMessage() . "\n";
        $logFile = '/path/to/demo.log';
        file_put_contents($logFile, $message, FILE_APPEND | LOCK_EX);


        // Display a friendly error message to the user
        echo 'An error occurred. Please try again later.';
    }
}


divide_numbers(1, 0); //Raises exception.


?>

If an exception is caught, we log the error message to a file using file_put_contents(). We also prepend the error message with a timestamp using date() to make error tracking easier.

  • The FILE_APPEND flag is used to append the message to the end of the log file
  • The LOCK_EX flag is used to acquire an exclusive lock on the file while writing to it. 

The function will write the log message when we invoke the function as follows divide_numbers(1, 0).

Pros & cons

ProsCons
Simple and easy to useMay not be suitable for high-volume logging
Requires minimal configurationMay not be suitable for complex logging scenarios
Can write to any file on the systemMay not be as performant as other logging libraries
No external dependenciesDoes not offer advanced features such as log rotation
Supports exclusive locking to prevent race conditionsMay require manual log rotation
May not be suitable for distributed systems or multiple writers

Write to a Log File using Monolog | PHP Logging

Monolog is a popular logging library for PHP that provides a variety of features and integrations. With Monolog, you can write to different log files based on severity levels, filter and format log messages, and send logs to various destinations like files, email, Slack, and more.

Installation

To use Monolog, you need to install it via Composer.

composer require monolog/monolog

Basic usage

Once installed, you can create a logger object and start logging messages.

<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;


$logger = new Logger('my_logger');
$logfile = "/path/to/demo.log";
$handler = new StreamHandler($logfile, Logger::WARNING);
$logger->pushHandler($handler);


$logger->warning('An error occurred');

?>

Let’s do some anatomy of this basic example.

  1. Import the Monolog classes: The first two lines of code import the Logger and StreamHandler classes from the Monolog library.
  1. Create a new logger instance: The next line creates a new Logger instance named “my_logger”. This logger will be used to record log messages.
  1. Set up a stream handler: Next, it sets up a StreamHandler to write log messages to a file. The second argument to the StreamHandler constructor sets the minimum severity level for recording messages. In this case, only messages with a severity of Logger::WARNING or higher will be recorded.
  1. Attach the stream handler to the logger: The next line attaches the StreamHandler to the logger using the pushHandler() method. This tells the logger to send all log messages to the stream handler for processing.
  2. Record a log message: The final line of code records a log message with a severity level of Logger::WARNING. This message will be passed to the StreamHandler, which will write it to the log file specified earlier.

Write to a log file using Monolog | PHP Logging

<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;


function divide_numbers($numerator, $denominator) {
    try {
        if ($denominator === 0) {
            throw new Exception('Cannot divide by zero.');
        }
        return $numerator / $denominator;
    } catch (Exception $e) {
        // Log the error message using Monolog
        $log = new Logger('my_logger');
        $log->pushHandler(new StreamHandler('/path/to/demo.log', Logger::ERROR));
        $log->error($e->getMessage());


        // Display a friendly error message to the user
        echo 'An error occurred. Please try again later.';
    }
}


divide_numbers(1,0); //Raises exception


?>

Here’s a breakdown of the example.

  • We first create a new instance of the Logger class with the name ‘my_logger’. 
  • We then push a new instance of the StreamHandler class onto the logger, specifying the path to the log file and a logging level of ERROR.
  • Finally, we call the error() method on the logger with the error message to log it to the file.

Pros & cons

ProsCons
Provides a simple, flexible interface for loggingCan add some overhead to application performance
Supports logging to a variety of handlers and formatsMay require some additional configuration or setup time
Offers advanced features like log filtering and cachingLearning curve for new users who are not familiar with OOP
Integrates easily with popular PHP frameworks
Has an active community and good documentation

Frequently Asked Questions

What are log levels in PHP?

In PHP, log levels refer to the different levels of severity of log messages that can be written to a log file or system. These log levels are typically represented by predefined constants, such as:

  1. DEBUG: Log messages that provide detailed debugging information.
  2. INFO: Log messages that provide general information about the application or system.
  3. NOTICE: Log messages that indicate an event or occurrence that may be of interest.
  4. WARNING: Log messages that indicate a warning or potential problem.
  5. ERROR: Log messages that indicate an error has occurred.
  6. CRITICAL: Log messages that indicate a critical error or system failure.
  7. ALERT: Log messages that indicate an urgent problem that requires immediate attention.
  8. EMERGENCY: Log messages that indicate a catastrophic system failure or other emergency.

Which logging library is used in Laravel?

Laravel uses the Monolog library under the hood. Learn more about logging in Laravel.

Which logging library is used in Symfony?

Symfony uses the PSR-3 logger, but it can integrate seamlessly with Monolog.

Which service is used for logs in AWS?

In AWS, one of the most commonly used services for logging is Amazon CloudWatch. CloudWatch is a monitoring and logging service that allows developers to collect and analyze log data from a variety of sources, including AWS services and applications running on AWS infrastructure.

How to Write to Log Files in PHP

Logging errors is an essential part of developing any application. In PHP, there are several ways to log errors to a file. The error_log() function is a built-in function that allows you to log messages to a file, including error messages. However, error_log() has limitations, such as limited configuration options and potential security risks.

Another way to log errors to a file in PHP is to use the file_put_contents() function. This function allows you to write a string to a file, which can be used to log error messages. 

A third option for logging errors in PHP is a library like Monolog. Monolog provides a powerful and flexible way to log messages to various channels, including files. With Monolog, you can configure loggers and handlers to customize the behavior of your logging, such as specifying log levels and formatting options.

A logging library like Monolog can be a more robust and flexible approach to logging errors in PHP, especially for larger or more complex applications. However, the choice of logging method will depend on the specific needs of your application and the available resources.
That’s all for now. Hope to see you again at FuelingPHP.

Handling Errors in PHP Article Series

This article is part of our learning series on handling PHP errors. Check out the fill series to learn how to master proper error handling.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.