shell: log_backend: Fix fifo cleanup

When shell log backend was disabled fifo used only in
deferred mode was unconditionally flushed which lead to
errors in immediate mode where fifo was not present. On
the other hand, in case of LOG2_MODE_DEFERRED fifo (mpsc_pbuf)
was initialized in enable stage.

In order to clean things up, deferred v1 fifo flushing and
deferred v2 mpsc pbuf initialization were moved to fifo_reset
function which is called when shell log backend is enabled.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
diff --git a/subsys/shell/shell_log_backend.c b/subsys/shell/shell_log_backend.c
index 9fa9fca..50d2f7d 100644
--- a/subsys/shell/shell_log_backend.c
+++ b/subsys/shell/shell_log_backend.c
@@ -17,6 +17,35 @@
 	return length;
 }
 
+static struct log_msg *msg_from_fifo(const struct shell_log_backend *backend)
+{
+	struct shell_log_backend_msg msg;
+	int err;
+
+	err = k_msgq_get(backend->msgq, &msg, K_NO_WAIT);
+
+	return (err == 0) ? msg.msg : NULL;
+}
+
+/* Set fifo clean state (in case of deferred mode). */
+static void fifo_reset(const struct shell_log_backend *backend)
+{
+	if (IS_ENABLED(CONFIG_LOG2_MODE_DEFERRED)) {
+		mpsc_pbuf_init(backend->mpsc_buffer,
+			       backend->mpsc_buffer_config);
+		return;
+	}
+
+	/* Flush pending log messages without processing. */
+	if (IS_ENABLED(CONFIG_LOG_MODE_DEFERRED)) {
+		struct log_msg *msg;
+
+		while ((msg = msg_from_fifo(backend)) != NULL) {
+			log_msg_put(msg);
+		}
+	}
+}
+
 void z_shell_log_backend_enable(const struct shell_log_backend *backend,
 				void *ctx, uint32_t init_log_level)
 {
@@ -31,12 +60,8 @@
 		err = shell->iface->api->enable(shell->iface, true);
 	}
 
-	if (IS_ENABLED(CONFIG_LOG2_MODE_DEFERRED)) {
-		mpsc_pbuf_init(backend->mpsc_buffer,
-			       backend->mpsc_buffer_config);
-	}
-
 	if (err == 0) {
+		fifo_reset(backend);
 		log_backend_enable(backend->backend, ctx, init_log_level);
 		log_output_ctx_set(backend->log_output, ctx);
 		backend->control_block->dropped_cnt = 0;
@@ -44,26 +69,6 @@
 	}
 }
 
-static struct log_msg *msg_from_fifo(const struct shell_log_backend *backend)
-{
-	struct shell_log_backend_msg msg;
-	int err;
-
-	err = k_msgq_get(backend->msgq, &msg, K_NO_WAIT);
-
-	return (err == 0) ? msg.msg : NULL;
-}
-
-static void fifo_flush(const struct shell_log_backend *backend)
-{
-	struct log_msg *msg;
-
-	/* Flush log messages. */
-	while ((msg = msg_from_fifo(backend)) != NULL) {
-		log_msg_put(msg);
-	}
-}
-
 static void flush_expired_messages(const struct shell *shell)
 {
 	int err;
@@ -127,7 +132,6 @@
 
 void z_shell_log_backend_disable(const struct shell_log_backend *backend)
 {
-	fifo_flush(backend);
 	log_backend_disable(backend->backend);
 	backend->control_block->state = SHELL_LOG_BACKEND_DISABLED;
 }