Hooking into page not found event
Go to Home » Administration » Configuration » System and set Error pages to some not used yet value, like http://localhost/403 and http://localhost/404, or http://localhost/forbidden and http://localhost/not-found. Then create a custom module. Implement hook_menu() to provide these pages. Use all logic you need in page callback function.