CodeSOD: A Big Ol’ Log

We've already picked on bad logging code this week, but we haven't picked on PHP in awhile, so let's look at some bad PHP logging code, from Kris.

        $path = self::getPath();

        if (file_exists($path)) {
            $content = file_get_contents($path);
        } else {
            $content = "";
        $content .= "\n" . date('Y-m-d H:i') . " | " . $message;
        file_put_contents($path, $content);

This is the interior of the log function, which takes a logging message and outputs it to a file.

The "magic" in this code is the call to file_get_contents, which loads an entire file into memory as a string. This is done for every log message. We load the entire file, append the new message, and then write the entire string back to the file. And, I'm not certain about PHP's concatenate implementation, but if it's like most languages, strings are immutable, and I suspect this makes a complete copy of the original file contents as part of concatenation.

For small log files, this is bad. This particular application frequently ended up with multi-gigabyte log files. This, as it turned out, wasn't good for performance, but was an excellent way to use as much RAM as possible and stress test their disk.

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published. Required fields are marked *