Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write date and time into LOG file in PHP

I would like to write into my LOG file the current date and time :

$logFileName = 'file://c:\MYLOG.log'; // /var/logs/file.log
$logContent = "Running through the function".PHP_EOL;
$date = (new DateTime('NOW'))->format("y:m:d h:i:s");
if ($handle = fopen($logFileName, 'a')) 
{
  fwrite($handle, $date);
  fwrite($handle, PHP_EOL);
  fwrite($handle, $logContent);
  fwrite($handle, PHP_EOL);
  fwrite($handle, $cmdWindows);
  fwrite($handle, PHP_EOL);
  fwrite($handle, $params);
  fwrite($handle, PHP_EOL);
 }
 fclose($handle);

When it is running through my method, I can see all my wanted information but not the date and the time. Can you tell me where am I wrong please ? Thank you in advance.

like image 283
Tofuw Avatar asked Dec 05 '22 04:12

Tofuw


1 Answers

In your datatime constructor now isn't necessary because it's default. And as for you answer you can't apply chaining on a constructor (before PHP 5.4) if you have PHP > 5.4 you can apply constructor chaining like this (new Foo)->bar()

Example below will definitly work:

$date = new DateTime();
$date = $date->format("y:m:d h:i:s");
like image 56
Daan Avatar answered Dec 06 '22 19:12

Daan