简体   繁体   中英

Apache2 PHP docker container, how to log errors as stderr and info as stdout to container log?

I am currently using the official php:7.4-apache image and I wanted to log some info and errors to the docker logs.

I realize that PHP does not log directly, but logs to the Apache2 Server instead since this is the server interpreting PHP.

Still, I tried the direct approach using the information from the official docker docs :

<?php

error_log('testlog', 3, '/proc/self/fd/1');
error_log('testerror', 3, '/proc/self/fd/2');

This gave me a "failed to open stream, the file does not exist" warning.

I also noticed that simply calling error_log('test') creates the following log without being written to stderr:

[Tue Nov 10 11:39:46.005650 2020] [php7:notice] [pid 17] [client 172.25.0.1:56576] test

I tried to figure out if there were any special ways to send a message to Apache2 stdout/stderr, but I was not able to find anything useful.

Is there a way to achieve this or is this simply the wrong way to log PHP within containers?

!!EDIT:!!

So far I've managed to find out that the log definition in the original Dockerfile is handled in this file to /dev/stderr & /dev/stdout .

I also found the following possibility:

error_log('test', 3, 'php://stdout');
error_log('testerr', 3, 'php://stderr');

But this results in the following output:

> test 
> 172.25.0.1 - - [18/Nov/2020:13:19:48 +0000] "GET / HTTP/1.1" 200 229 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36"
> testerr 

The goal would be to have something like this:

custom_info_log('test');
custom_error_log('testerr');

output this:

> [Wed Nov 18 13:19:48.459874 2020] [php7:info] [pid 20] [client 172.25.0.1:57398] test
> [Wed Nov 18 13:19:48.459874 2020] [php7:error] [pid 20] [client 172.25.0.1:57398] testerr

Don't know if that can help, but you can forward any output from PHP to a file using :

ob_start();

//
// your script ....
//

$filePath = "path/to/your/log/file"
$outstream = ob_get_flush();
ob_clean();

if(!($file = fopen($filePath,"wb")))
{
    echo "unable to open log file" ; 
}
fwrite($file, $outstream);
fclose($file);

So maybe you can create a file logging all your php output and forward this file content to your docker logs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM