private static void TryLoadManagedAssembly() { StartupLogger.Log("Managed Loader TryLoadManagedAssembly()"); try { var assembly = Assembly.Load("OpenTelemetry.AutoInstrumentation"); if (assembly == null) { throw new FileNotFoundException("The assembly OpenTelemetry.AutoInstrumentation could not be loaded"); } var type = assembly.GetType("OpenTelemetry.AutoInstrumentation.Instrumentation", throwOnError: false); if (type == null) { throw new TypeLoadException("The type OpenTelemetry.AutoInstrumentation.Instrumentation could not be loaded"); } var method = type.GetRuntimeMethod("Initialize", new Type[0]); if (method == null) { throw new MissingMethodException("The method OpenTelemetry.AutoInstrumentation.Instrumentation.Initialize could not be loaded"); } method.Invoke(obj: null, parameters: null); } catch (Exception ex) { StartupLogger.Log(ex, $"Error when loading managed assemblies. {ex.Message}"); throw; } }
/// <summary> /// ctor /// </summary> /// <param name="configuration"></param> public Startup(IConfiguration configuration, ILoggerFactory loggerFactory, IHostingEnvironment env) { Configuration = configuration; HostingEnvironment = env; LoggerFactory = loggerFactory; StartupLogger = loggerFactory.CreateLogger("Startup"); StartupLogger.LogInformation("Startup instantiated"); }
private static string ReadEnvironmentVariable(string key) { try { return(Environment.GetEnvironmentVariable(key)); } catch (Exception ex) { StartupLogger.Log(ex, "Error while loading environment variable " + key); } return(null); }
/// <summary> /// Initializes static members of the <see cref="Startup"/> class. /// This method also attempts to load the OpenTelemetry.AutoInstrumentation .NET assembly. /// </summary> static Startup() { ManagedProfilerDirectory = ResolveManagedProfilerDirectory(); try { AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve_ManagedProfilerDependencies; } catch (Exception ex) { StartupLogger.Log(ex, "Unable to register a callback to the CurrentDomain.AssemblyResolve event."); } TryLoadManagedAssembly(); }
/// <summary> /// Primary entry point for the program /// </summary> /// <param name="args"></param> static void Main(string[] args) { const string ComponentName = @"Front End Setup"; var logger = new StartupLogger("Protocol Gateway Setup"); Guid traceId = Guid.NewGuid(); try { logger.Informational(traceId, ComponentName, "Launched."); PerformanceCounters.RegisterCountersIfRequired(); logger.Informational(traceId, ComponentName, "Completed without exceptions."); } catch (Exception e) { logger.Critical(traceId, ComponentName, "Could not prepare the environment due to an error.", null, e); throw; } }
public static IApplicationBuilder UseOSharp(this IApplicationBuilder app) #endif { #if NET6_0_OR_GREATER IServiceProvider provider = app.Services; #else IServiceProvider provider = app.ApplicationServices; #endif ILogger logger = provider.GetLogger("ApplicationBuilderExtensions"); logger.LogInformation(0, "OSharp框架初始化开始"); // 输出注入服务的日志 StartupLogger startupLogger = provider.GetService <StartupLogger>(); startupLogger?.Output(provider); Stopwatch watch = Stopwatch.StartNew(); OsharpPack[] packs = provider.GetAllPacks(); logger.LogInformation($"共有 {packs.Length} 个Pack模块需要初始化"); foreach (OsharpPack pack in packs) { Type packType = pack.GetType(); string packName = packType.GetDescription(); logger.LogInformation($"正在初始化模块 “{packName} ({packType.Name})”"); if (pack is AspOsharpPack aspPack) { aspPack.UsePack(app); } else { pack.UsePack(provider); } logger.LogInformation($"模块 “{packName} ({packType.Name})” 初始化完成\n"); } watch.Stop(); logger.LogInformation(0, $"OSharp框架初始化完成,耗时:{watch.Elapsed}\r\n"); return(app); }
private static Assembly AssemblyResolve_ManagedProfilerDependencies(object sender, ResolveEventArgs args) { var assemblyName = new AssemblyName(args.Name); // On .NET Framework, having a non-US locale can cause mscorlib // to enter the AssemblyResolve event when searching for resources // in its satellite assemblies. This seems to have been fixed in // .NET Core in the 2.0 servicing branch, so we should not see this // occur, but guard against it anyways. If we do see it, exit early // so we don't cause infinite recursion. if (string.Equals(assemblyName.Name, "System.Private.CoreLib.resources", StringComparison.OrdinalIgnoreCase) || string.Equals(assemblyName.Name, "System.Net.Http", StringComparison.OrdinalIgnoreCase)) { return(null); } var path = Path.Combine(ManagedProfilerDirectory, $"{assemblyName.Name}.dll"); // Only load the main profiler into the default Assembly Load Context. // If OpenTelemetry.AutoInstrumentation or other libraries are provided by the NuGet package their loads are handled in the following two ways. // 1) The AssemblyVersion is greater than or equal to the version used by OpenTelemetry.AutoInstrumentation, the assembly // will load successfully and will not invoke this resolve event. // 2) The AssemblyVersion is lower than the version used by OpenTelemetry.AutoInstrumentation, the assembly will fail to load // and invoke this resolve event. It must be loaded in a separate AssemblyLoadContext since the application will only // load the originally referenced version if (assemblyName.Name.StartsWith("OpenTelemetry.AutoInstrumentation", StringComparison.OrdinalIgnoreCase) && File.Exists(path)) { StartupLogger.Debug("Loading {0} with Assembly.LoadFrom", path); return(Assembly.LoadFrom(path)); } else if (File.Exists(path)) { StartupLogger.Debug("Loading {0} with DependencyLoadContext.LoadFromAssemblyPath", path); return(DependencyLoadContext.LoadFromAssemblyPath(path)); // Load unresolved framework and third-party dependencies into a custom Assembly Load Context } return(null); }
private static Assembly AssemblyResolve_ManagedProfilerDependencies(object sender, ResolveEventArgs args) { var assemblyName = new AssemblyName(args.Name).Name; // On .NET Framework, having a non-US locale can cause mscorlib // to enter the AssemblyResolve event when searching for resources // in its satellite assemblies. Exit early so we don't cause // infinite recursion. if (string.Equals(assemblyName, "mscorlib.resources", StringComparison.OrdinalIgnoreCase) || string.Equals(assemblyName, "System.Net.Http", StringComparison.OrdinalIgnoreCase)) { return(null); } var path = Path.Combine(ManagedProfilerDirectory, $"{assemblyName}.dll"); if (File.Exists(path)) { StartupLogger.Debug("Loading {0}", path); return(Assembly.LoadFrom(path)); } return(null); }