PHP code example of arwg / laravel-final-logger
1. Go to this page and download the library: Download arwg/laravel-final-logger library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
arwg / laravel-final-logger example snippets
'providers' => [
Arwg\FinalLogger\FinalLoggerServiceProvider::class
]
$app->singleton(Arwg\FinalLogger\ErrorLogHandlerInterface::class, Arwg\FinalLogger\ErrorLogHandler::class);
$app->singleton(Arwg\FinalLogger\GeneralLogHandlerInterface::class, Arwg\FinalLogger\GeneralLogHandler::class);
$app->singleton(Arwg\FinalLogger\Exceptions\CommonExceptionModel::class, function ($app) {
return new Arwg\FinalLogger\Exceptions\CommonExceptionModel();
});
return [
'general_logger' => \Arwg\FinalLogger\GeneralLogHandler::class, // necessary
'error_logger' => \Arwg\FinalLogger\ErrorLogHandler::class, // necessary
'general_log_path' => 'your-path', // necessary
'request_excepted_log_data' => [
'final-test-uri' => [['password'],['password_reset']]
],
'response_excepted_log_data' => [
'final-test-uri' => [['a','b', 'c'], ['a','d']]
],
'success_code' => [
'OK' => 200,
'No Content' => 204
],
'error_code' => [
'Internal Server Error' => 500, // necessary
'Bad Request' => 400,
'Unauthorized' => 401,
'Not Found' => 404,
'Request Timeout' => 408,
'Precondition Failed' => 412,
'Unprocessable Entity' => 422
],
'error_user_code' => [
'all unexpected errors' => 900, // necessary
'socket error' => 1113,
'DB procedure...' => 1200,
]
];
// app/Http/Exceptions/Handler.php (or your registered Handler)
namespace App\Exceptions;
use Arwg\FinalLogger\Payload;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
protected $dontReport = [
];
public function report(Exception $exception)
{
// If you want to leave auth token invalidation info, don't comment this.
if ($this->shouldntReport($exception)) {
return;
}
// Can use only 'Payload::reportError($exception)' but recommends to create your own FinalException. So I have created a sample below.
Payload::reportError($exception, function ($exception){
return $this->createFinalException($exception);
});
}
public function render($request, Exception $exception)
{
$message = null;
/* XmlHttpRequest (Ajax) */
if (\Request::wantsJson()) {
if (Config('app.env') && Config('app.env') == 'local') {
return Payload::renderError($exception, false);
}else{
return Payload::renderError($exception, true);
}
} else {
/* HttpRequest */
try{
if (Config('app.env') && Config('app.env') == 'local') {
return parent::render($request, $exception->getPrevious() ? $exception->getPrevious() : $exception);
}else{
// Follow Laravel auth in case of HttpRequest 401, 422.
if($exception->getCode() == 422 || $exception->getCode() == 401){
return parent::render($request, $exception->getPrevious() ? $exception->getPrevious() : $exception);
}
// Customize this according to your environment.
return response()->view('errors.error01', ['code' => '...', 'message' => 'Server error. Ask the administrator.']);
}
}catch (\Throwable $e){
// Customize this according to your environment.
return response()->view('errors.error01', ['code' => '...', 'message' => 'Server error. Ask the administrator.']);
}
}
}
// This is only sample. You can create your own FinalException.
private function createFinalException(\Exception $e) : FinalException
{
$internalMessage = $e->getMessage();
$lowLeverCode = $e->getCode();
// 422: Laravel validation error
if (isset($e->status) && $e->status == 422) {
return new FinalException('Failed in Laravel validation check.',
$internalMessage, config('final-logger.error_user_code')['paraemeter validation'], $e->errors(),
config('final-logger.error_code')['Unprocessable Entity'], $e->getTraceAsString(), $e);
}// 401 Oauth2 (id, password)
else if ($e instanceof AuthenticationException || ($e instanceof ClientException && $lowLeverCode == 401)) {
if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
$internalMessage .= ' / ' . $_SERVER['HTTP_AUTHORIZATION'];
}
if (preg_match('/invalid.credentials|Unauthorized/', $internalMessage)) {
return new FinalException('Wrong ID, Password.',
$internalMessage, null, "",
config('final-logger.error_code')['Unauthorized'], $e->getTraceAsString(), $e);
} else if (preg_match('/Unauthenticated/', $internalMessage)) {
return new FinalException('token not valid.',
$internalMessage, null, "",
config('final-logger.error_code')['Unauthorized'], $e->getTraceAsString(), $e);
} else {
return new FinalException('Auth error.',
$internalMessage, null, "",
config('final-logger.error_code')['Unauthorized'], $e->getTraceAsString(), $e);
}
} // Oauth2 (token)
else if ($e instanceof OAuthServerException) {
return new FinalException('Oauth2 token error.',
$internalMessage, config('final-logger.error_user_code')['AccessToken error'], $e->getPayload(),
config('final-logger.error_code')['Unauthorized'], $e->getTraceAsString(), $e);
} else {
$userCode = config('final-logger.error_user_code')['all unexpected errors'];
return new FinalException('Data (server-side) error has occurred.',
$internalMessage, $userCode, "LowLeverCode : " . $lowLeverCode,
config('final-logger.error_code')['Internal Server Error'], $e->getTraceAsString(), $e);
}
}
}
return [
'general_log_path' => 'your-path', // necessary
];
protected $routeMiddleware = [
//...
'your-name' => \Arwg\FinalLogger\Middlewares\WriteGeneralLog::class
];
// In api, web.php. Surround every route.
Route::group(['middleware' => 'your-name'], function () {
//...
});
// config/final-logger.php
return [
'response_excepted_log_data' => [
'api/v2/final-test-uri/images' => [['baseData', 'data','stats'],['baseData', 'data','img_cnt']]
],
'request_excepted_log_data' => [
// ... others
]
];
// config/final-logger.php
return [
'general_logger' => \Arwg\FinalLogger\GeneralLogHandler::class, // necessary
'error_logger' => \Arwg\FinalLogger\ErrorLogHandler::class, // necessary
'general_log_path' => config('app.dashboard_all_request_response'), // necessary
'request_excepted_log_data' => [
'final-test-uri' => [['password'],['password_reset']]
],
'response_excepted_log_data' => [
'final-test-uri' => [['a','b', 'c'], ['a','d']]
],
'success_code' => [
'OK' => 200,
'No Content' => 204
],
'error_code' => [
'Internal Server Error' => 500, // necessary
'Bad Request' => 400,
'Unauthorized' => 401,
'Not Found' => 404,
'Request Timeout' => 408,
'Precondition Failed' => 412,
'Unprocessable Entity' => 422
],
'error_user_code' => [
'all unexpected errors' => 900, // necessary
'socket error' => 1113,
'DB procedure...' => 1200,
]
];
// In case of NOT Ajax, add a current exception to the last parameter of FinalException (like $e below).
throw new FinalException('requested email address is not valid.',
"", config('final-logger.error_user_code')['parameter validation'], "",
config('final-logger.error_code')['Bad Request'], $e);
Payload::createFinalException($e, function ($e){
// example
return new FinalException(...);
// OR I recommend creating one function as shown Number 1.
});
try {
$binary = Storage::disk('aaa')->get($file_name);
}catch (\Exception $e){
Payload::processFinalErrorLog(config('final-logger.error_code')['Internal Server Error'], \Arwg\FinalLogger\Exceptions\CommonExceptionModel::getExceptionMessage('error when opening a file',
$e->getMessage(),
'lowlevelcode : ' . $e->getCode(), config('final-logger.error_user_code')['all unexpected errors'], $e->getTraceAsString()));
}
class ArticleController extends Controller
{
public function index(Request $request)
{
$data = $this->getData($$request->all());
return Payload::renderSuccess(['list' => $data], config('final-logger.success_code')['OK']);
}
}