{"record":{"id":"c63b427ca34c6dac","repo":"moodle/moodle","slug":"fwrite-called-but-this-resource-is-not-a-resource","errorCode":null,"errorMessage":"fwrite called but $this->resource is not a resource","messagePattern":"fwrite called but \\$this->resource is not a resource","errorType":"exception","errorClass":"LogicException","httpStatus":null,"severity":"error","filePath":"public/lib/monolog/src/Monolog/Handler/SocketHandler.php","lineNumber":301,"sourceCode":"            throw new \\LogicException('streamSetChunkSize called but $this->resource is not a resource');\n        }\n\n        if (null === $this->chunkSize) {\n            throw new \\LogicException('streamSetChunkSize called but $this->chunkSize is not set');\n        }\n\n        return stream_set_chunk_size($this->resource, $this->chunkSize);\n    }\n\n    /**\n     * Wrapper to allow mocking\n     *\n     * @return int|false\n     */\n    protected function fwrite(string $data): int|bool\n    {\n        if (!\\is_resource($this->resource)) {\n            throw new \\LogicException('fwrite called but $this->resource is not a resource');\n        }\n\n        return @fwrite($this->resource, $data);\n    }\n\n    /**\n     * Wrapper to allow mocking\n     *\n     * @return mixed[]|bool\n     */\n    protected function streamGetMetadata(): array|bool\n    {\n        if (!\\is_resource($this->resource)) {\n            throw new \\LogicException('streamGetMetadata called but $this->resource is not a resource');\n        }\n\n        return stream_get_meta_data($this->resource);\n    }","sourceCodeStart":283,"sourceCodeEnd":319,"githubUrl":"https://github.com/moodle/moodle/blob/48ea8c33227277e916cdd4079dbecef448b37f2c/public/lib/monolog/src/Monolog/Handler/SocketHandler.php#L283-L319","documentation":"SocketHandler buffers writes through fwrite(), which first asserts that $this->resource is still an open socket stream. If the socket resource has been closed, never connected, or was invalidated by the remote peer, is_resource() fails and a LogicException is thrown instead of passing garbage to fwrite. This is an internal invariant check: the class expects connect() to have run and close() not to have run before any write.","triggerScenarios":"Calling write()/fwrite() after close() or closeSocket(); writing when connectIfNotConnected() was skipped or failed earlier; the remote end closed the connection leaving a dead resource; a persistent socket reaped by the server between requests.","commonSituations":"Logging to a syslog/TCP collector that restarted mid-request; long-running daemons reusing a handler whose socket timed out; code calling $handler->close() while the handler is still registered with the logger; shared handler across forked processes.","solutions":["Check isConnected() before writing and let connectIfNotConnected() re-establish the socket.","Wrap the write in try/catch for LogicException, reconnect once, then retry the write.","Ensure nothing in your code calls close()/closeSocket() while the handler is still in use.","Enable persistent sockets or add a reconnect loop if the log target drops idle connections.","Catch RuntimeException 'Could not write to socket' alongside it and recreate the handler as a last resort."],"exampleFix":"// before\n$handler->close();\n$logger->error('oops'); // fwrite called but $this->resource is not a resource\n// after\nif (!$handler->isConnected()) {\n    $handler = new \\Monolog\\Handler\\SocketHandler($endpoint);\n    $handler->setPersistent(true);\n}\n$logger->error('oops');","handlingStrategy":"type-guard","validationCode":"if (!is_resource($socketResource)) { reconnectHandler(); }","typeGuard":"function isOpenSocket($r): bool { return is_resource($r) || $r instanceof \\Socket; }","tryCatchPattern":"try { $handler->write($record); } catch (\\LogicException $e) { $handler->close(); $handler = new SocketHandler($endpoint); $handler->write($record); }","preventionTips":["Never write after close(); treat close as terminal for the handler instance.","Use persistent sockets for long-running workers and verify liveness periodically.","Catch LogicException/RuntimeException at the logging boundary and swap in a fresh handler.","Monitor log endpoint health; a dead remote manifests as these invariant failures."],"tags":["php","sockets","logging","monolog","state-error"],"backgroundTag":"internal-invariant-violation","analyzedSha":"48ea8c33227277e916cdd4079dbecef448b37f2c","analyzedAt":"2026-09-14T20:34:48.527Z","contentChangedAt":"2026-09-14T20:34:48.527Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}