Sometimes, you might have operations like crons running PHP scripts behind the scenes. If there are any errors in it, it can become difficult to debug them since they might not affect the entire website. Whether you are doing this with any PHP framework or in a Joomla component, logging can help you debug such issues.
Here is how you can use Joomla's logging functionality to log your errors to a file.
jimport('joomla.log.log'); //import this file on top of the file
 
//write db log code inside your function
JLog::addLogger(
array(
        //Sets file name
        'text_file' => 'com_test.errors.php'
        ),
 
//Sets all JLog messages to be set to the file
 JLog::ALL,
 //Chooses a component name
 'com_test'
 );
 
//insertion code :-
if(!$db->insertObject($table_name, $final_array, 'id')){
 
$logEntry = $db->stderr();   //logentry variable
 
// Log my extension errors only.
JLog::add($logEntry, JLog::WARNING, 'com_test');
 
return false;
} 

Logs shall be stored in yoursiteroot/logs/com_test.errors.php