public static Microsoft.Extensions.Logging.ILoggerFactory GetLoggerFactory() { var fac = new Microsoft.Extensions.Logging.LoggerFactory(); fac.AddSerilog(); return(fac); }
public async Task CanUseSelectedHoststDependencies() { // Make sure that the referenced version of JSON.NET is loaded into memory var json = Newtonsoft.Json.JsonConvert.SerializeObject(1); // Make sure that the referenced version of Microsoft.Extensions.Logging is loaded into memory var logging = new Microsoft.Extensions.Logging.LoggerFactory(); var options = new AssemblyPluginCatalogOptions();; options.PluginLoadContextOptions = new PluginLoadContextOptions() { UseHostApplicationAssemblies = UseHostApplicationAssembliesEnum.Selected, HostApplicationAssemblies = new List <AssemblyName>() { typeof(Microsoft.Extensions.Logging.LoggerFactory).Assembly.GetName() } }; var catalog = new AssemblyPluginCatalog(@"..\..\..\..\..\Assemblies\bin\JsonOld\netstandard2.0\JsonNetOld.dll", options); await catalog.Initialize(); var oldPlugin = catalog.Single(); dynamic oldPluginJsonResolver = Activator.CreateInstance(oldPlugin); var oldPluginVersion = oldPluginJsonResolver.GetVersion(); var loggerVersion = oldPluginJsonResolver.GetLoggingVersion(); Assert.Equal("3.1.2.0", loggerVersion); Assert.Equal("9.0.0.0", oldPluginVersion); }
private static void RegisterLoggerFactory() { var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); loggerFactory.AddLog4Net(true); Container.RegisterInstance <Microsoft.Extensions.Logging.ILoggerFactory>(loggerFactory); }
private static Microsoft.Extensions.Logging.ILoggerFactory _CreateLoggerFactory() { var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); Microsoft.Extensions.Logging.ConsoleLoggerExtensions.AddConsole(loggerFactory); return(loggerFactory); }
public string GetLoggingVersion() { var logging = new Microsoft.Extensions.Logging.LoggerFactory(); Console.WriteLine(logging.ToString()); var result = typeof(Microsoft.Extensions.Logging.LoggerFactory).Assembly.GetName().Version.ToString(); return(result); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string currentDirectory = Directory.GetCurrentDirectory(); optionsBuilder.UseSqlite(string.Format("Filename={0}", Path.Combine(currentDirectory, DatabaseFileName))); Microsoft.Extensions.Logging.LoggerFactory loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); loggerFactory.AddProvider(new DbLoggerProvider()); optionsBuilder.UseLoggerFactory(loggerFactory); optionsBuilder.EnableSensitiveDataLogging(); }
/// <summary> /// Setup and configuration of the <see cref="LogManager"/> with a custom serilog built configuration. /// </summary> /// <param name="configuration">The Serilog configure to be loaded.</param> /// <exception cref="ArgumentNullException">Thrown when a null configuration is provided.</exception> public static void LoadLogManager(LoggerConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } var logger = configuration.CreateLogger(); var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); var loadedFactory = loggerFactory.AddSerilog(logger); LogManager.InitalizeManager(loadedFactory); }
/// <summary> /// Adds a console logger. Can be omitted if internal SIPSorcery debug and warning messages are not required. /// </summary> private static void AddConsoleLogger() { var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); var loggerConfig = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Is(Serilog.Events.LogEventLevel.Information) .WriteTo.Console() .CreateLogger(); loggerFactory.AddSerilog(loggerConfig); SIPSorcery.Sys.Log.LoggerFactory = loggerFactory; }
public void TestInit() { SQLitePCL.Batteries_V2.Init(); var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); var logger = loggerFactory.CreateLogger(nameof(KeyValueLite)); //Clear db //var dbPath = dsFactory.GetDataStorePathName(nameof(KeyValueLite)); //File.Delete(dbPath); var dsFactory = new DataStoreFactory(new GenericPlatformService()); cacheService = new KeyValueLite(dsFactory, new KeyValueItemSytemTextJsonSerializer(), logger); }
static async Task Main(string[] args) { Console.WriteLine("Hello World!"); var token = System.Threading.CancellationToken.None; using var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); //NullLogger.Instance await using var transport = new ServerNet.TcpTransport(loggerFactory.CreateLogger("TCP local")); var localEndpoint = "127.0.0.1:32452"; var messages = transport.BindAsync(IPEndPoint.Parse(localEndpoint), token); var reader = Task.Run(async() => { await foreach (var incoming in messages.WithCancellation(token)) { using var msg = incoming; var text = Encoding.UTF8.GetString(msg.Payload.FirstSpan); Console.WriteLine($"Received message from '{msg.Endpoint}': {text}"); } }); Console.WriteLine($"Local host started at {transport.LocalEndpoint} ..."); //var endpoints = new List<IPEndPoint>(); //foreach (var hostWithPort in options.SeedNodes) //{ // var endpoint = IPEndPoint.Parse(hostWithPort); // endpoints.Add(endpoint); //} Console.WriteLine("Ready to receive messages..."); var userText = ""; do { Console.Write("> "); userText = Console.ReadLine(); //var bytes = new System.Buffers.ReadOnlySequence<byte>(Encoding.UTF8.GetBytes(userText)); //foreach (var endpoint in endpoints) //{ // await transport.SendAsync(endpoint, bytes, token); // Console.WriteLine($"Sent '{userText}' to {endpoint}..."); //} } while (userText != "quit"); }
public RSocketWebSocketClient(Uri url) { Url = url; var logger = new Microsoft.Extensions.Logging.LoggerFactory(new[] { new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider() }); //TODO Really, we should take the CWSO and invert it into the HTTPCO below - super goofy since they just reverse it later on... //new ClientWebSocketOptions(). Transport = new WebSocketsTransport(new HttpConnectionOptions() { Url = url, }, logger, null); Transport2 = new WebSocketTransport(url); }
public static void UseHealthChecks( this IAppBuilder app, string url, HealthCheckOptions options, params IHealthCheck[] healthChecks) { var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); var logger = loggerFactory.CreateLogger(nameof(HealthCheckMiddleware)); app.Map(url, appBuilder => { appBuilder.Use <HealthCheckMiddleware>( logger, options, healthChecks); }); }
public static Microsoft.Extensions.Logging.ILogger InitTestLogger(Xunit.Abstractions.ITestOutputHelper output) { #if DEBUG string template = "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} [{Level}] {Scope} {Message}{NewLine}{Exception}"; //string template = "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} [{Level}] ({ThreadId:000}){Scope} {Message}{NewLine}{Exception}"; var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); var loggerConfig = new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.WithProperty("ThreadId", System.Threading.Thread.CurrentThread.ManagedThreadId) .WriteTo.TestOutput(output, outputTemplate: template) .WriteTo.Console(outputTemplate: template) .CreateLogger(); loggerFactory.AddSerilog(loggerConfig); SIPSorcery.Sys.Log.LoggerFactory = loggerFactory; #endif return(SIPSorcery.Sys.Log.Logger); }
/// <summary> /// Setup and configuration of the <see cref="LogManager"/> with the entire configuration being loaded from the config file. /// </summary> /// <param name="configuration">The loaded application settings from the hosting app.settings file.</param> /// <param name="includeMachineName">Optional parameter that determines if the machine name will be included in the logging, this is set to a default value of true.</param> /// <param name="includeThreadId">Optional parameter that determines if the executing thread id will be included in the logging, this is set to a default value of false.</param> /// <param name="includeThreadName">Optional parameter that determines if the executing thread name will be included in the logging, this is set to a default value of false. </param> /// public static void LoadLogManager(IConfiguration configuration, bool includeMachineName = true, bool includeThreadId = true, bool includeThreadName = false) { // instantiate and configure logging. Using serilog here, to log to console and a text-file. var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); var loggerConfig = LoadConfiguration(configuration); if (includeMachineName) { loggerConfig.Enrich.WithMachineName(); } if (includeThreadId) { loggerConfig.Enrich.WithThreadId(); } if (includeThreadName) { loggerConfig.Enrich.WithThreadName(); } var logger = loggerConfig.CreateLogger(); var loadedFactory = loggerFactory.AddSerilog(logger); LogManager.InitalizeManager(loadedFactory); }
public void TestMethod1() { var settings = new NpgsqlSettings { ConnectionString = "Server=localhost;Port=5433;Database=kasbah;User Id=kasbah;Password=kasbah" }; var typeRegistry = new TypeRegistry(); typeRegistry.Register <TestType>(); var contentProvider = new ContentProvider(settings); var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); var eventBus = new EventBus(Enumerable.Empty <IOnContentPublished>()); var typeMapper = new TypeMapper(loggerFactory, contentProvider, null, typeRegistry); var queryProviderFactory = new KasbahQueryProviderFactory(loggerFactory, settings, typeRegistry, typeMapper); var contentService = new ContentService(loggerFactory, contentProvider, typeRegistry, eventBus, queryProviderFactory); contentService.Query <TestType>() // .Where(ent => ent.TestProp == "hello" && ent.PestTrop != "olleh") .Where(ent => ent.PestTrop.Contains("bye")) .Skip(0) .Take(5) .ToList(); }
public void Setup() { var factory = new Microsoft.Extensions.Logging.LoggerFactory(); LibraryLogger.Factory = factory; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <ApplicationIdentityContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("AspNetCore"))); //add aspnet identity services.AddIdentity <Framework.AspNetIdentity.ApplicationUser, ApplicationRole>() .AddEntityFrameworkStores <ApplicationIdentityContext>() .AddUserManager <ApplicationUserManager>() .AddDefaultTokenProviders(); var clients = Configuration.GetSection("ClientSettings").Get <Client[]>(); foreach (var item in clients) { item.ClientSecrets = new List <Secret> { new Secret("secret".Sha256()) }; } var apiResources = Configuration.GetSection("ApiResources").Get <ApiResource[]>(); //add identityserver services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryPersistedGrants() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(apiResources) //.AddInMemoryClients(Config.GetClients()) .AddInMemoryClients(clients) .AddAspNetIdentity <ApplicationUser>(); services.AddTransient <IProfileService, IdentityClaimsProfileService>(); services.AddMvc(); // .AddRazorPagesOptions(options => // { // options.Conventions.AuthorizeFolder("/Account/Manage"); // options.Conventions.AuthorizePage("/Account/Logout"); // }) ; //add serilog Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger(); var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory().AddSerilog(Log.Logger); services.AddSingleton(loggerFactory).AddLogging(); // Register no-op EmailSender used by account confirmation and password reset during development // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 services.AddSingleton <IEmailSender, EmailSender>(); //add authentication var appSettingsSection = Configuration.GetSection("JwtSettings"); services.Configure <JwtSettings>(appSettingsSection); // configure jwt authentication var appSettings = appSettingsSection.Get <JwtSettings>(); //var key = Encoding.ASCII.GetBytes(appSettings.Secret); var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(appSettings.SecurityKey)); // api user claim policy //services.AddAuthorization(options => //{ // options.AddPolicy("ApiUser", policy => policy.RequireClaim("ABC", "ApiAccess")); //}); //services.AddAuthentication(x => //{ // x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; // x.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; //}) //.AddCookie() //.AddJwtBearer(x => //{ // x.RequireHttpsMetadata = false; // x.SaveToken = true; // x.TokenValidationParameters = new TokenValidationParameters // { // ValidateIssuerSigningKey = true, // IssuerSigningKey = securityKey, // //ValidateIssuer = true, // //ValidateAudience = true, // ValidAudience = appSettings.Audience, // ValidIssuer = appSettings.Issuer // }; //}); services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:44302"; options.RequireHttpsMetadata = false; options.ApiName = "api2"; }); services.AddScoped <IJwtTokenManagerService, JwtTokenManager>(); //end add authentication }