I would like to know how to use google cloud logging library at a lumen\laravel application, there are some examples for php, but I would like to know how to implement in the best way at that framework.
Lumen seems to work the same logging infrastructure as Laravel does. By default it uses Monolog which is a PSR-3 compatible logging library but I think the following code might also work for logging with Google cloud:
Create the logger factory class:
class CreateGoogleCloudLogger {
public function __invoke() {
$logging = new LoggingClient([
'projectId' => $projectId
]);
return $logging->psrLogger('app');
}
}
Change your .env
file:
LOG_CHANNEL=googlecloud
Then add this in your AppServiceProvider
register function
config(['logging.channels.googlecloud' => [
'driver' => 'custom',
'via' => App\Logging\CreateGoogleCloudLogger::class,
] ]);
This should use the factory to create a PSR-3 compatible logger.
I found the accepted answer did not work for me when used in a stack
channel (which is Laravel 9's default configuration). This seems to be due to the stack channel requiring Monolog loggers, not just PSR-3 loggers
To make that work I copied (or "took inspiration from") https://github.com/einnar82/google-stack-driver
Made no changes to app.php
.
In .env
(note you'll need to set your actual values here)
LOG_LEVEL=debug
LOG_CHANNELS=single,googlecloud
GOOGLE_PROJECT=my-project-name-from-google
GOOGLE_APPLICATION_CREDENTIALS=/var/www/somepath/credentials-file-from-google.json
In logging.php
:
'googleProjectId' => env('GOOGLE_PROJECT'),
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', env('LOG_CHANNELS', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
],
'googlecloud' => [
'driver' => 'custom',
'via' => \App\Logging\CreateGoogleCloudLogger::class,
'level' => env('LOG_LEVEL', 'debug'),
],
];
in app/Logging/CreateGoogleCloudLogger.php
namespace App\Logging;
use Google\Cloud\Logging\LoggingClient;
use Monolog\Handler\PsrHandler;
use Monolog\Logger;
class CreateGoogleCloudLogger
{
public function __invoke(array $config)
{
$logName = config('app.name');
$logging = new LoggingClient([
'projectId' => config('logging.googleProjectId')
]);
$psrLogger = $logging->psrLogger($logName);
$handler = new PsrHandler($psrLogger);
return new Logger($logName, [$handler]);
}
}
Then in your application at any point you can just do...
Log::debug('This is a log message');
try {
$var = $this->doSomethingRisky();
} catch (\Exception $e) {
Log::warning('The risky thing failed but we will carry on anyway', ['message' => $e->getMessage()]);
$var = null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With