Yii2 -- log to file immediately
Yii by default logs to a file, and buffers up the log entries into memory and writes them to disk at the very end of the request (or console request). In Yii2, it'll buffer up to 1000 messages by default before it flushes the messages to a log file. This may not be ideal, though, if it's a long-running request and you expect to see the log messages right away rather than all at once after the request completes.
My first stab at this was to simply toggle the "flushInterval" property of the logger to 1, meaning it'd flush its buffer on every log entry. It did not work that way, though, when I tested it.
Each log target has its own "exportInterval" property. A log target can be anything: logging to a file, logging by sending an email, inserting a database row, etc. So this field serves the same purpose, but at the target level. What this means for me I'll need to adjust this property for any log files I want to write to immediately. What I ended up with is:
$logger = \Yii::$app->getLog(); $logger->setFlushInterval(1); foreach ($logger->targets as $logTarget) { if ($logTarget instanceof \yii\log\FileTarget && $logTarget->enabled ) { $logTarget->exportInterval = 1; } }
And now in effect every log entry will be written to disk immediately wherever I execute that code.










