elsa-core/src/modules/Elsa.Python/HostedServices/PythonGlobalInterpreterManager.cs
Sipke Schoorstra 6d4a428c80 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.
2023-12-27 20:18:08 +01:00

56 lines
1.6 KiB
C#

using Elsa.Python.Options;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Python.Runtime;
namespace Elsa.Python.HostedServices;
/// <summary>
/// Initializes the Python engine.
/// </summary>
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, ILogger<PythonGlobalInterpreterManager> logger)
{
_options = options;
_logger = logger;
}
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
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");
}
return Task.CompletedTask;
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
if(_mainThreadState != IntPtr.Zero)
{
PythonEngine.EndAllowThreads(_mainThreadState);
PythonEngine.Shutdown();
}
return Task.CompletedTask;
}
}