Can Monolog be used on GAE and have the logging levels recorded in Stack Driver?

Viewed 424

There are a number of posts on the internet that indicate the right way to use Monolog on the google app engine (GAE standard) is like so:

   $logger = new  Monolog\Logger($name);
   $syslogHandler = new \Monolog\Handler\SyslogHandler("Ident_String", LOG_USER, \Monolog\Logger::INFO);
        $syslogHandler->setFormatter(new \Monolog\Formatter\JsonFormatter());
        $logger->pushHandler($syslogHandler);
        break;


    $logger->warn("Starting priam import." );

That does get me logging, but the level is buried in the textPayload:

textPayload: "[28-Feb-2020 11:00:07] WARNING: [pool app] child 22 said into stderr: "[2020-02-28 06:00:07] match_old.INFO: Doing a super huge SELECT to get all intls. [] []""

and the level icon is always a stippled out asterisk. enter image description here Has something changed? I'm using the php 7.3 run-time on GAE standard. Is there a way to use Monolog on GAE that let's you take proper use of stack driver?

2 Answers

There is a package available that allows you to push Monolog to Stackdriver.

As per the doc:

The supplied StackdriverHandler copies the given log level into the Stackdriver's severity based on your log method.

It also respects the context argument which allows you to send extra contextual data with your log message. This will be stored in the log message under jsonPayload.data.

The source code can be found here monolog-stackdriver

I wound up conditionally loading a different logger locally than I do on GAE. It's workable, but it seems like an unnecessary hack considering monolog is such a popular library. And, oh, it's 2020.

<?php
require_once __DIR__ . '/../vendor/autoload.php';

use Google\Cloud\Logging\LoggingClient;

function  get_logger($name) {
    $kind = getenv('LOG_TYPE')?:'remote';
    return _get_logger($kind, $name);
}

function _get_logger($kind, $name) {
    if ($kind ==='local') {
        $logger = new  Monolog\Logger($name);
        $logger->pushHandler(new Monolog\Handler\StreamHandler('php://stdout', Monolog\Logger::INFO));
        return $logger;
    }
    $logging = new LoggingClient();
    $logger = $logging->psrLogger($name);
    return $logger;
}

I'm hoping someone can make this work with monolog.

Related