public static void RegisterGlobalExceptionHandling( ) { var logger = LoggerProvider.CreateLogger(Constants.ApplicationName, Constants.LogFilename); logger.Debug("Registering global exception handlers..."); // this is the line you really want AppDomain.CurrentDomain.UnhandledException += (sender, args) => CurrentDomainOnUnhandledException(args, logger); // optional: hooking up some more handlers, remember that you need // to hook up additional handlers when logging from other dispatchers, // schedulers, or applications Application.Current.Dispatcher.UnhandledException += (sender, args) => DispatcherOnUnhandledException(args, logger); Application.Current.DispatcherUnhandledException += (sender, args) => CurrentOnDispatcherUnhandledException(args, logger); TaskScheduler.UnobservedTaskException += (sender, args) => TaskSchedulerOnUnobservedTaskException(args, logger); }
/// <summary> /// Connect a customer LN node to the merchant LN node /// </summary> /// <returns></returns> public async Task EnsureChannelsSetup() { TestLogs.LogInformation("Connecting channels"); BTCPayServer.Lightning.Tests.ConnectChannels.Logs = LoggerProvider.CreateLogger("Connect channels"); await BTCPayServer.Lightning.Tests.ConnectChannels.ConnectAll(ExplorerNode, GetLightningSenderClients(), GetLightningDestClients()).ConfigureAwait(false); TestLogs.LogInformation("Channels connected"); }
public static void Start(string[] args) { int interval = int.Parse(ConfigurationManager.AppSettings["interval"]) * 1000; var user = ConfigurationManager.AppSettings["user"]; var pass = ConfigurationManager.AppSettings["pass"]; var logWriters = new List <ILogBatchWriter>(); if (Environment.UserInteractive) { logWriters.Add(new ConsoleBatchWriter()); } var elasticsearchURL = ConfigurationManager.AppSettings["ElasticsearchUrl"]; var elasticsearchUser = ConfigurationManager.AppSettings["ElasticsearchUser"]; var elasticsearchPass = ConfigurationManager.AppSettings["ElasticsearchPass"]; logWriters.Add(new ElasticsearchBatchWriter(elasticsearchURL, "mailsender", elasticsearchUser, elasticsearchPass)); var loggerProvider = new LoggerProvider((cat, logLevel) => logLevel >= LogLevel.Information, false, new LoggerBatchingProcessor(logWriters)); var gmailSender = new GmailSender(loggerProvider.CreateLogger <GmailSender>(), user, pass); var config = new Config() { SubjectTemplateFileNameSubfix = ConfigurationManager.AppSettings["SubjectTemplateFileNameSubfix"], BodyTemplateFileNameSubfix = ConfigurationManager.AppSettings["BodyTemplateFileNameSubfix"], MailFolderPath = ConfigurationManager.AppSettings["MailFolderPath"], EmailKey = ConfigurationManager.AppSettings["EmailKey"], PurposeKey = ConfigurationManager.AppSettings["PurposeKey"], ProcessedFolderName = ConfigurationManager.AppSettings["ProcessedFolderName"], TemplateFolderPath = ConfigurationManager.AppSettings["TemplateFolderPath"], Interval = interval }; var processor = new EmailTemplateProcessor.EmailTemplateProcessor(gmailSender, loggerProvider.CreateLogger <EmailTemplateProcessor.EmailTemplateProcessor>(), config); if (processor.Start() == false) { return; } if (Environment.UserInteractive == true) { Console.Read(); } }
/// <summary> /// Creates a new Server instance. /// </summary> /// <param name="version">Version the server is running. <i>(independent of minecraft version)</i></param> public Server(Config config, string version, int serverId) { this.Config = config; ServerImplementationRegistry.RegisterServerImplementations(); this.LoggerProvider = new LoggerProvider(LogLevel.Debug); this.Logger = this.LoggerProvider.CreateLogger($"Server/{this.Id}"); // This stuff down here needs to be looked into Globals.PacketLogger = this.LoggerProvider.CreateLogger("Packets"); PacketDebug.Logger = this.LoggerProvider.CreateLogger("PacketDebug"); Registry.Logger = this.LoggerProvider.CreateLogger("Registry"); this.Port = config.Port; this.Version = version; this.Id = serverId; this.tcpListener = new TcpListener(IPAddress.Any, this.Port); this.clients = new ConcurrentHashSet <Client>(); this.cts = new CancellationTokenSource(); this.chatMessages = new ConcurrentQueue <QueueChat>(); this.placed = new ConcurrentQueue <PlayerBlockPlacement>(); Logger.LogDebug("Initializing command handler..."); this.Commands = new CommandHandler("/"); Logger.LogDebug("Registering commands..."); this.Commands.RegisterCommandClass <MainCommandModule>(); Logger.LogDebug("Registering custom argument parsers..."); this.Commands.AddArgumentParser(new LocationTypeParser()); this.Commands.AddArgumentParser(new PlayerTypeParser()); Logger.LogDebug("Registering command context type..."); this.Commands.RegisterContextType <ObsidianContext>(); Logger.LogDebug("Done registering commands."); this.Events = new MinecraftEventHandler(); this.PluginManager = new PluginManager(Events, this, LoggerProvider.CreateLogger("Plugin Manager")); this.Operators = new OperatorList(this); this.World = new World("world", this); this.Events.PlayerLeave += this.OnPlayerLeave; this.Events.PlayerJoin += this.OnPlayerJoin; this.Events.ServerTick += this.OnServerTick; }
public void CreateLoggerLogLevelTest() { // Arrange var categoryName = "DarkwingDuck"; // Act var logger = _classUnderTest.CreateLogger(categoryName); // Assert logger.IsEnabled(LogLevel.Trace).Should().BeFalse(); logger.IsEnabled(LogLevel.Debug).Should().BeFalse(); logger.IsEnabled(LogLevel.Information).Should().BeFalse(); logger.IsEnabled(LogLevel.Warning).Should().BeTrue(); logger.IsEnabled(LogLevel.Error).Should().BeTrue(); logger.IsEnabled(LogLevel.Critical).Should().BeTrue(); }
public UnbufferedLoggerProviderTests() { _messagesHandler = new MockHttpMessageHandler(); _provider = new LoggerProvider(new LoggerOptions() { Uri = "http://www.fakeadress.com", SourceName = "LoggerProviderTestSourceName", SourceCategory = "LoggerProviderTestSourceCategory", SourceHost = "LoggerProviderTestSourceHost", IsBuffered = false, HttpMessageHandler = _messagesHandler, }); _logger = _provider.CreateLogger("OverriddenCategory"); }
public UnbufferedLoggerProviderTests() { _messagesHandler = new MockHttpMessageHandler(); _provider = new LoggerProvider(new LoggerOptions() { Uri = "http://www.fakeadress.com", SourceName = "LoggerProviderTestSourceName", SourceCategory = "LoggerProviderTestSourceCategory", SourceHost = "LoggerProviderTestSourceHost", IsBuffered = false, HttpMessageHandler = _messagesHandler, MinLogLevel = LogLevel.Debug, MessageFormatterFunc = (message, ex, category, level, scopedProperties) => message }); _logger = _provider.CreateLogger("OverriddenCategory"); }
public void Initialize() { //Need to setup the logger first if (LoggingEnabled) { LoggerProvider = Options.LoggerProvider ?? new SystemLoggerProviderLog4Net(this); } _logger = LoggerProvider.CreateLogger(typeof(Settings)); //Setting up the rest of the system _logger.Info("Settings - Setup Started"); _logger.Debug(() => string.Format("Settings - Settings Extension Options - {0}", Options)); var sqlFactory = new SqlFactory(); var feedProvider = new NugetReleaseFeedProvider(); var persistencyProvider = new ReleasePersistencyProvider(sqlFactory); QueryProvider = new CacheReleaseQueryProvider(); ReleaseQueryService = new ReleaseQueryService(QueryProvider); if (UseOfflineData) { RefreshReleaseRepositoryService = new RefreshReleaseRepositoryOfflineService(NugetListingPath); } else { RefreshReleaseRepositoryService = new RefreshReleaseRepositoryService(feedProvider, persistencyProvider); } RefreshReleaseService = new RefreshReleaseService(this, RefreshReleaseRepositoryService, QueryProvider); ReleaseService = new ReleaseService(QueryProvider); _logger.Info("Settings - Setup Finished"); //Run system setup _logger.Info("Settings - Pre Initialize"); RefreshReleaseService.Execute(true); _logger.Info("Settings - Post Initialize"); }
public ISecretsRepository GetNewSecretRepository() { var logger = LoggerProvider.CreateLogger("Test"); if (RepositoryType == SecretsRepositoryType.BlobStorage) { return(new BlobStorageSecretsRepository(SecretsDirectory, ConnectionStringNames.Storage, TestSiteName, logger, Environment, AzureBlobStorageProvider)); } else if (RepositoryType == SecretsRepositoryType.BlobStorageSas) { return(new BlobStorageSasSecretsRepository(SecretsDirectory, BlobSasConnectionUri.ToString(), TestSiteName, logger, Environment, AzureBlobStorageProvider)); } else if (RepositoryType == SecretsRepositoryType.FileSystem) { return(new FileSystemSecretsRepository(SecretsDirectory, logger, Environment)); } else { return(new KeyVaultSecretsRepository(SecretsDirectory, KeyVaultUri, KeyVaultClientId, KeyVaultClientSecret, KeyVaultTenantId, logger, Environment)); } }
private void SetupLogger(long messagesPerRequest, long maxFlushInterval, long flushingAccuracy, long retryInterval = 10000) { _messagesHandler = new MockHttpMessageHandler(); _provider = new LoggerProvider(new LoggerOptions() { Uri = "http://www.fakeadress.com", SourceName = "LoggerProviderTestSourceName", SourceCategory = "LoggerProviderTestSourceCategory", SourceHost = "LoggerProviderTestSourceHost", MessagesPerRequest = messagesPerRequest, MaxFlushInterval = TimeSpan.FromMilliseconds(maxFlushInterval), FlushingAccuracy = TimeSpan.FromMilliseconds(flushingAccuracy), RetryInterval = TimeSpan.FromMilliseconds(retryInterval), IsBuffered = true, HttpMessageHandler = _messagesHandler, DebuggingLogger = new Microsoft.Extensions.Logging.Console.ConsoleLogger("debugging", (a, b) => true, true) }); _logger = _provider.CreateLogger("OverriddenCategory"); }
private async void Listen(IHttpListener listener) { var aggregatedHandler = _handlers.Aggregate(); while (_isActive) { try { _requestProvider.Handle ( await listener.GetClient().ConfigureAwait(false), aggregatedHandler, _requestProvider, LoggerProvider?.CreateLogger("ClientHandler") ); } catch (Exception e) { Logger?.LogWarning("Error while getting client - " + e); } } Logger?.LogInformation("Spirit has stopped."); }
public Program([NotNull] IServiceProvider serviceProvider, [NotNull] IApplicationEnvironment appEnv, [NotNull] ILibraryManager libraryManager, [NotNull] IRuntimeEnvironment runtimeEnv) { Check.NotNull(serviceProvider, nameof(serviceProvider)); Check.NotNull(appEnv, nameof(appEnv)); Check.NotNull(libraryManager, nameof(libraryManager)); Check.NotNull(runtimeEnv, nameof(runtimeEnv)); _runtimeEnv = runtimeEnv; _projectDir = appEnv.ApplicationBasePath; _rootNamespace = appEnv.ApplicationName; var loggerProvider = new LoggerProvider(name => new ConsoleCommandLogger(name, verbose: true)); var assemblyName = new AssemblyName(appEnv.ApplicationName); var assembly = Assembly.Load(assemblyName); _migrationTool = new MigrationTool(loggerProvider, assembly); _databaseTool = new DatabaseTool(serviceProvider, loggerProvider); _libraryManager = libraryManager; _logger = loggerProvider.CreateLogger(typeof(Program).FullName); }
public TestProviderController(LoggerProvider logger) { _logger = logger.CreateLogger("Information"); _context = new Db(); }
/// <summary> /// Creates a new instance of <see cref="Server"/>. /// </summary> /// <param name="version">Version the server is running. <i>(unrelated to minecraft version)</i></param> public Server(Config config, string version, int serverId) { this.Config = config; this.Port = config.Port; this.Version = version; this.Id = serverId; this.ServerFolderPath = Path.GetFullPath($"Server-{this.Id}"); this.tcpListener = new TcpListener(IPAddress.Any, this.Port); this.clients = new ConcurrentHashSet <Client>(); this.cts = new CancellationTokenSource(); this.chatMessages = new ConcurrentQueue <QueueChat>(); this.placed = new ConcurrentQueue <PlayerBlockPlacement>(); this.Events = new MinecraftEventHandler(); this.Operators = new OperatorList(this); this.LoggerProvider = new LoggerProvider(Globals.Config.LogLevel); this.Logger = this.LoggerProvider.CreateLogger($"Server/{this.Id}"); // This stuff down here needs to be looked into Globals.PacketLogger = this.LoggerProvider.CreateLogger("Packets"); PacketDebug.Logger = this.LoggerProvider.CreateLogger("PacketDebug"); //Registry.Logger = this.LoggerProvider.CreateLogger("Registry"); Logger.LogDebug("Initializing command handler..."); this.Commands = new CommandHandler("/"); this.PluginManager = new PluginManager(Events, this, LoggerProvider.CreateLogger("Plugin Manager"), this.Commands); this.Commands.LinkPluginManager(this.PluginManager); Logger.LogDebug("Registering commands..."); this.Commands.RegisterCommandClass(null, new MainCommandModule()); Logger.LogDebug("Registering custom argument parsers..."); this.Commands.AddArgumentParser(new LocationTypeParser()); this.Commands.AddArgumentParser(new PlayerTypeParser()); Logger.LogDebug("Registering command context type..."); Logger.LogDebug("Done registering commands."); this.Events.PlayerLeave += this.OnPlayerLeave; this.Events.PlayerJoin += this.OnPlayerJoin; this.Events.PlayerAttackEntity += this.PlayerAttack; if (this.Config.UDPBroadcast) { this.udpClient = new UdpClient("224.0.2.60", 4445); _ = Task.Run(async() => { while (!this.cts.IsCancellationRequested) { await Task.Delay(1500); // Official clients do this too. var str = Encoding.UTF8.GetBytes($"[MOTD]{config.Motd.Replace('[', '(').Replace(']', ')')}[/MOTD][AD]{config.Port}[/AD]"); await this.udpClient.SendAsync(str, str.Length); } }); } }
public async Task StartAsync() { if (!Directory.Exists(_Directory)) { Directory.CreateDirectory(_Directory); } string chain = NBXplorerDefaultSettings.GetFolderName(ChainName.Regtest); string chainDirectory = Path.Combine(_Directory, chain); if (!Directory.Exists(chainDirectory)) { Directory.CreateDirectory(chainDirectory); } StringBuilder config = new StringBuilder(); config.AppendLine($"{chain.ToLowerInvariant()}=1"); if (InContainer) { config.AppendLine($"bind=0.0.0.0"); } config.AppendLine($"port={Port}"); config.AppendLine($"chains={string.Join(',', Chains)}"); if (Chains.Contains("BTC", StringComparer.OrdinalIgnoreCase)) { config.AppendLine($"btc.explorer.url={NBXplorerUri.AbsoluteUri}"); config.AppendLine($"btc.explorer.cookiefile=0"); } if (UseLightning) { config.AppendLine($"btc.lightning={IntegratedLightning}"); var localLndBackupFile = Path.Combine(_Directory, "walletunlock.json"); File.Copy(TestUtils.GetTestDataFullPath("LndSeedBackup/walletunlock.json"), localLndBackupFile, true); config.AppendLine($"btc.external.lndseedbackup={localLndBackupFile}"); } if (Chains.Contains("LTC", StringComparer.OrdinalIgnoreCase)) { config.AppendLine($"ltc.explorer.url={LTCNBXplorerUri.AbsoluteUri}"); config.AppendLine($"ltc.explorer.cookiefile=0"); } if (Chains.Contains("LBTC", StringComparer.OrdinalIgnoreCase)) { config.AppendLine($"lbtc.explorer.url={LBTCNBXplorerUri.AbsoluteUri}"); config.AppendLine($"lbtc.explorer.cookiefile=0"); } if (CheatMode) { config.AppendLine("cheatmode=1"); } config.AppendLine($"torrcfile={TestUtils.GetTestDataFullPath("Tor/torrc")}"); config.AppendLine($"socksendpoint={SocksEndpoint}"); config.AppendLine($"debuglog=debug.log"); config.AppendLine($"nocsp={NoCSP.ToString().ToLowerInvariant()}"); if (!string.IsNullOrEmpty(SSHPassword) && string.IsNullOrEmpty(SSHKeyFile)) { config.AppendLine($"sshpassword={SSHPassword}"); } if (!string.IsNullOrEmpty(SSHKeyFile)) { config.AppendLine($"sshkeyfile={SSHKeyFile}"); } if (!string.IsNullOrEmpty(SSHConnection)) { config.AppendLine($"sshconnection={SSHConnection}"); } if (TestDatabase == TestDatabases.MySQL && !String.IsNullOrEmpty(MySQL)) { config.AppendLine($"mysql=" + MySQL); } else if (!String.IsNullOrEmpty(Postgres)) { config.AppendLine($"postgres=" + Postgres); } var confPath = Path.Combine(chainDirectory, "settings.config"); await File.WriteAllTextAsync(confPath, config.ToString()); ServerUri = new Uri("http://" + HostName + ":" + Port + "/"); HttpClient = new HttpClient(); HttpClient.BaseAddress = ServerUri; Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development"); var conf = new DefaultConfiguration() { Logger = LoggerProvider.CreateLogger("Console") }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath, "--disable-registration", DisableRegistration ? "true" : "false" }); _Host = new WebHostBuilder() .UseConfiguration(conf) .UseContentRoot(FindBTCPayServerDirectory()) .UseWebRoot(Path.Combine(FindBTCPayServerDirectory(), "wwwroot")) .ConfigureServices(s => { s.AddLogging(l => { l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical); l.SetMinimumLevel(LogLevel.Information) .AddFilter("Microsoft", LogLevel.Error) .AddFilter("Hangfire", LogLevel.Error) .AddFilter("Fido2NetLib.DistributedCacheMetadataService", LogLevel.Error) .AddProvider(LoggerProvider); }); }) .ConfigureServices(services => { services.TryAddSingleton <IFeeProviderFactory>(new BTCPayServer.Services.Fees.FixedFeeProvider(new FeeRate(100L, 1))); }) .UseKestrel() .UseStartup <Startup>() .Build(); await _Host.StartWithTasksAsync(); var urls = _Host.ServerFeatures.Get <IServerAddressesFeature>().Addresses; foreach (var url in urls) { TestLogs.LogInformation("Listening on " + url); } TestLogs.LogInformation("Server URI " + ServerUri); InvoiceRepository = (InvoiceRepository)_Host.Services.GetService(typeof(InvoiceRepository)); StoreRepository = (StoreRepository)_Host.Services.GetService(typeof(StoreRepository)); Networks = (BTCPayNetworkProvider)_Host.Services.GetService(typeof(BTCPayNetworkProvider)); if (MockRates) { var rateProvider = (RateProviderFactory)_Host.Services.GetService(typeof(RateProviderFactory)); rateProvider.Providers.Clear(); coinAverageMock = new MockRateProvider(); coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_USD"), new BidAsk(5000m))); coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_EUR"), new BidAsk(4000m))); coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_CAD"), new BidAsk(4500m))); coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_LTC"), new BidAsk(162m))); coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("LTC_USD"), new BidAsk(500m))); rateProvider.Providers.Add("coingecko", coinAverageMock); var bitflyerMock = new MockRateProvider(); bitflyerMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_JPY"), new BidAsk(700000m))); rateProvider.Providers.Add("bitflyer", bitflyerMock); var ndax = new MockRateProvider(); ndax.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_CAD"), new BidAsk(6000m))); rateProvider.Providers.Add("ndax", ndax); var bittrex = new MockRateProvider(); bittrex.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("DOGE_BTC"), new BidAsk(0.004m))); rateProvider.Providers.Add("bittrex", bittrex); var bitfinex = new MockRateProvider(); bitfinex.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("UST_BTC"), new BidAsk(0.000136m))); rateProvider.Providers.Add("bitfinex", bitfinex); var bitpay = new MockRateProvider(); bitpay.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("ETB_BTC"), new BidAsk(0.1m))); rateProvider.Providers.Add("bitpay", bitpay); var kraken = new MockRateProvider(); kraken.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("ETH_BTC"), new BidAsk(0.1m))); rateProvider.Providers.Add("kraken", kraken); } TestLogs.LogInformation("Waiting site is operational..."); await WaitSiteIsOperational(); TestLogs.LogInformation("Site is now operational"); }
private void LoadSettings() { var configProcessor = new ConfigProcessor(new ConfigProvider(LoggerProvider.CreateLogger(typeof(ConfigProvider)))); configProcessor.Process(this); }