This article has participated in the comment drawing peripheral gift activity, digging gold badge *2, comments related content can participate in the lucky draw to see details

I have written a similar article before and received good feedback. This article will be further upgraded and several application scenarios will be added.

  1. Interface error details (request parameters, request body, response time, error information, etc.) are synchronized to the pin group in real time
  2. Slowly query interface information and synchronize it to the nail group (adding interface whitelist is supported)
  3. Error information of non-mandatory problems is synchronized to the nail group for timely tracking and positioning

Based on the above scenario, we can use this idea for reference and discuss better implementation and application scenarios in the comments section.

First, let me explain my code language: the PHP-based Laravel framework

The core code is shown below, with critical code commented out and irrelevant code omitted.

Modifying Log Configuration

  1. Custom channel
  2. Distinguish which environments use custom channels
  3. Powered by the elegant monolog
<? php use Monolog\Handler\NullHandler; use Monolog\Handler\StreamHandler; use Monolog\Handler\SyslogUdpHandler; return [ 'default' => env('LOG_CHANNEL', 'stack'), 'channels' => [ 'stack' => [ 'driver' => 'stack', // In addition to using daily to save daily logs to logs/laravel.log, Env ("APP_ENV") == 'test'? ['daily', 'dingding'] ['daily'], 'ignore_exceptions' => false,], // Configure the pegdrive options of monolog' dingding' => [' driver' => 'monolog', 'level' = > 'error' and 'handler' = > \ App \ handler \ DingdingLogHandler: : class, / / a custom handler, 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', 'days' => 14, ], [,];Copy the code

Use 3 vertical rows for the non-important code above. Omit the display, the following code snippets are also in 3 vertical order of non-important. Omitted.

Custom nail Handler

  1. You can easily get the Request link, Request parameters, and Request header from Illuminate\Support\Facades\Request
  2. The Error message is passed in externally, and the default Error message is run into the send() method
<? php namespace App\Handler; use App\Library\CurlRequest; use App\Library\Utility; use Monolog\Logger; use Monolog\Handler; class DingdingLogHandler extends Handler\AbstractProcessingHandler { private $apiKey; private $channel; public function __construct( $level = Logger::ERROR, bool $bubble = true ) { parent::__construct($level, $bubble); } protected function write(array $record): void { $this->send($record['formatted']); } protected function send(string $message): void { $microSecond = Utility::getMicroSecond(); $key = "xxxx"; $hashString = hash_hmac("sha256", $microSecond ."\n" . $key, $key, true); $sign = urlencode(base64_encode($hashString)); CurlRequest::post("https://oapi.dingtalk.com/robot/send?access_token=xxxxx&timestamp=".$microSecond."&sign=".$sign, [ "msgtype" => "text", "at" => [ "atMobiles" => [ "xxxx", "xxxx" ] ], "Text" = > [" content "= >" Request link: \ n ". Request: : path (). "Request parameters: \ n \ n". \ GuzzleHttp \ json_encode (Request: : toArray ()). "\n Request Header :\n". \GuzzleHttp\json_encode(Request::header()). "\n Error Message :\n". $message]]); }}Copy the code

Effect:

The above two pieces of code are the core codes to realize the synchronization of error information to the pin group. The following are the implementation ideas of various scenarios:

The core idea of slow query:

Response middleware:

  1. This is the network request and response middleware, left and right network requests will be processed by this middleware
  2. The calculation of time-consuming operations is only deployed in the test environment and removed when online. (Or, better yet, the dynamic variables of the production or development environment)
  3. In order to avoid frequent interface reminders, we can set the whitelist
  4. The difference between Log::info() and Log::error() is that slow queries are only stored in logs. The latter not only stores information to the log, but also synchronizes information to the pin (we define the log level of the pin channel as error)
<? php namespace App\Http\Middleware; use App\Library\Utility; use App\Model\ErrorCode; use Closure; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Request; class ApiResponse { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $requestMicroSecond = Utility::getMicroSecond(); $response = $next($request); if (! is_array($response->original) && (int)($response->original) ! = 0) { $errCode = (int)$response->original; Self ::calcTime($requestMicroSecond); return response()->json(['ret' => $errCode, 'msg' => ErrorCode::getErrorMsg($errCode)]) ->header("Timestamp", Utility::getMicroSecond()); } else { $ret = ['ret' => 0, 'msg' => ErrorCode::getErrorMsg(0)]; if (! empty($response->original) && is_array($response->original)) { $ret['data'] = $response->original; } else if ($response->original ! = Null) { echo $response->original; exit; } self::calcTime($requestMicroSecond); return response()->json($ret)->header("Timestamp", Utility::getMicroSecond()); $requestTime = [' API /pay/order/status', 'API /pay/order/repair', 'api/log/token/get', ]; $responseTime = Utility::getMicroSecond(); $consumeTime = $responseTime - $requestTime; if ($consumeTime >= 1000) { if (in_array(Request::path(), $consumeTime. "ms"); $consumeTime. "ms"); } else {Log::error($consumeTime. "ms"); }}}}Copy the code

rendering

Troubleshoot unnecessary problems

How it works: We can print an error Log with Log::error() in the offending code segment, which when triggered will be synchronized to the pin group message.

For example, the error scenario is that the Android client occasionally fails to verify the verification code when it sends SMS verification code to log in. The client is sure that it has passed the correct verification code to the server, and the server responds: you cannot fail to pass the verification if you have passed the normal verification code.

This kind of argument is useless, plus this kind of unnecessary problem, print the Log to locate the problem, it takes a long time to climb the Log, and can not timely know when the error, so synchronization error information to the nail group is a very typical application scenario.

In the code

public function validateMsg(Request $request) { $authCode = new AuthCode($request->phone); $code = $authCode->get(); if (empty($code) || $code ! $request->code) {Log::error(" AuthCode:". $code. "); return ErrorCode::TYPE_CODE_INCORRECT; } $authCode->delCode(); ...}Copy the code

rendering

The local authCode was empty and was cleaned, resulting in a verification failure.

conclusion

The above is the real-time interface alarm system based on the services of Dingding and Laravel.

Feel free to join us in the comments section for a chance to win nuggets perimeter prizes.

Rules for sweepstakes

First of all, we welcome your positive comments and thank you for your support. Here are the rules for the draw

All comments need to comply with the nuggets community guidelines. Otherwise, you cannot participate in the activity.

Random draw in comments area, maximum one badge per person.

If the winner cannot be contacted, a new draw will be made.

The drawing will be announced on September 12.

You can add my wechat: Wangzhongyang0601, add friends note: nuggets lucky draw.

Through the three-party software lottery, the results of the lottery will be announced to everyone in the wechat group live video recording.