Skip to content

Instantly share code, notes, and snippets.

@figaw
Last active January 7, 2021 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save figaw/a61df1bfab530a4901c3c514e01c2757 to your computer and use it in GitHub Desktop.
Save figaw/a61df1bfab530a4901c3c514e01c2757 to your computer and use it in GitHub Desktop.
Basic logging for PHP in JSON to stdout with Loglevel configurable from environment variables.
<?php
$LOGLEVEL = 5;
if( isset($_SERVER['LOGLEVEL']) && is_numeric(Log::LEVELS[$_SERVER['LOGLEVEL']])){
$LOGLEVEL = Log::LEVELS[$_SERVER['LOGLEVEL']];
}
abstract class Log
{
const LEVELS = array(
"ALL" => 0,
"TRACE" => 1,
"DEBUG" => 2,
"INFO" => 3,
"WARN" => 4,
"ERROR" => 5
);
}
function trace($msg){
if($GLOBALS['LOGLEVEL'] > Log::LEVELS['TRACE']) return;
formatAndPrint("TRACE", $msg);
}
function debug($msg){
if($GLOBALS['LOGLEVEL'] > Log::LEVELS['DEBUG']) return;
formatAndPrint("DEBUG", $msg);
}
function info($msg){
if($GLOBALS['LOGLEVEL'] > Log::LEVELS['INFO']) return;
formatAndPrint("INFO", $msg);
}
function warn($msg){
if($GLOBALS['LOGLEVEL'] > Log::LEVELS['WARN']) return;
formatAndPrint("WARN", $msg);
}
function error($msg, $exception = null){
if($GLOBALS['LOGLEVEL'] > Log::LEVELS['ERROR']) return;
formatAndPrint("ERROR", $msg, $exception);
}
function formatAndPrint( $level, $msg, $exception = null)
{
$obj = array(
"timestamp" => date(DateTime::ISO8601),
"level" => $level,
"msg" => $msg,
);
if(isset($exception))
$obj['exception'] = $exception->getMessage();
$flags = JSON_UNESCAPED_SLASHES;
if($GLOBALS['DEVELOPMENT'])
$flags = $flags | JSON_PRETTY_PRINT;
$message = json_encode($obj, $flags);
file_put_contents("php://stdout" , $message.PHP_EOL);
}
/*
## Usage
### somewhere you load libraries..
`require('./Log.php');`
### in the environment
LOGLEVEL in ("ALL", "TRACE", "DEBUG", "INFO", "WARN", "ERROR") # default is ERROR
DEVELOPMENT in (true, false) # pretty-print json in logs, default is false
### put this wherever
trace("THIS IS A trace message");
debug("THIS IS A debug message");
info("THIS IS A info message");
warn("THIS IS A warn message");
error("THIS IS A error message");
error("THIS IS A error message", new Exception("With Exception"));
## Example output
{
"timestamp": "2021-01-07T21:13:21+0000",
"level": "WARN",
"msg": "THIS IS A warn message"
}
{
"timestamp": "2021-01-07T21:13:21+0000",
"level": "ERROR",
"msg": "THIS IS A error message"
}
{
"timestamp": "2021-01-07T21:13:21+0000",
"level": "ERROR",
"msg": "THIS IS A error message",
"exception": "With Exception"
}
*/
@figaw
Copy link
Author

figaw commented Jan 7, 2021

I wanted basic logging in PHP in JSON format, without installing modules. Loglevel is configurable from the environment.

Use this e.g. if you want to run PHP in a Docker container, and pick up the logs with DataDog or similar.

I'm sharing this because from what I could Google it looks like I'm not the only one that could use something like this.

Rules for usage

  • This is provided "as is," I have no intention of maintaining it, use with caution.
  • If you have cool suggestions, please post them in a comment and I will consider them if I notice it in my sea of notifications.

"Look, Mom, I made a framework!..."


Heavily inspired by a tiny logger I wrote for Java https://gitlab.com/com.figaw.util/loglite

and augmented error_logger,

function myErrorHandler( $errType, $errStr, $errFile, $errLine )
{
    $displayErrors = ini_get( 'display_errors' );
    $logErrors     = ini_get( 'log_errors' );

    if( $displayErrors ) echo $errStr.PHP_EOL;

    if( $logErrors )
    {
        $err = array(
            "timestamp" => date(DateTime::ISO8601),
            "error" => $errStr,
            "file" => $errFile,
            "line" => $errLine
        );

        $flags = JSON_UNESCAPED_SLASHES;
        if($GLOBALS['DEVELOPMENT'])
            $flags = $flags | JSON_PRETTY_PRINT;

        $message = json_encode($err, $flags);
        file_put_contents("php://stderr" , $message.PHP_EOL);
    }
}

ini_set( 'log_errors', 1 );
set_error_handler( 'myErrorHandler' );

From: https://stackoverflow.com/a/35400363/1104755

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment