Skip to content

Commit

Permalink
Added loggers for App Engine flexible environment.
Browse files Browse the repository at this point in the history
  • Loading branch information
Takashi Matsuo committed Apr 3, 2016
1 parent 2fcc6ff commit 5f9318c
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 0 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"google/auth": "0.7",
"guzzlehttp/guzzle": "~5.2|~6.0",
"guzzlehttp/psr7": "1.2.*",
"monolog/monolog": "~1",
"psr/http-message": "1.0.*"
},
"require-dev": {
Expand Down
64 changes: 64 additions & 0 deletions src/Logger/AppEngineFlexFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Cloud\Logger;

use Monolog\Formatter\LineFormatter;

/**
* Class for formatting logs on App Engine flexible environment.
*/
class AppEngineFlexFormatter extends LineFormatter
{
/**
* @param string $format The format of the message
* @param string $dateFormat The format of the timestamp
* @param bool $ignoreEmptyContextAndExtra
*/
public function __construct($format = null, $dateFormat = null, $ignoreEmptyContextAndExtra = false)
{
parent::__construct($format, $dateFormat, true, $ignoreEmptyContextAndExtra);
}

/**
* Get the plain text message with LineFormatter's format method and add
* metadata including the trace id then return the json string.
*
* @param array $record A record to format
* @return mixed The formatted record
*/
public function format(array $record)
{
$message = parent::format($record);
list($usec, $sec) = explode(" ", microtime());
$usec = (int)(((float)$usec)*1000000000);
$sec = (int)$sec;
$payload = [
'message' => $message,
'timestamp'=> ['seconds' => $sec,
'nanos' => $usec],
'thread' => '',
'severity' => $record['level_name'],
];
if (isset($_SERVER['HTTP_X_CLOUD_TRACE_CONTEXT'])) {
$payload['traceId'] = explode(
"/",
$_SERVER['HTTP_X_CLOUD_TRACE_CONTEXT']
)[0];
}
return "\n" . json_encode($payload);
}
}
63 changes: 63 additions & 0 deletions src/Logger/AppEngineFlexHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Cloud\Logger;

use Monolog\Handler\StreamHandler;
use Monolog\Logger;

/**
* Class for logging on App Engine flexible environment.
*/
class AppEngineFlexHandler extends StreamHandler
{
/**
* @param int $level The minimum logging level at which this handler will be triggered.
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not.
* @param int|null $filePermission Optional file permissions (default (0640) are only for owner read/write).
* @param Boolean $useLocking Try to lock log file before doing any writes.
* @param resource|string|null $stream
*/
public function __construct(
$level = Logger::INFO,
$bubble = true,
$filePermission = 0640,
$useLocking = false,
$stream = null
) {
if ($stream === null) {
$pid = posix_getpid();
$stream = "file:///var/log/app_engine/app.$pid.json";
}
parent::__construct(
$stream,
$level,
$bubble,
$filePermission,
$useLocking
);
}

/**
* Get the default formatter.
*
* @return FormatterInterface
*/
protected function getDefaultFormatter()
{
return new AppEngineFlexFormatter();
}
}
55 changes: 55 additions & 0 deletions tests/Logger/AppEngineFlexHandlerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Cloud\Tests\Logger;

use Google\Cloud\Logger\AppEngineFlexHandler;
use Monolog\Logger;

class AppEngineFlexHandlerTest extends \PHPUnit_Framework_TestCase
{
private $path;
private $log;

public function setUp()
{
$dir = sys_get_temp_dir();
$this->path = tempnam($dir, "log");
$handler = new AppEngineFlexHandler(
Logger::DEBUG, true, 0640, false, $this->path
);
$this->log = new Logger('gcloud-test');
$this->log->pushHandler($handler);
}

public function tearDown()
{
unlink($this->path);
}

public function testOneLine()
{
$msg = 'Error message';
$this->log->addError($msg);
$log_text = file_get_contents($this->path);
$log_array = json_decode($log_text, true);
$this->assertContains($msg, $log_array['message']);
$this->assertInternalType('int', $log_array['timestamp']['seconds']);
$this->assertInternalType('int', $log_array['timestamp']['nanos']);
$this->assertEquals('ERROR', $log_array['severity']);
}
}

0 comments on commit 5f9318c

Please sign in to comment.