diff --git a/main/Util/CustomPOILoggerFactory.cs b/main/Util/CustomPOILoggerFactory.cs new file mode 100644 index 000000000..1987da755 --- /dev/null +++ b/main/Util/CustomPOILoggerFactory.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace NPOI.Util +{ + /// + /// Helper class to circumvent Type.GetType & Activator.CreateInstance under AOT + /// + public abstract class CustomPOILoggerFactory + { + public abstract POILogger Create(string name); + } +} diff --git a/main/Util/POILogFactory.cs b/main/Util/POILogFactory.cs index 8f6603b8e..066b1a98c 100644 --- a/main/Util/POILogFactory.cs +++ b/main/Util/POILogFactory.cs @@ -28,6 +28,7 @@ limitations under the License. using System; using System.Collections; +using System.Collections.Generic; using System.Configuration; namespace NPOI.Util @@ -51,6 +52,14 @@ public class POILogFactory */ private static String _loggerClassName = null; + private static readonly string BuiltInNameNullLogger = typeof(NullLogger).Name; + private static readonly string BuiltInNameSystemOutLogger = typeof(SystemOutLogger).Name; + + private static readonly string BuiltInFullNameNullLogger = typeof(NullLogger).FullName; + private static readonly string BuiltInFullNameSystemOutLogger = typeof(SystemOutLogger).FullName; + + public static List CustomFactories { get; } = new(); + /// /// Initializes a new instance of the class. /// @@ -108,8 +117,15 @@ public static POILogger GetLogger(String cat) } else { try { //logger=assembly.CreateInstance(_loggerClassName) as POILogger; - Type loggerClass = Type.GetType(_loggerClassName); - logger = Activator.CreateInstance(loggerClass) as POILogger; + + // REMOVE-REFLECTION: I doubt if the following line would work, + // because _loggerClassName is Name of the type but Type.GetType requires FullName. + // It all ends up using the null logger. + + //Type loggerClass = Type.GetType(_loggerClassName); + // logger = Activator.CreateInstance(loggerClass) as POILogger; + + logger = CreateLoggerByTypeName(_loggerClassName); logger.Initialize(cat); } catch(Exception) { // Give up and use the null logger @@ -121,5 +137,22 @@ public static POILogger GetLogger(String cat) } return logger; } + + private static POILogger CreateLoggerByTypeName(string typeName) + { + if (typeName == BuiltInNameNullLogger || typeName == BuiltInFullNameNullLogger) + return _nullLogger; + + if (typeName == BuiltInNameSystemOutLogger || typeName == BuiltInFullNameSystemOutLogger) + return new SystemOutLogger(); + + foreach (var it in CustomFactories) + { + var logger = it.Create(typeName); + if (logger is not null) return logger; + } + + return _nullLogger; + } } }