W
W
WebDev2021-03-22 11:48:47
PHP
WebDev, 2021-03-22 11:48:47

How to organize the code in this case?

Hello! I need to cover the project with logs. In some parts of the code, you need to write data to the database. I have identified several entities that I need to log:
1. User request
2. Server response to the user
3. Exceptions
4. Payment system responses
Probably something else will need to be logged later, but so far so.
I decided to do this:

interface LoggerInterface
{
    public function log($data);
}

class RequestLogger implements LoggerInterface
{
    public function log($request)
    {
        $activeRecord->insert(
            'request_id' => $request->id,
            'headers' => $request->headers,
            //...
         );
    }
}

class ResponseLogger implements LoggerInterface
{
    public function log($request, $response)
    {
        $activeRecord->insert(
            'request_id' => $request->id,
            'headers' => $response->headers,
            //...
         );
    }
}

class ExceptionLogger implements LoggerInterface
{
    public function log($exception)
    {
        $activeRecord->insert(
            'message' => $exception->getLine() . ' ' . $exception->getMessage(),
            //...
         );
    }
}

class CloudPaymentsLogger implements LoggerInterface
{
    public function log($data)
    {
        $activeRecord->insert(
            'status' => $data->status,
            'data' => $data->message,
            //...
         );
    }
}


Now I wrap the routes I need in middleware, call RequestLogger and ResponseLogger there, and inside the code I log data that comes from the payment system using CloudPaymentsLogger, and catch exceptions that fall in catch using ExceptionLogger.
I feel like I'm doing some heresy and it's all wrong. First, ResponseLogger takes 2 arguments, while all other classes take one. Secondly, for some reason PhpStorm swears that the name of the argument in the interface and classes is different. Thirdly, all these classes differ only in how they process data. Probably it is possible to make one class and to transfer the formatted data to it.
Tell me, please, how is it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-03-22
@delphinpro

In general, if you need to screw up logging, just install the package https://github.com/php-fig/log
and don't be distracted by reinventing the wheel. Do some really useful work - covering logs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question