Skip to content

Commit

Permalink
[php-slim4] Add monolog package as default logger (#12137)
Browse files Browse the repository at this point in the history
* Add monolog to templates

* Remove default values from DI\get helper

It turned out \DI\get expects only single argument, current method call
doesn't throw any errors but it should be corrected anyway.

* Refresh samples
  • Loading branch information
ybelenko committed Apr 16, 2022
1 parent c533deb commit 0e9d6b0
Show file tree
Hide file tree
Showing 17 changed files with 118 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,8 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("htaccess_deny_all", "config", ".htaccess"));
supportingFiles.add(new SupportingFile("config_dev_default.mustache", "config" + File.separator + "dev", "default.inc.php"));
supportingFiles.add(new SupportingFile("config_prod_default.mustache", "config" + File.separator + "prod", "default.inc.php"));
// add restricted htaccess to create log folder
supportingFiles.add(new SupportingFile("htaccess_deny_all", "logs", ".htaccess"));

if (Boolean.TRUE.equals(generateModels)) {
supportingFiles.add(new SupportingFile("base_model.mustache", toSrcPath(invokerPackage, srcBasePath), "BaseModel.php"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ Used packages:
* [Openapi Data Mocker Server Middleware](https://github.com/ybelenko/openapi-data-mocker-server-middleware) - PSR-15 HTTP server middleware.
* [Openapi Data Mocker Interfaces](https://github.com/ybelenko/openapi-data-mocker-interfaces) - package with mocking interfaces.

## Logging

Build contains pre-configured [`monolog/monolog`](https://github.com/Seldaek/monolog) package. Make sure that `logs` folder is writable.
Add required log handlers/processors/formatters in `{{srcBasePath}}/App/RegisterDependencies.php`.

{{#generateApiDocs}}
## API Endpoints

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
{{#isZendDiactoros}}
"laminas/laminas-diactoros": "^2.3.0",
{{/isZendDiactoros}}
"monolog/monolog": "^2.4",
"neomerx/cors-psr7": "^2.0",
{{#isNyholmPsr7}}
"nyholm/psr7": "^1.3.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,10 @@ return [
return $response->withHeader('X-{{invokerPackage}}-Mock', 'pong');
};
},

// logger
'logger.name' => 'App',
'logger.path' => \realpath(__DIR__ . '/../../logs') . '/app.log',
'logger.level' => 100, // equals DEBUG level
'logger.options' => [],
];
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,10 @@ return [
'pdo.options' => [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
],

// logger
'logger.name' => 'App',
'logger.path' => \realpath(__DIR__ . '/../../logs') . '/app.log',
'logger.level' => 300, // equals WARNING level
'logger.options' => [],
];
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@ composer.phar
!/config/.htaccess
!/config/dev/default.inc.php
!/config/prod/default.inc.php

# Logs folder
/logs/**/*.*
!/logs/.htaccess
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
<!-- Don't need to inspect installed packages -->
<exclude-pattern>./vendor</exclude-pattern>

<!-- Don't need to scan logs -->
<exclude-pattern>./logs</exclude-pattern>

<!-- <basepath> A path to strip from the front of file paths inside reports -->
<arg name="basepath" value="."/>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ final class RegisterDependencies
// Slim error middleware
// @see https://www.slimframework.com/docs/v4/middleware/error-handling.html
\Slim\Middleware\ErrorMiddleware::class => \DI\autowire()
->constructorParameter('displayErrorDetails', \DI\get('slim.displayErrorDetails', false))
->constructorParameter('logErrors', \DI\get('slim.logErrors', true))
->constructorParameter('logErrorDetails', \DI\get('slim.logErrorDetails', true)),
->constructorParameter('displayErrorDetails', \DI\get('slim.displayErrorDetails'))
->constructorParameter('logErrors', \DI\get('slim.logErrors'))
->constructorParameter('logErrorDetails', \DI\get('slim.logErrorDetails'))
->constructorParameter('logger', \DI\get(\Psr\Log\LoggerInterface::class)),
// CORS
\Neomerx\Cors\Contracts\AnalysisStrategyInterface::class => \DI\create(\Neomerx\Cors\Strategies\Settings::class)
Expand All @@ -57,7 +58,7 @@ final class RegisterDependencies
\DI\get('pdo.dsn'),
\DI\get('pdo.username'),
\DI\get('pdo.password'),
\DI\get('pdo.options', null)
\DI\get('pdo.options')
),
// DataMocker
Expand All @@ -68,6 +69,33 @@ final class RegisterDependencies
\OpenAPIServer\Mock\OpenApiDataMockerRouteMiddlewareFactory::class => \DI\autowire()
->constructorParameter('getMockStatusCodeCallback', \DI\get('mocker.getMockStatusCodeCallback'))
->constructorParameter('afterCallback', \DI\get('mocker.afterCallback')),
// Monolog Logger
\Psr\Log\LoggerInterface::class => \DI\factory(function (string $mode, string $name, string $path, $level, array $options = []) {
$logger = new \Monolog\Logger($name);
$handlers = [];
// stream logger as default handler across all environments
// somebody might not need it during development
$handlers[] = new \Monolog\Handler\StreamHandler($path, $level);
if ($mode === 'development') {
// add dev handlers if necessary
// @see https://github.com/Seldaek/monolog/blob/f2f66cd480df5f165391ff9b6332700d467b25ac/doc/02-handlers-formatters-processors.md#logging-in-development
} elseif ($mode === 'production') {
// add prod handlers
// @see https://github.com/Seldaek/monolog/blob/f2f66cd480df5f165391ff9b6332700d467b25ac/doc/02-handlers-formatters-processors.md#send-alerts-and-emails
// handlers which doesn't make sense during development
// Slack, Sentry, Swift or native mailer
}
return $logger->setHandlers($handlers);
})
->parameter('mode', \DI\get('mode'))
->parameter('name', \DI\get('logger.name'))
->parameter('path', \DI\get('logger.path'))
->parameter('level', \DI\get('logger.level'))
->parameter('options', \DI\get('logger.options')),
]);
}
}
4 changes: 4 additions & 0 deletions samples/server/petstore/php-slim4/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@ composer.phar
!/config/.htaccess
!/config/dev/default.inc.php
!/config/prod/default.inc.php

# Logs folder
/logs/**/*.*
!/logs/.htaccess
1 change: 1 addition & 0 deletions samples/server/petstore/php-slim4/.openapi-generator/FILES
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ lib/Model/Order.php
lib/Model/Pet.php
lib/Model/Tag.php
lib/Model/User.php
logs/.htaccess
phpcs.xml.dist
phpunit.xml.dist
public/.htaccess
Expand Down
5 changes: 5 additions & 0 deletions samples/server/petstore/php-slim4/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,11 @@ Used packages:
* [Openapi Data Mocker Server Middleware](https://github.com/ybelenko/openapi-data-mocker-server-middleware) - PSR-15 HTTP server middleware.
* [Openapi Data Mocker Interfaces](https://github.com/ybelenko/openapi-data-mocker-interfaces) - package with mocking interfaces.

## Logging

Build contains pre-configured [`monolog/monolog`](https://github.com/Seldaek/monolog) package. Make sure that `logs` folder is writable.
Add required log handlers/processors/formatters in `lib/App/RegisterDependencies.php`.

## API Endpoints

All URIs are relative to *http://petstore.swagger.io/v2*
Expand Down
1 change: 1 addition & 0 deletions samples/server/petstore/php-slim4/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"require": {
"php": "^7.4 || ^8.0",
"dyorg/slim-token-authentication": "dev-slim4",
"monolog/monolog": "^2.4",
"neomerx/cors-psr7": "^2.0",
"php-di/slim-bridge": "^3.2",
"slim/psr7": "^1.1.0",
Expand Down
6 changes: 6 additions & 0 deletions samples/server/petstore/php-slim4/config/dev/default.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,10 @@
return $response->withHeader('X-OpenAPIServer-Mock', 'pong');
};
},

// logger
'logger.name' => 'App',
'logger.path' => \realpath(__DIR__ . '/../../logs') . '/app.log',
'logger.level' => 100, // equals DEBUG level
'logger.options' => [],
];
6 changes: 6 additions & 0 deletions samples/server/petstore/php-slim4/config/prod/default.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,10 @@
'pdo.options' => [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
],

// logger
'logger.name' => 'App',
'logger.path' => \realpath(__DIR__ . '/../../logs') . '/app.log',
'logger.level' => 300, // equals WARNING level
'logger.options' => [],
];
36 changes: 32 additions & 4 deletions samples/server/petstore/php-slim4/lib/App/RegisterDependencies.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ public function __invoke(\DI\ContainerBuilder $containerBuilder): void
// Slim error middleware
// @see https://www.slimframework.com/docs/v4/middleware/error-handling.html
\Slim\Middleware\ErrorMiddleware::class => \DI\autowire()
->constructorParameter('displayErrorDetails', \DI\get('slim.displayErrorDetails', false))
->constructorParameter('logErrors', \DI\get('slim.logErrors', true))
->constructorParameter('logErrorDetails', \DI\get('slim.logErrorDetails', true)),
->constructorParameter('displayErrorDetails', \DI\get('slim.displayErrorDetails'))
->constructorParameter('logErrors', \DI\get('slim.logErrors'))
->constructorParameter('logErrorDetails', \DI\get('slim.logErrorDetails'))
->constructorParameter('logger', \DI\get(\Psr\Log\LoggerInterface::class)),

// CORS
\Neomerx\Cors\Contracts\AnalysisStrategyInterface::class => \DI\create(\Neomerx\Cors\Strategies\Settings::class)
Expand All @@ -70,7 +71,7 @@ public function __invoke(\DI\ContainerBuilder $containerBuilder): void
\DI\get('pdo.dsn'),
\DI\get('pdo.username'),
\DI\get('pdo.password'),
\DI\get('pdo.options', null)
\DI\get('pdo.options')
),

// DataMocker
Expand All @@ -81,6 +82,33 @@ public function __invoke(\DI\ContainerBuilder $containerBuilder): void
\OpenAPIServer\Mock\OpenApiDataMockerRouteMiddlewareFactory::class => \DI\autowire()
->constructorParameter('getMockStatusCodeCallback', \DI\get('mocker.getMockStatusCodeCallback'))
->constructorParameter('afterCallback', \DI\get('mocker.afterCallback')),

// Monolog Logger
\Psr\Log\LoggerInterface::class => \DI\factory(function (string $mode, string $name, string $path, $level, array $options = []) {
$logger = new \Monolog\Logger($name);

$handlers = [];
// stream logger as default handler across all environments
// somebody might not need it during development
$handlers[] = new \Monolog\Handler\StreamHandler($path, $level);

if ($mode === 'development') {
// add dev handlers if necessary
// @see https://github.com/Seldaek/monolog/blob/f2f66cd480df5f165391ff9b6332700d467b25ac/doc/02-handlers-formatters-processors.md#logging-in-development
} elseif ($mode === 'production') {
// add prod handlers
// @see https://github.com/Seldaek/monolog/blob/f2f66cd480df5f165391ff9b6332700d467b25ac/doc/02-handlers-formatters-processors.md#send-alerts-and-emails
// handlers which doesn't make sense during development
// Slack, Sentry, Swift or native mailer
}

return $logger->setHandlers($handlers);
})
->parameter('mode', \DI\get('mode'))
->parameter('name', \DI\get('logger.name'))
->parameter('path', \DI\get('logger.path'))
->parameter('level', \DI\get('logger.level'))
->parameter('options', \DI\get('logger.options')),
]);
}
}
1 change: 1 addition & 0 deletions samples/server/petstore/php-slim4/logs/.htaccess
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Deny from all
3 changes: 3 additions & 0 deletions samples/server/petstore/php-slim4/phpcs.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
<!-- Don't need to inspect installed packages -->
<exclude-pattern>./vendor</exclude-pattern>

<!-- Don't need to scan logs -->
<exclude-pattern>./logs</exclude-pattern>

<!-- <basepath> A path to strip from the front of file paths inside reports -->
<arg name="basepath" value="."/>

Expand Down

0 comments on commit 0e9d6b0

Please sign in to comment.