PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 5, 2022

[FIXED] How to log every GET And POST data in Codeigniter 4?

 March 05, 2022     ajax, codeigniter, codeigniter-4     No comments   

Issue

my web application is doing a lot of AJAX calls (GET and POST) to our CodeIgniter 4 backend. My current approach to debug the AJAX call is setting manual logging messages within every method. Too time-consuming.

Do you know if there is a better way to do that? Overwriting a CI class?

I am happy about every help.


Solution

For logging the request you have to create the "after filters".

First You Define the Class which implements FilterInterface.

    class Logger implements FilterInterface
    {
        use ResponseTrait;
    
    public function before(RequestInterface $request)
        {
         ...   
        }
    
    public function after(RequestInterface $request, ResponseInterface $response)
        {
           ...
        }
    
    }

In the after method, you will need to store the response and then save it using log_message.

public function after(RequestInterface $request, ResponseInterface $response)
    {
        $response_service = \Config\Services::response();
         log_message('info', '{message}', ['message' => $response_service->getJSON()]

    }

Here, I have stored used the response service explicitly and then simply called the getJSON to store the JSON body of the request. You will need to modify this for your problem. Also, do note you don't need to call the response service explicitly. There was another thread that showed how you can save the response implicitly, so you might want to refer to that.

Once the filter is done, you need to register the alias for the routes as below :

public $aliases = ['logger'         =>  \App\Filters\Logger::class];

Once done you can either implement on individual routes or global routes. Below is how you can implement it on global routes:

public $globals = [
    'before' => [
        ...
    ],
    'after'  => [
        'logger',
    ],
];

References : https://codeigniter4.github.io/userguide/incoming/filters.html?highlight=filter

https://codeigniter4.github.io/userguide/incoming/request.html?highlight=request

https://codeigniter4.github.io/userguide/general/logging.html?highlight=log_message



Answered By - Dhaval Chheda
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing