2017-06-09 18 views
1

我正在研究Moodle項目。我想有一種方法可以將我的錯誤寫入PHP中的Log.txt文件。我該如何寫一個自定義函數來將錯誤寫入我的日誌文件中?

下面是我的代碼

類drill_auto_enrolluser擴展\核心\任務\ {scheduled_task

public function execute() { 

    global $DB; 
    $name=""; 
    $description=""; 
    $descriptionformat =""; 
    $userid=""; 
    $templateid=""; 
    $timecreated=""; 
    $timemodified=0; 
    $origtemplateid=NULL; 
    $status=0; 
    $duedate=0; 
    $reviewerid=NULL;  

     $DATA = $DB->get_recordset_sql ("Select name,description,descriptionformat,userid,templateid from vw_new_user_lp"); 

      foreach ($DATA as $id => $rec) { 

       $record = new \stdClass();           
          $record ->name = $rec->name; 
          $record ->description= $rec->description; 
          $record ->descriptionformat=$rec->descriptionformat; 
          $record ->userid= $rec->userid;  
          $record->origtemplateid=$origtemplateid; 
          $record ->templateid=$rec->templateid; 
          $record->status= $status; 
          $record->duedate= $duedate; 
          $record->reviewerid= $reviewerid; 
          $record->timecreated= time(); 
          $record->timemodified = $timemodified; 
          $record->usermodified = $userid; 

       $DB->insert_record('competency', $record); 

     } 

} 

}

+0

你有什麼試過?代碼在哪裏? – LSerni

+0

嗨,我已經添加了我的Moodle PHP code.Yet我寫了任何錯誤日誌代碼。 –

回答

0

在這種情況下,你必須知道錯誤是怎麼報道。這通常通過例外或通過返回值完成。在第一種情況下,如果未捕獲異常,應用程序將中止(這應該是)。

例如,假設插入拋出MoodleDatabaseException類的異常(當然,你需要檢查什麼例外實際上拋出):

try { 
    $DB->insert_record('competency', $record); 
} catch (\MoodleDatabaseException $err) { 
    myErrorLog($err->getMessage()); 
} 

否則,如果該函數返回例如真或假,你會去:

if (true !== $DB->insert_record('competency', $record)) { 
    myErrorLog($DB->functionThatReturnsLastErrorMessage()); 
} 

在這兩種情況下,你需要一個myErrorLog函數。我認爲Moodle有一個日誌工具和you may want to check it out,並且可能會提出更詳細的後續問題。您可能還會根據自己的需要決定使用the Apache error_log facility。在捏,你可以使用文本日誌文件:

function myErrorLog($message = 'no message') { 
    $date = date('Y-m-d H:i:s'); 
    $fp = fopen('/var/log/moodle-errors.log', 'a'); 
    if (!$fp) { 
     throw new \Exception("Could not open log file! Permission error?"); 
    } 
    fwrite($fp, $date . ' ' . $message . "\n"); 
    fclose($fp); 
} 

上述代碼不擔心多用戶鎖定,這可能會有問題。這對於快速和骯髒的調試是很好的;否則你需要使用任何提供的功能(或者看看集成Log4Php或Monolog,也許;但這看起來像一個要求很高的項目)。

更新

由於我沒有太明確的(英語不是我的母語),留給你的的問題,其中定義myErrorLog功能,從而使其隨處可見,但從來沒有定義兩次以避免錯誤。

爲了快速調試,您可以將myErrorLog替換爲error_log,它將輸出到Apache錯誤日誌文件,從而也避免了併發問題和權限問題。

+0

感謝您的回覆,我不想使用模式錯誤記錄功能。我會嘗試你的自定義函數。如果有任何疑問將在這裏發表評論。 –

+0

謝謝,LSemi。您的英文單詞很容易理解。我面臨權限問題。警告:fopen(/moodle_error.txt):無法打開流:權限被拒絕在/ home/onlin200/public_html/mod/certificate/classes第13行的/task/errorlogging_function.php 計劃任務失敗:自動註冊能力課程中的用戶(mod_certificate \ task \ drill_auto_enrolluser),無法打開日誌文件!權限錯誤? –

+0

您正在寫信給/,並且Web服務器沒有權限。嘗試/tmp/moodle-errors.txt或在路徑之前添加一個點:./moodle_error.txt。 – LSerni

相關問題