0

I'm trying to log every write operation so I'm using the afterSave and afterDelete callbacks in AppModel. Basically I need to log(for the moment): the model , the controller function, the loggedin user data and the remote ip It seems that I was able to get all of them but I don't know how to get the controller function name. This is the aftersave function I have now:

public function afterSave($created) {
    App::uses('Folder', 'Utility');
    $month = date("y-m");
    if(!is_dir('../tmp/logs/'.$month)) {
        $dir = new Folder('../tmp/logs/'.$month, true);
    }
    App::uses('CakeSession', 'Model/Datasource');
    $user_id = CakeSession::read('Auth.User.username');
    if($created) {
        $id =   'New';
    } else {
        $id =   $this->data[$this->alias]['id'];
    }
    $str = 'WRITE Action. Model: '.$this->alias.'. Controller: functon_name. ID:'.$id.'. Username: '.$user_id.'. Client IP: '.$this->getIP();
    CakeLog::write($month.'/'.date("d-m-y"), $str);
}

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
slacky
  • 101
  • 1
  • 2
  • 8

1 Answers1

2

You're doing this on the model, which has no knowledge of the controller (and really shouldn't). I'd suggest copying the CakeRequest object to the model so you have that information. Here's one way:

//controller
function beforeFilter() {
  $this->{$this->modelClass}->request = $this->request;
}

Then you can access the request object from the model. Use $this->request['params']['action'] to get the current dispatched action.

It's worth suggesting that you might want to move this to the read() method on a custom datasource, as afterSave() can possibly be skipped and therefore not logged.

jeremyharris
  • 7,884
  • 22
  • 31
  • Thank you Jeremy. I did as you said, I put the code in beforefilter, in the app controller. However The problem was that for some reason I had an empty output on $this->request['params']['action'], in the appmodel so I used $this->request->action which worked well. Can you explain better in which cases the afterSave could be skipped? Thank again, that was really useful. – slacky Apr 16 '12 at 17:42
  • `afterSave` can be skipped if you pass `'callbacks' => false` in the save options. Behaviors, etc. can modify this if they wanted to. – jeremyharris Apr 16 '12 at 17:50