php設(shè)置日志輸出的方法:使用php的寫入文件函數(shù),把數(shù)據(jù)寫入到事先定義好的文件中,代碼為【file_put_contents(file,data,mode,context)】。
php設(shè)置日志輸出的方法:
思想:在想要輸出log日志的地方,使用php的寫入文件函數(shù),把數(shù)據(jù)寫入到事先定義好的文件中。
php代碼如下:
//輸出日志 public function outputLog() { logOutput(time()); sleep(3); $arr = array("k1" => "v1", "k2" => "v2"); logOutput($arr); $this->display(); } logOutput()函數(shù): /** * @param string,array $data 需要輸出到日志中的數(shù)據(jù) * @return null */ function logOutput($data) { //數(shù)據(jù)類型檢測 if (is_array($data)) { $data = json_encode($data); } $filename = "./log/".date("Y-m-d").".log"; $str = date("Y-m-d H:i:s")." $data"."n"; file_put_contents($filename, $str, FILE_APPEND|LOCK_EX); return null; }
file_put_contents() 函數(shù)把一個(gè)字符串寫入文件中。
與依次調(diào)用 fopen(),fwrite() 以及 fclose() 功能一樣。
語法
file_put_contents(file,data,mode,context)
參數(shù) 描述
-
file 必需。規(guī)定要寫入數(shù)據(jù)的文件。如果文件不存在,則創(chuàng)建一個(gè)新文件。
-
data 可選。規(guī)定要寫入文件的數(shù)據(jù)??梢允亲址?、數(shù)組或數(shù)據(jù)流。
-
mode 可選。規(guī)定如何打開/寫入文件??赡艿闹担?/p>
FILE_USE_INCLUDE_PATH
FILE_APPEND 追加數(shù)據(jù)而不是覆蓋
LOCK_EX 寫入數(shù)據(jù)時(shí),鎖住文件,防止其他人對文件的改動(dòng)
-
context 可選。規(guī)定文件句柄的環(huán)境。(不懂何用)
context 是一套可以修改流的行為的選項(xiàng)。若使用 null,則忽略。
意義:
-
在可能出錯(cuò)的地方,進(jìn)行調(diào)試時(shí),輸出錯(cuò)誤信息
-
輸出變量,進(jìn)行調(diào)試,可以避免平常的var_dump、dump函數(shù)打印一長串的數(shù)據(jù),影響頁面布局
相關(guān)免費(fèi)學(xué)習(xí)推薦:php編程(視頻)