web-app-template/backend/app/app.Configuration/HostExtensions.cs

116 lines
5.6 KiB
C#
Raw Normal View History

2022-02-20 13:43:25 +01:00
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace app.Configuration {
public static class HostExtensions {
// copied from https://github.com/dotnet/extensions/blob/release/3.1/src/Hosting/Hosting/src/Host.cs,
// modified to use customer environment
public static IHostBuilder CreateBuilder(string[] args) {
var builder = new HostBuilder();
builder.UseContentRoot(Directory.GetCurrentDirectory()); // UseWindowsService overrides content root to AppContext.BaseDirectory
builder.ConfigureHostConfiguration(config => {
config.AddEnvironmentVariables(prefix: "DOTNET_");
config.AddEnvironmentVariables(prefix: "LOGINCOUNTER_");
if (args != null) {
config.AddCommandLine(args);
}
});
builder.ConfigureAppConfiguration((hostingContext, config) => {
var env = hostingContext.HostingEnvironment;
var customerEnv = hostingContext.Configuration.GetValue<string>(Constants.CustomerEnvironmentVariable);
//var customerEnv = Environment.GetEnvironmentVariable(Constants.CustomerEnvironmentVariable);
if (!string.IsNullOrEmpty(customerEnv))
config.SetBasePath(Path.Combine(hostingContext.HostingEnvironment.ContentRootPath, Constants.CustomersDirectoryName, customerEnv));
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);
var computerName = Environment.GetEnvironmentVariable(Constants.ComputerNameEnvironmentVariable);
if (!string.IsNullOrEmpty(computerName))
config.AddJsonFile($"appsettings.{computerName}.json", optional: true, reloadOnChange: true);
if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName)) {
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null) {
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
config.AddEnvironmentVariables("IOTHUB_");
if (args != null) {
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) => {
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
// IMPORTANT: This needs to be added *before* configuration is loaded, this lets
// the defaults be overridden by the configuration.
if (isWindows) {
// Default the EventLogLoggerProvider to warning or above
logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning);
}
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
if (isWindows) {
// Add the EventLogLoggerProvider on windows machines
logging.AddEventLog();
}
})
.UseDefaultServiceProvider((context, options) => {
var isDevelopment = context.HostingEnvironment.IsDevelopment();
options.ValidateScopes = isDevelopment;
options.ValidateOnBuild = isDevelopment;
});
return builder;
}
public static void LogHostingEnvironment<T>(this IHost host) {
var loggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
var configuration = host.Services.GetRequiredService<IConfiguration>();
var hostEnvironment = host.Services.GetRequiredService<IHostEnvironment>();
var logger = loggerFactory.CreateLogger<T>();
logger.LogInformation("Running Host...");
logger.LogInformation($"EnvironmentName:{hostEnvironment.EnvironmentName}");
logger.LogInformation($"ContentRootPath:{hostEnvironment.ContentRootPath}");
logger.LogInformation($"CurrentDirectory:{Environment.CurrentDirectory}");
logger.LogInformation($"ApplicationName:{hostEnvironment.ApplicationName}");
logger.LogInformation($"Customer:{configuration.GetCustomer()}");
logger.LogInformation($"ComputerName:{configuration.GetComputerName()}");
}
public static void LogStartError(Exception ex) {
var logDir = Path.Combine(AppContext.BaseDirectory, "logs");
if (!Directory.Exists(logDir))
Directory.CreateDirectory(logDir);
var logFile = Path.Combine(logDir, "start_error.txt");
File.AppendAllText(logFile, DateTime.Now.ToString() + ": " + ex.ToString() + Environment.NewLine);
}
public static void ChangeCurrentDirToProjectDir() {
var currentDir = Directory.GetCurrentDirectory();
var ix = currentDir.IndexOf("\\bin"); // goto project dir, if we are running from VS
if (ix >= 0) {
var newDir = currentDir.Substring(0, ix);
Directory.SetCurrentDirectory(newDir);
}
}
}
}