Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to write a message to a log file

Short answer

Append a line with the date to a file:

<?php
 
function logMessage(string $file, string $message): void
{
    $line = sprintf("[%s] %s\n", date('Y-m-d H:i:s'), $message);
 
    file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
}
 
$file = sys_get_temp_dir() . '/recipe-app.log';
file_put_contents($file, '');
 
logMessage($file, 'User 42 logged in');
logMessage($file, 'Order 7 paid');
 
echo count(file($file)), ' lines';

Output:

2 lines

The built-in function

error_log() writes to PHP's error log or, with type 3, to a given file:

<?php
 
$file = sys_get_temp_dir() . '/recipe-errors.log';
file_put_contents($file, '');
 
error_log("Payment failed for order 7\n", 3, $file);
 
echo file_get_contents($file);

Output:

Payment failed for order 7

In a large project

Use the Monolog library: it handles message levels, daily files and sending to external services. Passwords, tokens and card numbers are never written to a log.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.