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.
This commit is contained in:
parent
c780cb3ffe
commit
6d4a428c80
|
|
@ -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<PythonOptions> _options;
|
||||
private readonly ILogger _logger;
|
||||
private IntPtr _mainThreadState;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PythonGlobalInterpreterManager"/> class.
|
||||
/// </summary>
|
||||
public PythonGlobalInterpreterManager(IOptions<PythonOptions> options)
|
||||
public PythonGlobalInterpreterManager(IOptions<PythonOptions> options, ILogger<PythonGlobalInterpreterManager> logger)
|
||||
{
|
||||
_options = options;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
PythonEngine.EndAllowThreads(_mainThreadState);
|
||||
PythonEngine.Shutdown();
|
||||
if(_mainThreadState != IntPtr.Zero)
|
||||
{
|
||||
PythonEngine.EndAllowThreads(_mainThreadState);
|
||||
PythonEngine.Shutdown();
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue