Laravel记录SQL操作日志的方法
在laravel中我们有一个需求就是,涉及到sql操作的update,insert,delete操作的语句,我们都要写一个日志来记录一下
说说方法吧。
在项目目录app/Providers/AppServiceProvider.php中添加代码
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
DB::listen(function ($query) {
$tmp = str_replace('?', '"' . '%s' . '"', $query->sql);
$tmp = vsprintf($tmp, $query->bindings);
$tmp = str_replace("\\", "", $tmp);
$action = substr($tmp, 0, 6);
if ($action == 'update' || $action == 'delete' || $action == "insert") {
$myfile = fopen("sql.txt", "a+") or die("Unable to open file!");
fwrite($myfile, $tmp . " use_time:" . $query->time . "ms " . date('Y-m-d H:i:s') . " \n\n");
fclose($myfile);
}
});
}
最终在public目录下写入了sql.txt文件中
