I am creating a PHP backend for a web application. Now I need to log all API calls into a log file. Now the logic is to create a log file inside the server itself and append the same file when new API calls are made. I am using AWS S3 file storage for image uploading, I wonder what if I can implement the log file creation and appending this log file in a specific folder called logs in my S3 bucket.
Is it possible to achieve creating a new log file inside S3 bucket (not uploading into s3 from local) and appending local API call logs into it?
My local code for log creation is given bellow:
$log = "--------------------------------------".PHP_EOL.
"UserIP: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
"Request Data: ".$req_dump.PHP_EOL.
"Request Method: ".$_SERVER['REQUEST_METHOD'].PHP_EOL.
"API URL: ".$actual_link.PHP_EOL.
"File Name: ".$filename.PHP_EOL.
"--------------------------------------".PHP_EOL;
// $fp = fopen('../api_logs/request.txt', 'a');
// $fw = fwrite($fp, $log);
// fclose($fp);
$fp = file_put_contents( '../api_logs/request.log', $log, FILE_APPEND);
Amazon stream wrapper allow you to store and retrieve data from Amazon S3 using built-in PHP functions like file_get_contents
, fopen
, copy
, rename
, unlink
, mkdir
, rmdir
, etc
You can stream data to the file something like below:
$stream = fopen('s3://bucket/key', 'a');
fwrite($stream, 'Hello!');
fclose($stream);
Full documentation of Amazon S3 Stream Wrapper can be found here