Write/saved logs in WordPress

I´m doing a plugin which includes a query to import data from external API into custom post types/taxonomies/medias etc…
The query can be really heavy.
I had to make logs to know exactly what happens.
For the moment I´m saving logs thanks to update_option() to avoid loose logs when I have these kinds of errors :

mysqli_real_connect(): (HY000/2002): Connection refused

Maybe because there are too many action with the database.
I changed define('DB_HOST', 'localhost'); by define('DB_HOST', ''); without any success.

If I´m using a log file, I will have to open/write/close the log file all the time and the algorithme would need more time. That could create a timeout server error.

What could be the best way in my case ?