From 6d4a428c80f1968d3d4f8f2d47d97213e7128f8e Mon Sep 17 00:00:00 2001 From: Sipke Schoorstra Date: Wed, 27 Dec 2023 20:18:08 +0100 Subject: [PATCH] Add logging to PythonGlobalInterpreterManager Implemented logging in the PythonGlobalInterpreterManager class to ensure visibility during Python engine initialization and shutdown. These changes are important for spotting errors, troubleshooting issues, and understanding potential failures in Python engine initialization. --- .../PythonGlobalInterpreterManager.cs | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/modules/Elsa.Python/HostedServices/PythonGlobalInterpreterManager.cs b/src/modules/Elsa.Python/HostedServices/PythonGlobalInterpreterManager.cs index 7cda4baf1..4b75d927f 100644 --- a/src/modules/Elsa.Python/HostedServices/PythonGlobalInterpreterManager.cs +++ b/src/modules/Elsa.Python/HostedServices/PythonGlobalInterpreterManager.cs @@ -1,5 +1,6 @@ using Elsa.Python.Options; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Python.Runtime; @@ -11,14 +12,16 @@ namespace Elsa.Python.HostedServices; public class PythonGlobalInterpreterManager : IHostedService { private readonly IOptions _options; + private readonly ILogger _logger; private IntPtr _mainThreadState; /// /// Initializes a new instance of the class. /// - public PythonGlobalInterpreterManager(IOptions options) + public PythonGlobalInterpreterManager(IOptions options, ILogger logger) { _options = options; + _logger = logger; } /// @@ -26,17 +29,28 @@ public class PythonGlobalInterpreterManager : IHostedService { if (!string.IsNullOrEmpty(_options.Value.PythonDllPath)) Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", _options.Value.PythonDllPath); + + try + { + PythonEngine.Initialize(); + _mainThreadState = PythonEngine.BeginAllowThreads(); + } + catch (Exception e) + { + _logger.LogWarning(e, "Failed to initialize Python engine"); + } - PythonEngine.Initialize(); - _mainThreadState = PythonEngine.BeginAllowThreads(); return Task.CompletedTask; } /// public Task StopAsync(CancellationToken cancellationToken) { - PythonEngine.EndAllowThreads(_mainThreadState); - PythonEngine.Shutdown(); + if(_mainThreadState != IntPtr.Zero) + { + PythonEngine.EndAllowThreads(_mainThreadState); + PythonEngine.Shutdown(); + } return Task.CompletedTask; } } \ No newline at end of file