简体   繁体   中英

cakephp database logger - how to access controller variable?

I am following the cakephp documentation to implement the database logger function. I got everything working after creating the logger class in

app/Lib/Log/Engine/DatabaseLogger.php

and add these lines to bootstrap

CakeLog::config('otherFile', array(
'engine' => 'DatabaseLogger',
'model' => 'LogEntry',
// ...
));

After this I can log to the database by calling

CakeLog::info(message);

Everything works fine, but then I ran into problem trying to automatically log the user's username and ip address. I have searched for many solutions onlien but I do not seems to be able to find an answer. Is it possible to access the controller in the DatabaseLogger class?

You don't need access to the controller

The information you need is effectively global, you don't need to access the controller object to get it.

Client IP

You can use the Router::getRequest method to get the current request object and retrieve the client IP from that:

$request = Router::getRequest();
$ip = $request->clientIp();

Or simply use the env method:

$ip = env('REMOTE_ADDR');

Current User's name

For this, just use the static session interface :

$name = CakeSession::read('Auth.User.name');

This will hopefully get you going in the right direction. I'm currently in the process of migrating some of my CakePHP apps up to 2.2. I'm not 100% certain on this, but it seems to be about the way to go about this. I am thinking about using database logging and I like your idea so let me know how this works out. If it doesn't, provide feedback and I'll dig deeper. ;)

Create your LogEntry model (database table) to include fields for the username and the ip address.

Create an AppController. In the beforeFilter method place the user's ip address in their session. The CakeRequest object will contain their IP address.

$this->request->clientIp();

In your beforeSave() method for that model, you will collect the username and IP address.

To access the username field (assuming you are using Auth component and clientIp as the key to their ip address):

App::import('Component', 'Session');
$Session = new SessionComponent();
$user = $Session->read('Auth.User');
$ip = $Session->read('clientIp');

Assign these to the right fields so that they will be saved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM