Answer the question
In order to leave comments, you need to log in
Formation of a log line only if the required debugging level is enabled?
Good day. I ran into a problem with the execution time of some scripts in one large project. I wanted to try to win at least half a second by reducing the formation of a line for logging. There are a lot of logs, the log call looks something like this:
class SomeClass(){
function someFunction(string $param1, string $param2, int $param3): bool{
debugLog(
'log-level-3',
__METHOD__ ,
': start with arguments: ' .PHP_EOL. $param1 . PHP_EOL. $param2.PHP_EOL . $param3
);
// code
$success = $this->doSomething();
debugLog('log-level-3', __METHOD__, ': end ' . $success ? 'successfully' : 'failure');
return $success;
}
}
class SomeClass(){
function someFunction(string $param1, string $param2, int $param3): bool{
debugLog(
'log-level-3',
__METHOD__ ,
function() use ($param1, $param2, $param3){
return ': start with arguments: ' .PHP_EOL. $param1 . PHP_EOL. $param2.PHP_EOL . $param3;
}
);
// code
$success = $this->doSomething();
debugLog('log-level-3', __METHOD__, function() use ($success) { return ': end ' . $success ? 'successfully' : 'failure';});
return $success;
}
}
Answer the question
In order to leave comments, you need to log in
Wrote a small benchmark for 1,000,000 entries in the log, provided that logging is not performed in any of the cases. One function collects a string and passes it, and the second function calls some callback that generates a string if a log is needed.
function logText(string $message, int $logLevel = LOG_WARNING){
if ($logLevel <= LOG_WARNING){
file_put_contents(__DIR__ . '/logText.log', date('H:m:s') . "\t$message\n", FILE_APPEND);
}
}
function logFn($renderMsg, int $logLevel = LOG_WARNING){
if ($logLevel <= LOG_WARNING){
$text = $renderMsg();
file_put_contents(__DIR__ . '/logText.log', date('H:m:s') . "\t$text\n", FILE_APPEND);
}
}
$a = microtime(true);
for ($i = 1000000; $i > 0; $i--){
logText("$i some text value " . ($i*100), LOG_DEBUG);
}
$time = microtime(true)-$a;
echo "<h3>time log message: $time</h3>";
$a = microtime(true);
for ($i = 1000000; $i > 0; $i--){
logFn(
function() use ($i){
return "$i some text value " . ($i*100);
}, LOG_DEBUG
);
}
$time = microtime(true)-$a;
echo "<h3>time fn message: $time</h3>";
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question