@@ -48,7 +48,7 @@ class Connection extends BaseConnection
4848 */
4949 protected $ connection ;
5050
51- private ?CommandSubscriber $ commandSubscriber ;
51+ private ?CommandSubscriber $ commandSubscriber = null ;
5252
5353 /**
5454 * Create a new database connection instance.
@@ -65,8 +65,6 @@ public function __construct(array $config)
6565
6666 // Create the connection
6767 $ this ->connection = $ this ->createConnection ($ dsn , $ config , $ options );
68- $ this ->commandSubscriber = new CommandSubscriber ($ this );
69- $ this ->connection ->addSubscriber ($ this ->commandSubscriber );
7068
7169 // Select database
7270 $ this ->db = $ this ->connection ->selectDatabase ($ this ->getDefaultDatabaseName ($ dsn , $ config ));
@@ -141,6 +139,40 @@ public function getDatabaseName()
141139 return $ this ->getMongoDB ()->getDatabaseName ();
142140 }
143141
142+ public function enableQueryLog ()
143+ {
144+ parent ::enableQueryLog ();
145+
146+ if (! $ this ->commandSubscriber ) {
147+ $ this ->commandSubscriber = new CommandSubscriber ($ this );
148+ $ this ->connection ->addSubscriber ($ this ->commandSubscriber );
149+ }
150+ }
151+
152+ public function disableQueryLog ()
153+ {
154+ parent ::disableQueryLog ();
155+
156+ if ($ this ->commandSubscriber ) {
157+ $ this ->connection ->removeSubscriber ($ this ->commandSubscriber );
158+ $ this ->commandSubscriber = null ;
159+ }
160+ }
161+
162+ protected function withFreshQueryLog ($ callback )
163+ {
164+ try {
165+ return parent ::withFreshQueryLog ($ callback );
166+ } finally {
167+ // The parent method enable query log using enableQueryLog()
168+ // but disables it by setting $loggingQueries to false. We need to
169+ // remove the subscriber for performance.
170+ if (! $ this ->loggingQueries ) {
171+ $ this ->disableQueryLog ();
172+ }
173+ }
174+ }
175+
144176 /**
145177 * Get the name of the default database based on db config or try to detect it from dsn.
146178 *
@@ -203,8 +235,7 @@ public function ping(): void
203235 /** @inheritdoc */
204236 public function disconnect ()
205237 {
206- $ this ->connection ?->removeSubscriber($ this ->commandSubscriber );
207- $ this ->commandSubscriber = null ;
238+ $ this ->disableQueryLog ();
208239 $ this ->connection = null ;
209240 }
210241
0 commit comments