本文實(shí)例講述了Laravel框架實(shí)現(xiàn)的記錄SQL日志功能。分享給大家供大家參考,具體如下:
在項(xiàng)目開發(fā)過程中或者是性能優(yōu)化中,經(jīng)常會(huì)有要查看執(zhí)行sql的情況,然而Laravel日志默認(rèn)不記錄執(zhí)行sql。好在留有相關(guān)接口,我們可以很方便的就是想SQl日志功能。
在 App/Providers/EventServiceProvider:class 中的$listen中新增如下
protected $listen = [ 'App/Events/Event' => [ 'App/Listeners/EventListener', ], // 新增SqlListener監(jiān)聽QueryExecuted 'Illuminate/Database/Events/QueryExecuted' => [ 'App/Listeners/SqlListener', ],];
新建SqlListener監(jiān)聽器
方法1,手動(dòng)創(chuàng)建,在App/Listeners/SqlListener.php 文件,內(nèi)容如下
namespace App/Listeners;use Illuminate/Database/Events/QueryExecuted;class SqlListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param =QueryExecuted $event * @return void */ public function handle(QueryExecuted $event) { // 在這里編寫業(yè)務(wù)邏輯 }}方法2,使用命令行創(chuàng)建,命令如下
// 該命令必須在項(xiàng)目跟目錄下執(zhí)行,因?yàn)轫?xiàng)目跟目錄下才有artisan文件。// 該命令可以自動(dòng)創(chuàng)建SqlListener文件,但是QueryExecuted這個(gè)類的導(dǎo)入可能會(huì)有點(diǎn)問題,自己改下。> php artisan make:listener SqlListener -e=QueryExecuted
在handle方法中編寫記錄sql的業(yè)務(wù)邏輯,如:
/** * Handle the event. * * @param =QueryExecuted $event * @return void */public function handle(QueryExecuted $event) { $sql = str_replace("?", "'%s'", $event->sql); $log = vsprintf($sql, $event->bindings); $log = '[' . date('Y-m-d H:i:s') . '] ' . $log . "/r/n"; $filepath = storage_path('logs/sql.log'); file_put_contents($filepath, $log, FILE_APPEND); // 這里也可以直接用Log::info() 里的函數(shù),只是這樣會(huì)和其他調(diào)試信息摻在一起。 // 如果要用Log里的函數(shù),別忘記了引入Log類。}希望本文所述對大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選