{"record":{"id":"75e0ea1d146a55b4","repo":"nautechsystems/nautilus_trader","slug":"logging-already-initialized-but-new-guard-could-no","errorCode":null,"errorMessage":"Logging already initialized but new guard could not be created","messagePattern":"Logging already initialized but new guard could not be created","errorType":"exception","errorClass":"anyhow::Error","httpStatus":null,"severity":"error","filePath":"crates/common/src/logging/logger.rs","lineNumber":921,"sourceCode":"    /// # Errors\n    ///\n    /// Returns an error if the logger fails to register or initialize the background thread.\n    #[cfg_attr(\n        not(all(feature = \"simulation\", madsim)),\n        expect(clippy::needless_pass_by_value)\n    )]\n    pub fn init_with_config(\n        trader_id: TraderId,\n        instance_id: UUID4,\n        config: LoggerConfig,\n        file_config: FileWriterConfig,\n    ) -> anyhow::Result<LogGuard> {\n        let mut lifecycle = LOGGER_LIFECYCLE.lock();\n\n        match *lifecycle {\n            LoggerLifecycle::Running => {\n                return LogGuard::new_locked().ok_or_else(|| {\n                    anyhow::anyhow!(\n                        \"Logging already initialized but new guard could not be created\"\n                    )\n                });\n            }\n            LoggerLifecycle::Terminated => {\n                anyhow::bail!(\"Logging has been shut down and cannot be re-initialized\");\n            }\n            LoggerLifecycle::Uninitialized => {}\n        }\n\n        let (tx, rx) = std::sync::mpsc::channel::<LogEvent>();\n        let filter_policy = FilterPolicy::from_config(&config);\n\n        #[cfg(not(all(feature = \"simulation\", madsim)))]\n        let handle = std::thread::Builder::new()\n            .name(LOGGING.to_string())\n            .spawn({\n                let config = config.clone();","sourceCodeStart":903,"sourceCodeEnd":939,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/common/src/logging/logger.rs#L903-L939","documentation":"When the logger lifecycle is already `Running`, an init call simply hands back a locked LogGuard referencing the global sender. `LogGuard::new_locked()` returns None if the guard's internal state (global sender) cannot be established, and the code surfaces that as this error: logging is up, but a second guard handle could not be created.","triggerScenarios":"Calling logging init (e.g. nautilus_pyo3 init_logging or the Rust init) while a previous logger is still running, in a process where the global sender/static state is unavailable or was never fully established — e.g. after fork in a child process, or across unusual embed boundaries where statics did not carry over.","commonSituations":"Re-initializing logging on every script run in one interpreter; embedding multiple node instances in one process; Unix fork() after logger init leaving stale statics in the child; conflicting logging bootstrap between host app and library.","solutions":["Initialize logging once at process start and reuse/clone the returned LogGuard instead of re-initializing.","Keep the original guard alive for the process lifetime; drop it only when you intend shutdown.","In forked children, fully re-create logging state (or avoid forking after init) so the global sender is valid.","If re-init is required, shut down the running logger first (drop guard) and handle the Terminated lifecycle path."],"exampleFix":"// before\nlet guard1 = init_logging(...)?;\nlet guard2 = init_logging(...)?; // Running path fails here\n// after\nlet guard = init_logging(...)?; // hold for process lifetime\nstd::mem::forget(guard); // or store globally; never re-init","handlingStrategy":"try-catch","validationCode":"// Rust: only init when not already running\nif logging_is_running() { return Ok(existing_guard()); }","typeGuard":"fn ensure_guard(g: Option<LogGuard>) -> anyhow::Result<LogGuard> {\n    g.ok_or_else(|| anyhow::anyhow!(\"no log guard available\"))\n}","tryCatchPattern":"match init_logging(cfg) {\n    Ok(g) => g,\n    Err(e) if e.to_string().contains(\"already initialized\") => Ok(shared_guard()),\n    Err(e) => return Err(e),\n}","preventionTips":["Initialize logging once per process and store the guard globally.","Never re-init on repeated script/strategy runs; reuse the running logger.","Avoid fork() after logging init; re-init inside children if needed.","Keep guard lifetime tied to process lifetime, not per-call scope."],"tags":["rust","logging","lifecycle","initialization"],"backgroundTag":"module-init-failed","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}