public HistoryMailFixture() { var loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(LogLevel.Debug); var sendGridSettings = new SendGridMailerSettings { ApiKey = "abc", FromDisplayName = "xunit", FromEmailAddress = "*****@*****.**" }; var logger = loggerFactory.CreateLogger <SendGridMailer>(); MailerFactoryForHistoryWithSerializableAttachments.Register(() => new SendGridMailerFake( new OptionsWrapper <SendGridMailerSettings>(sendGridSettings), logger, StoreWithSerializableAttachments)); MailerFactoryForHistoryWithoutSerializableAttachments.Register(() => new SendGridMailerFake( new OptionsWrapper <SendGridMailerSettings>(sendGridSettings), logger, StoreWithoutSerializableAttachments)); }
private static void SetUpServiceProvider(IPlatformHelper platformHelper) { if (platformHelper == null) { throw new ArgumentNullException(nameof(platformHelper)); } var logFileLocation = Path.Combine(platformHelper.LogFolderPath, string.Format("_EFCoreCPTest_{0}.log", platformHelper.PlatformName)); var loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(LogLevel.Trace); loggerFactory.AddFile(logFileLocation, append: false); var logger = loggerFactory.CreateLogger("EFCoreCPTest"); logger.LogTrace("AppCommon.SetUpServiceProvider() called and default logger created"); logger.LogTrace("Creating the ServiceCollection instance"); var serviceCollection = new ServiceCollection() .AddSingleton <ILoggerFactory>(loggerFactory) .AddSingleton(logger) .AddSingleton(platformHelper) .AddLogging(); logger.LogTrace("Building the ServiceProvider instance"); ServiceProvider = serviceCollection.BuildServiceProvider(); logger.LogTrace("AppCommon.SetUpServiceProvider() returning"); }
public HistoryMailFixture() { var loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(LogLevel.Debug); // ReSharper disable once UnusedVariable var mkSettings = SetupMailerOptions(out bool isMailServerAlive).Value; Func <SmtpClient> getClientFunc = () => { var c = Substitute.For <SmtpClient>(); c .SendAsync(Arg.Any <MimeMessage>(), Arg.Any <CancellationToken>()) .Returns(Task.CompletedTask); return(c); }; var logger = loggerFactory.CreateLogger <MkSmtpMailer>(); MailerFactoryForHistoryWithSerializableAttachments.AddMkSmtpMailer(getClientFunc, mkSettings, logger, StoreWithSerializableAttachments); MailerFactoryForHistoryWithoutSerializableAttachments.AddMkSmtpMailer(getClientFunc, mkSettings, logger, StoreWithoutSerializableAttachments); }
public void ConfigureServices(IServiceCollection services) { var loggerFactory = new LoggerFactory { MinimumLevel = LogLevel.Debug }; loggerFactory.AddConsole(); loggerFactory.AddDebug(); services.AddMvc( config => { config.Filters.Add(new GlobalFilter(loggerFactory)); config.Filters.Add(new GlobalLoggingExceptionFilter(loggerFactory)); }); services.AddScoped <ConsoleLogActionOneFilter>(); services.AddScoped <ConsoleLogActionTwoFilter>(); services.AddScoped <ClassConsoleLogActionBaseFilter>(); services.AddScoped <ClassConsoleLogActionOneFilter>(); services.AddScoped <CustomOneLoggingExceptionFilter>(); services.AddScoped <CustomTwoLoggingExceptionFilter>(); services.AddScoped <CustomOneResourceFilter>(); }
public void InitContext() { var builder = new DbContextOptionsBuilder <SQLiteLogQuakeContext>() .UseInMemoryDatabase(databaseName: "Add_writes_to_database"); _context = new SQLiteLogQuakeContext(builder.Options); IMemoryCache cache = new MemoryCache(new MemoryCacheOptions()); LoggerFactory loggerFactoryServices = new LoggerFactory(); loggerFactoryServices.AddConsole(LogLevel.None); loggerFactoryServices.AddDebug(LogLevel.None); _loggerLogQuakeServices = new Logger <LogQuakeService>(loggerFactoryServices); _unitOfWork = new UnitOfWork(_context, cache, _configuration); _logQuakeService = new LogQuakeService(_unitOfWork, cache, _loggerLogQuakeServices, _configuration); LoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(LogLevel.None); loggerFactory.AddDebug(LogLevel.None); _loggerGamesController = new Logger <GamesController>(loggerFactory); _configuration = new ConfigurationBuilder() .SetBasePath(System.AppContext.BaseDirectory) .AddJsonFile("appsettings.json") .Build(); }
/// <summary> /// One time call to create Private Client /// /// </summary> /// <param name="accessHelper"></param> public void CreatePrivateClient(string serverURL = null) { if (_privateClient == null) { try { ILoggerFactory l = null; //Log.Info("Creating PrivateClient on " + serverURL); LoggerFactory factory = new LoggerFactory(); factory.AddDebug(Microsoft.Extensions.Logging.LogLevel.Trace); PrivateServerSettings settings = new PrivateServerSettings { ServerUrl = new Uri(serverURL ?? TestConfig.GetValueFromConfig("PrivateServer")), LoggerFactory = factory }; _privateClient = PrivateClient.CreateClient(settings); } catch (Exception e) { //Log.Error(e); } } else { //Log.Info("PrivateClient already created"); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddTransient <IRepository, RepositoryIMPL>(); services.AddTransient <IMeasurementManager, MeasurementManagerIMPL>(); // Add the service as a singleton services.AddSingleton <RedisService>(); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(); services.AddSingleton <ILoggerFactory>(loggerFactory); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "QuantityMeasurement", Version = "v1" }); }); }
public static LoggerFactory GetFactory(LogLevel level, string fileName = M_LogFileName) { if (string.IsNullOrEmpty(fileName)) { fileName = M_LogFileName; } if (fileName == M_LogFileName && LogConfig.Config.SplitLevel) { fileName += $".{level.ToString().ToLower()}"; } if (!m_factorys.ContainsKey(fileName)) { lock (m_factorys) { if (!m_factorys.ContainsKey(fileName)) { var logPath = GetLogPath(); var pathFormat = System.IO.Path.Combine(logPath, LogConfig.Config.FileFormat.Replace("@FileName", fileName)); var factory = new LoggerFactory(); factory.AddDebug(); factory.AddConsole(LogConfig.Config.LogLevel, true); factory.AddFile(pathFormat, LogConfig.Config.LogLevel); m_factorys.Add(fileName, factory); } } } return(m_factorys[fileName]); }
public void WithTheLoggerExtension_ShouldCreateLoggingItem() { var httpClient = _host.CreateClient(); var loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(); loggerFactory.AddDebug(); var settings = new RemoteLoggerSetting(); ConfigurationBuilder config = new ConfigurationBuilder(); config.AddJsonFile("appSettings.json"); config.Build().GetSection("Logging").Bind(settings); settings.RemoteUrl = httpClient.BaseAddress.ToString(); loggerFactory.AddRemoteLogger(settings, httpClient); var logger = loggerFactory.CreateLogger("Test"); logger.Should().NotBeNull(); logger.LogInformation("This is a test"); var logFile = "c:\\temp\\app.log"; File.Exists(logFile).Should().BeTrue(); }
public DatabaseRepositoryTest() { ILoggerFactory factory = new LoggerFactory(); factory.AddDebug(); _log = factory.CreateLogger <DatabaseRepository>(); }
// use length of file to pick a random spot to read a cookie from public string randomCookie() { try { ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(); loggerFactory.AddDebug(); ILogger logger = loggerFactory.CreateLogger <Program>(); FileInfo fi = new FileInfo(cookieFile); int size = (int)fi.Length; Random startFrom = new Random(); int skip = startFrom.Next(0, size); logger.LogInformation("File: " + cookieFile + "\nSize: " + size.ToString() + "\nSkip to: " + skip.ToString()); string cookieText = readCookieFrom(cookieFile, skip); logger.LogInformation(cookieText); return(cookieText); } catch (Exception e) { // just catch and fail transparently as cookie text return(e.Message); } }
public static void Main(string[] args) { var configuration = Startup.RegisterConfiguration(); ILoggerFactory loggerFactory = new LoggerFactory(); var logger = loggerFactory.CreateLogger("Ef Migrations"); loggerFactory.AddConsole(configuration.GetSection("Logging")); loggerFactory.AddDebug(); IServiceCollection services = new ServiceCollection(); services.AddSingleton(loggerFactory); var conn = configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<VotingContext>(options => options.UseSqlServer(conn)); IServiceProvider provider = services.BuildServiceProvider(); logger.LogDebug($"Initialized Context with {conn}"); using (var serviceScope = provider.GetService<IServiceScopeFactory>().CreateScope()) { var context = serviceScope.ServiceProvider.GetService<VotingContext>(); logger.LogDebug($"Initializing Database for VotingContext..."); context.Database.EnsureCreated(); logger.LogDebug($"Database created"); logger.LogDebug($"Initializing data seeding..."); context.EnsureSeedData(); logger.LogDebug($"Data seeded for {conn}"); } }
private static ILogger ConfigureLogger() { var loggingSection = ConfigurationService.Root.GetSection("logging"); var loggingSettings = ConfigurationService.Root.GetSection("logging")?.Get <LoggingSettings>(); var resultLogger = default(ILogger); if (loggingSettings != null && loggingSettings.IsEnabled) { ILoggerFactory loggerFactory = new LoggerFactory(); if (loggingSettings.IsConsoleLoggingEnabled) { loggerFactory.AddConsole(loggingSection); } if (loggingSettings.IsDebugLoggingEnabled) { loggerFactory.AddDebug(); } if (loggingSettings.IsFileLoggingEnabled) { var fileLoggingSection = ConfigurationService.Root.GetSection("logging:fileLogging"); loggerFactory.AddFile(fileLoggingSection); } resultLogger = loggerFactory.CreateLogger("Bellatrix"); } return(resultLogger); }
static ApiController() { #if NET461 ApiController.log = LogManager.GetLogger(typeof(ApiController)); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; if (ApiConfig.IsDebug()) { if (File.Exists("log4net.xml")) { XmlConfigurator.Configure(new FileInfo("log4net.xml")); return; } BasicConfigurator.Configure(); } #elif NETSTANDARD1_6 ILoggerFactory loggerFactory = new LoggerFactory(); if (ApiConfig.IsDebug()) { loggerFactory.AddDebug(); } ApiController.log = loggerFactory.CreateLogger <ApiController>(); #endif }
public static void Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", true, true) .AddUserSecrets <Program>(); var config = builder.Build(); var airbrakeOptions = new AirbrakeOptions(); config.GetSection("Airbrake").Bind(airbrakeOptions); var loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(config.GetSection("Logging")); loggerFactory.AddDebug(); var client = new AirbrakeClient(loggerFactory, airbrakeOptions); Console.WriteLine("Sending the exception now!"); try { Program.RaiseException(); } catch (Exception exc) { exc.SendToAirbrakeAsync(client).Wait(); Console.WriteLine("Exception has been send!"); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <UserDBContext>( option => option.UseSqlServer( this._config.GetConnectionString("UserDbConnection"), sqlServerOptions => sqlServerOptions.MigrationsAssembly("Repository"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddTransient <IBookManager, BookManager>(); services.AddTransient <IBookRepo, BookRepoIMPL>(); services.AddTransient <ICartRepo, CartRepoIMPL>(); services.AddTransient <ICartManager, CartManager>(); services.AddTransient <ICustomerDetailsRepo, CustomerDetailsRepoIMPL>(); services.AddTransient <ICustomerDetailsManager, CustomerDetailsManager>(); services.AddTransient <ILoginManager, LoginManager>(); services.AddTransient <ILoginRepo, LoginRepoIMPL>(); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(); services.AddSingleton <ILoggerFactory>(loggerFactory); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); }
private void MockGenerator() { var optionsMock = new Mock <IOptions <DapperDatabaseOptions> >(); var options = new DapperDatabaseOptions { DefaultConnectionName = "default", ConnectionStrings = new Dictionary <string, string> { { "default", helper.ConnectionString } } }; var builder = new DapperDataFeatureBuilder(options); builder.Conventions(convention => { convention .AutoGenerateKey <TimeTest>(x => x.Id) .Ignore <TimeTest>(x => x.Time) .Types(s => s == typeof(TimeTest)) .IsEntity(); }); builder.Build(); optionsMock.Setup(o => o.Value).Returns(options); var loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(LogLevel.Trace); _testContext = new DapperContext(new DapperRuntime(optionsMock.Object, new IDapperMetadataProvider[] { new DapperMetadataProviderInstance(), }) , loggerFactory); _dapper = new DapperRepository <DapperTestEntity>(_testContext); _dapper1 = new DapperRepository <TimeTest>(_testContext); }
/// <summary> /// Create a new test-suite. /// </summary> /// <param name="testOutput"> /// Output for the current test. /// </param> protected TestBase(ITestOutputHelper testOutput) { if (testOutput == null) { throw new ArgumentNullException(nameof(testOutput)); } // We *must* have a synchronisation context for the test, or we'll see random deadlocks. SynchronizationContext.SetSynchronizationContext( new SynchronizationContext() ); TestOutput = testOutput; // Redirect component logging to Serilog. LoggerFactory = new LoggerFactory(); Disposal.Add(LoggerFactory); LoggerFactory.AddDebug(LogLevel); LoggerFactory.AddTestOutput(TestOutput, LogLevel); // Ugly hack to get access to the current test. CurrentTest = (ITest) TestOutput.GetType() .GetField("test", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(TestOutput); Assert.True(CurrentTest != null, "Cannot retrieve current test from ITestOutputHelper."); Log = LoggerFactory.CreateLogger("CurrentTest"); Disposal.Add( Log.BeginScope("TestDisplayName='{TestName}'", CurrentTest.DisplayName) ); }
public void Setup() { var factory = new LoggerFactory(); factory.AddDebug(); LogManager.ConfigureLoggerFactory(factory); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(); loggerFactory.AddDebug(); services.AddOptions(); services.Configure <Appsettings>(appsettings => { appsettings.ApplicationName = Configuration.GetSection("AppSettings:ApplicationName").Value; }); services.AddMvc(config => { config.Filters.Add(new GlobalFilter(loggerFactory)); config.Filters.Add(new GlobalLoggingExceptionFilter(loggerFactory)); }); services.AddScoped <ConsoleLogActionOneFilter>(); services.AddScoped <ConsoleLogActionTwoFilter>(); services.AddScoped <ClassConsoleLogActionBaseFilter>(); services.AddScoped <ClassConsoleLogActionOneFilter>(); services.AddScoped <CustomOneLoggingExceptionFilter>(); services.AddScoped <CustomTwoLoggingExceptionFilter>(); services.AddScoped <CustomOneResourceFilter>(); }
static void Main() { var hardwareOptions = new HardwareOptions() { BoardModel = BoardModel.Sc20260D }; var MainBoard = new Mainboard(hardwareOptions).Connect(); MainBoard.Network.Enabled(); var loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(LogLevel.Trace); IServer server = new SocketServer(loggerFactory, options => { options.Pipeline(app => { app.UseMemoryInfo(); app.UseHttpResponse(); }); }); server.Start(); }
private static ApplicationBuilder GetApplicationBuilder() { var services = new ServiceCollection(); services.AddTransient <MvcMarkerService>(); services.AddTransient <MiddlewareFilterConfigurationProvider>(); services.AddTransient <MiddlewareFilterBuilder>(); services.AddTransient <IActionDescriptorCollectionProvider, ActionDescriptorCollectionProvider>(); services.AddTransient <IActionInvokerFactory, ActionInvokerFactory>(); services.AddTransient <IActionSelector, ActionSelector>(); services.AddTransient <IEnumerable <IActionConstraintProvider> >(provider => new IActionConstraintProvider[] { new DefaultActionConstraintProvider() }); services.AddSingleton(new Mock <DiagnosticSource>().Object); services.AddTransient <MvcRouteHandler>(); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(); loggerFactory.AddDebug(); services.AddSingleton(loggerFactory); services.AddTransient <ActionConstraintCache>(); services.AddRouting(); var serviceProvider = services.BuildServiceProvider(); return(new ApplicationBuilder(serviceProvider)); }
public static ApplicationDbContext CreateDbContext() { DbContextOptionsBuilder <ApplicationDbContext> contextOptionsBuilder = // declaring the options we are going to use for the context we will be using for tests new DbContextOptionsBuilder <ApplicationDbContext>(); LoggerFactory loggerFactory = new LoggerFactory(); // this will allow us to add loggers so we can actually inspect what code and queries EntityFramework produces. loggerFactory .AddDebug() // this logger will log to the Debug output .AddConsole(); // this logger will output to the console SqliteConnectionStringBuilder connectionStringBuilder = new SqliteConnectionStringBuilder { Mode = SqliteOpenMode.Memory }; // this is more syntax friendly approach to defining and InMemory connection string for our database, the alternative is to write it out as a string. SqliteConnection connection = new SqliteConnection(connectionStringBuilder.ConnectionString); // create a connection to the InMemory database. connection.Open(); // open the connection contextOptionsBuilder.UseLoggerFactory(loggerFactory); // register the loggers inside the context options builder, this way, entity framework logs the queries contextOptionsBuilder.UseSqlite(connection); // we're telling entity framework to use the SQLite connection we created. contextOptionsBuilder.EnableSensitiveDataLogging(); // this will give us more insight when something does go wrong. It's ok to use it here since it's a testing project, but be careful about enabling this in production. ApplicationDbContext context = new ApplicationDbContext(contextOptionsBuilder.Options); // creating the actual DbContext context.Database.EnsureCreated(); // this command will create the schema and apply configurations we have made in the context, like relations and constraints return(context); // return the context to be further used in tests. }
private static void ApplyCommonConfiguration(IConfigurationRoot configuration, EventLogLoggerProvider eventLogProvider = null) { // This is needed because we are trying to read the config file. At this point we don't have the config info for the logger // we generally use in the broker. Log will be visible if the user runs broker interactively for broker running locally. Log // will be added to windows event log for the remote broker. using (ILoggerFactory configLoggerFactory = new LoggerFactory()) { configLoggerFactory .AddDebug() .AddConsole(LogLevel.Trace); if (eventLogProvider != null) { configLoggerFactory.AddProvider(eventLogProvider); } ILogger logger = configLoggerFactory.CreateLogger <BrokerService>(); try { string configFile = configuration["config"]; if (configFile != null) { var configBuilder = new ConfigurationBuilder().AddJsonFile(configFile, optional: false); configuration = configBuilder.Build(); } Configuration = configuration; Configuration.GetSection("startup").Bind(_startupOptions); Configuration.GetSection("security").Bind(_securityOptions); Configuration.GetSection("logging").Bind(_loggingOptions); } catch (Exception ex) when(!ex.IsCriticalException()) { logger.LogCritical(Resources.Error_ConfigFailed, ex.Message); Exit((int)BrokerExitCodes.BadConfigFile, Resources.Error_ConfigFailed, ex.Message); } } }
public FactoryMailFixture() { var loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(LogLevel.Debug); Mail = new MailerFactory(loggerFactory, Store); var mkSettings = SetupMailerOptions(out bool isMailServerAlive).Value; if (isMailServerAlive) { Mail.AddMkSmtpMailer(mkSettings); } else { Func <SmtpClient> getClientFunc = () => { var c = Substitute.For <SmtpClient>(); c .SendAsync(Arg.Any <MimeMessage>(), Arg.Any <CancellationToken>()) .Returns(Task.CompletedTask); return(c); }; Mail.AddMkSmtpMailer(getClientFunc, mkSettings); } }
internal static ILoggerFactory GetDebugLoggerFactory(LogLevel level = LogLevel.Trace) { ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(level); return(loggerFactory); }
private static ILoggerFactory getDebugLoggerFactory() { ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(LogLevel.Trace); return(loggerFactory); }
public void Setup() { _loggerFactory = new LoggerFactory(); _loggerFactory.AddDebug(); _logger = _loggerFactory.CreateLogger <AddressRegistryTests>(); _registry = GetDefaultAddressRegistryMock(); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { MyLoggerFactory.AddDebug(); optionsBuilder .UseLoggerFactory(MyLoggerFactory) .EnableSensitiveDataLogging() .UseSqlite("Data Source=blogging.db"); }
public static ILogger GetLogger(string logger = "UnitTest") { LoggerFactory factory = new LoggerFactory(); factory.AddConsole(LogLevel.Information); factory.AddDebug(LogLevel.Information); return(factory.CreateLogger(logger)); }