private static ILoggerFactory CreateLoggerFactory() { var configuration = new ConfigurationBuilder() .AddJsonFile(AppSettingsPath) .Build(); var loggingSection = configuration.GetSection("Lambda.Logging"); if (loggingSection == null) { throw new InvalidOperationException($"Cannot find Lambda.Logging section."); } var options = new LambdaLoggerOptions(configuration); if (options.IncludeCategory != false) { throw new InvalidOperationException($"IncludeCategory should be false."); } if (options.IncludeLogLevel != true) { throw new InvalidOperationException($"IncludeLogLevel should be true."); } var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(options); return(loggerfactory); }
/// <summary> /// Configures the logging stack to use the AWS LambdaLogger. /// Console output will only be included if the ASPNETCORE_ENVIRONMENT environment variable /// value is not "Staging" or "Production". /// </summary> /// <param name="services">The service collection</param> /// <param name="configuration">A Configuration instance</param> /// <returns>The service collection</returns> public static IServiceCollection ConfigureLambdaLogging(this IServiceCollection services, IConfiguration configuration) { // We rebuild the logging stack so as to ensure the console logger is not used in production. // See here: https://weblog.west-wind.com/posts/2018/Dec/31/Dont-let-ASPNET-Core-Default-Console-Logging-Slow-your-App-down services.AddLogging(config => { // clear out default configuration config.ClearProviders(); config.AddConfiguration(configuration.GetSection("Logging")); config.AddDebug(); config.AddEventSourceLogger(); // Create and populate LambdaLoggerOptions object var loggerOptions = new LambdaLoggerOptions { IncludeCategory = false, IncludeLogLevel = true, IncludeNewline = true, IncludeEventId = true, IncludeException = true, IncludeScopes = true }; config.AddLambdaLogger(loggerOptions); var aspNetcoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if ((aspNetcoreEnvironment != EnvironmentName.Production) && (aspNetcoreEnvironment != EnvironmentName.Staging)) { config.AddConsole(); } }); return(services); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { var loggerOptions = new LambdaLoggerOptions { IncludeCategory = true, IncludeLogLevel = true, IncludeNewline = true, IncludeException = true, IncludeEventId = true, IncludeScopes = true }; var provider = new LambdaJsonLoggerProvider(loggerOptions); loggerFactory.AddProvider(provider); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
/// <summary> /// Configures the <see cref="IServiceCollection"/> to use. /// </summary> /// <param name="services">The service collection to configure.</param> protected virtual void ConfigureServices(IServiceCollection services) { services.AddLogging((builder) => { var options = new LambdaLoggerOptions() { Filter = FilterLogs, }; builder.AddLambdaLogger(options); }); services.AddHttpClients(); services.AddPolly(); services.TryAddSingleton((_) => SkillConfiguration.CreateDefaultConfiguration()); services.AddSingleton <AlexaSkill>(); services.AddSingleton <FunctionHandler>(); services.AddSingleton <IntentFactory>(); services.AddSingleton((_) => TelemetryConfiguration.CreateDefault()); services.AddSingleton(CreateTelemetryClient); services.AddSingleton <EmptyIntent>(); services.AddSingleton <HelpIntent>(); services.AddSingleton <UnknownIntent>(); services.AddTransient <CommuteIntent>(); services.AddTransient <DisruptionIntent>(); services.AddTransient <StatusIntent>(); }
public void TestOnlyOneWildcardSupported() { var dict = new Dictionary <string, string> { { "Lambda.Logging:LogLevel:*.*", "Information" } }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(dict) .Build(); ArgumentOutOfRangeException exception = null; try { var loggerOptions = new LambdaLoggerOptions(configuration); } catch (ArgumentOutOfRangeException ex) { exception = ex; } // check that there are no unexpected strings in the text Assert.NotNull(exception); Assert.True(exception.Message.Contains("only 1 wildcard is supported in a category")); }
/// <summary> /// </summary> /// <param name="categoryName"></param> /// <param name="options"></param> /// <param name="applicationName"></param> /// <param name="environment"></param> public BunyanLambdaILogger(string categoryName, LambdaLoggerOptions options, string applicationName, string environment = null) : this(categoryName, options) { this.applicationName = applicationName; this.environment = environment; hostname = hostname = Dns.GetHostName(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseSession(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseStaticFiles(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}"); }); app.UseCookiePolicy(); // Configure Lambda logging var loggerOptions = new LambdaLoggerOptions(Configuration); loggerFactory.AddLambdaLogger(loggerOptions); }
public void TestOnlyTerminatingWildcardsSupported() { var dict = new Dictionary <string, string> { { "Lambda.Logging:LogLevel:Foo.*.Bar", "Information" } }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(dict) .Build(); ArgumentException exception = null; try { var loggerOptions = new LambdaLoggerOptions(configuration); } catch (ArgumentException ex) { exception = ex; } // check that there are no unexpected strings in the text Assert.NotNull(exception); Assert.True(exception.Message.Contains("wilcards are only supported at the end of a category")); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, Context db, ISchema schema) { // https://github.com/aws/aws-lambda-dotnet/tree/master/Libraries/src/Amazon.Lambda.Logging.AspNetCore var loggerOptions = new LambdaLoggerOptions(Configuration.GetSection("Lambda.Logging")); loggerFactory.AddLambdaLogger(loggerOptions); if (true) //(Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseGraphQLPlayground(new GraphQLPlaygroundOptions { Path = "/playground" }); app.UseGraphQL <ISchema>(""); schema.Initialize(); if (!Env.IsEnvironment("Test") && Environment.GetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME") == "") { db.EnsureSeedData(); } }
protected override void ConfigureLoggingService(IServiceCollection services) { // Create and populate LambdaLoggerOptions object var loggerOptions = new LambdaLoggerOptions(); loggerOptions.IncludeCategory = true; loggerOptions.IncludeLogLevel = true; loggerOptions.IncludeNewline = true; loggerOptions.IncludeException = true; loggerOptions.IncludeEventId = true; loggerOptions.IncludeScopes = true; // Configure Filter to only log some loggerOptions.Filter = (category, logLevel) => { // For some categories, only log events with minimum LogLevel if (string.Equals(category, "Default", StringComparison.Ordinal)) { return(logLevel >= LogLevel.Debug); } if (string.Equals(category, "Microsoft", StringComparison.Ordinal)) { return(logLevel >= LogLevel.Information); } // Log everything else return(true); }; var loggerFactory = (ILoggerFactory) new LoggerFactory(); loggerFactory.AddLambdaLogger(loggerOptions); var logger = loggerFactory.CreateLogger(LoggingCategoryName); services.AddSingleton(logger); }
public void TestDefaultLogLevelIfNotConfigured() { // arrange using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.without_default.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); // act // `Dummy` category is not specified, we should stick with default: min level = INFO var dummyLogger = loggerfactory.CreateLogger("Dummy"); dummyLogger.LogTrace(SHOULD_NOT_APPEAR); dummyLogger.LogDebug(SHOULD_NOT_APPEAR); dummyLogger.LogInformation(SHOULD_APPEAR); // `Microsoft` category is specified, log accordingly var msLogger = loggerfactory.CreateLogger("Microsoft"); msLogger.LogTrace(SHOULD_NOT_APPEAR); msLogger.LogDebug(SHOULD_NOT_APPEAR); msLogger.LogInformation(SHOULD_NOT_APPEAR); // assert var text = writer.ToString(); Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); } }
public void TestLoggingScopesEvents_When_ScopesDisabled() { // Arrange using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var loggerOptions = new LambdaLoggerOptions { IncludeScopes = false }; var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); var defaultLogger = loggerfactory.CreateLogger("Default"); // Act using (defaultLogger.BeginScope("First {0}", "scope123")) { defaultLogger.LogInformation("Hello"); using (defaultLogger.BeginScope("Second {0}", "scope456")) { defaultLogger.LogError("In 2nd scope"); defaultLogger.LogInformation("that's enough"); } } // Assert // get text and verify var text = writer.ToString(); Assert.Contains("[Information] Default: Hello ", text); Assert.Contains("[Error] Default: In 2nd scope ", text); Assert.Contains("[Information] Default: that's enough ", text); } }
/// <summary> /// Creates the provider /// </summary> /// <param name="options"></param> public LambdaJsonLoggerProvider(LambdaLoggerOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } _options = options; _loggers = new ConcurrentDictionary <string, LambdaJsonLogger>(); _scopeProvider = options.IncludeScopes ? new LoggerExternalScopeProvider() : NullExternalScopeProvider.Instance; }
public static LambdaLoggerOptions Build(IConfiguration config, string defaultSection) { // Create and populate LambdaLoggerOptions object. var loggerOptions = new LambdaLoggerOptions(); loggerOptions.IncludeCategory = TryGetValueFromConfig <bool>(config[$"{defaultSection}:IncludeCategory"]); loggerOptions.IncludeLogLevel = TryGetValueFromConfig <bool>(config[$"{defaultSection}:IncludeLogLevel"]); loggerOptions.IncludeNewline = TryGetValueFromConfig <bool>(config[$"{defaultSection}:IncludeNewline"]); loggerOptions.Filter = GetFiltersFromConfig(config.GetSection(defaultSection).GetSection("LogLevel")); return(loggerOptions); }
/// <summary> /// ロガーの設定を行います。 /// </summary> /// <param name="logging">logging</param> protected void ConfigureLogger(ILoggingBuilder logging) { var loggerOptions = new LambdaLoggerOptions { IncludeCategory = true, IncludeLogLevel = true, IncludeNewline = true, IncludeEventId = true, IncludeException = true }; logging.AddLambdaLogger(loggerOptions); }
[CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static ILoggerFactory AddBunyanLambdaLogger(this ILoggerFactory factory, LambdaLoggerOptions options) { if (factory == null) { throw new ArgumentNullException(nameof(factory)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var provider = new BunyanLambdaILoggerProvider(options); factory.AddProvider(provider); return(factory); }
private void SetupLogging(ILoggingBuilder logging, IConfiguration config) { var opts = new LambdaLoggerOptions(config); // var opts = new LambdaLoggerOptions // { // IncludeCategory = true, // IncludeEventId = true, // IncludeException = true, // IncludeLogLevel = true, // IncludeNewline = true, // IncludeScopes = true, // } logging.AddLambdaLogger(opts); }
protected FunctionBase( Action <IConfigurationBuilder>?configureConfiguration = null, Action <ILoggingBuilder>?configureLogging = null, Action <IServiceCollection>?configureServices = null, string environmentVariablesPrefix = "") { configureConfiguration ??= _ => { }; configureServices ??= _ => { }; configureLogging ??= _ => { }; var hostConfiguration = new ConfigurationBuilder() .AddEnvironmentVariables() .Build(); var environment = hostConfiguration[HostDefaults.EnvironmentKey] ?? Environments.Production; var configurationBuilder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true) .AddJsonFile($"appsettings.{environment}.json", optional: true) .AddEnvironmentVariables(environmentVariablesPrefix); configureConfiguration(configurationBuilder); var configurationRoot = configurationBuilder.Build(); var services = new ServiceCollection(); services.AddLogging(logging => { logging.AddConfiguration(configurationRoot); var loggerOptions = new LambdaLoggerOptions { IncludeException = true, IncludeEventId = true, IncludeScopes = true }; logging.AddLambdaLogger(loggerOptions); configureLogging(logging); }); services.AddSingleton <IConfiguration>(configurationRoot); services.AddOptions <TOptions>().Bind(configurationRoot); services.AddTransient <THandler>(); services.AddFeatureManagement(); configureServices(services); ServiceProvider = services.BuildServiceProvider(); }
public void TestConfigurationReadingForExceptionsEvents() { // Arrange var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.exceptions.json")) .Build(); // Act var loggerOptions = new LambdaLoggerOptions(configuration); // Assert Assert.False(loggerOptions.IncludeCategory); Assert.False(loggerOptions.IncludeLogLevel); Assert.False(loggerOptions.IncludeNewline); Assert.True(loggerOptions.IncludeEventId); Assert.True(loggerOptions.IncludeException); }
public void TestLoggingWithTypeCategories() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); // arrange var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.nsprefix.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); var loggerFactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); // act var httpClientLogger = loggerFactory.CreateLogger <System.Net.HttpListener>(); var authMngrLogger = loggerFactory.CreateLogger <System.Net.AuthenticationManager>(); var arrayLogger = loggerFactory.CreateLogger <System.Array>(); httpClientLogger.LogTrace(SHOULD_NOT_APPEAR); httpClientLogger.LogDebug(SHOULD_APPEAR); httpClientLogger.LogInformation(SHOULD_APPEAR); httpClientLogger.LogWarning(SHOULD_APPEAR); httpClientLogger.LogError(SHOULD_APPEAR); httpClientLogger.LogCritical(SHOULD_APPEAR); authMngrLogger.LogTrace(SHOULD_NOT_APPEAR); authMngrLogger.LogDebug(SHOULD_NOT_APPEAR); authMngrLogger.LogInformation(SHOULD_APPEAR); authMngrLogger.LogWarning(SHOULD_APPEAR); authMngrLogger.LogError(SHOULD_APPEAR); authMngrLogger.LogCritical(SHOULD_APPEAR); arrayLogger.LogTrace(SHOULD_NOT_APPEAR); arrayLogger.LogDebug(SHOULD_NOT_APPEAR); arrayLogger.LogInformation(SHOULD_NOT_APPEAR); arrayLogger.LogWarning(SHOULD_APPEAR); arrayLogger.LogError(SHOULD_APPEAR); arrayLogger.LogCritical(SHOULD_APPEAR); // assert var text = writer.ToString(); Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var loggerOptions = new LambdaLoggerOptions { IncludeCategory = false, IncludeLogLevel = false, IncludeNewline = true, // Configure Filter to only log some Filter = (category, logLevel) => { // For some categories, only log events with minimum LogLevel if (string.Equals(category, "Default", StringComparison.Ordinal)) { return(logLevel >= LogLevel.Debug); } if (string.Equals(category, "Microsoft", StringComparison.Ordinal)) { return(logLevel >= LogLevel.Information); } return(true); } }; // Configure Lambda logging loggerFactory .AddLambdaLogger(loggerOptions); app.UseAuthentication(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); }
[CLSCompliant(false)] // https://github.com/aspnet/Logging/issues/500 public static ILoggerFactory AddBunyanLambdaLogger(this ILoggerFactory factory, IConfiguration configuration, string loggingSectionName) { if (factory == null) { throw new ArgumentNullException(nameof(factory)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (string.IsNullOrEmpty(loggingSectionName)) { throw new ArgumentNullException(nameof(loggingSectionName)); } var options = new LambdaLoggerOptions(configuration, loggingSectionName); var provider = new BunyanLambdaILoggerProvider(options); factory.AddProvider(provider); return(factory); }
public void TestDefaultLogLevel() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); // act // creating named logger, `Default` category is set to "Debug" // (Default category has special treatment - it's not actually stored, named logger just falls to default) var defaultLogger = loggerfactory.CreateLogger("Default"); defaultLogger.LogTrace(SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_APPEAR); defaultLogger.LogInformation(SHOULD_APPEAR); // `Dummy` category is not specified, we should use `Default` category instead var dummyLogger = loggerfactory.CreateLogger("Dummy"); dummyLogger.LogTrace(SHOULD_NOT_APPEAR); dummyLogger.LogDebug(SHOULD_APPEAR); dummyLogger.LogInformation(SHOULD_APPEAR); // `Microsoft` category is specified, log accordingly var msLogger = loggerfactory.CreateLogger("Microsoft"); msLogger.LogTrace(SHOULD_NOT_APPEAR); msLogger.LogDebug(SHOULD_NOT_APPEAR); msLogger.LogInformation(SHOULD_APPEAR); // assert var text = writer.ToString(); Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); } }
/// <summary> /// Constructor. /// </summary> /// <param name="categoryName">Category name for the logger.</param> /// <param name="options">Options for the logger.</param> public LambdaJsonLogger(string categoryName, LambdaLoggerOptions options) { _categoryName = categoryName; _options = options; }
public void TestWilcardConfiguration() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.wildcard.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); Assert.False(loggerOptions.IncludeCategory); Assert.False(loggerOptions.IncludeLogLevel); Assert.False(loggerOptions.IncludeNewline); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); int count = 0; // Should match: // "Foo.*": "Information" var foobarLogger = loggerfactory.CreateLogger("Foo.Bar"); foobarLogger.LogTrace(SHOULD_NOT_APPEAR); foobarLogger.LogDebug(SHOULD_NOT_APPEAR); foobarLogger.LogInformation(SHOULD_APPEAR + (count++)); foobarLogger.LogWarning(SHOULD_APPEAR + (count++)); foobarLogger.LogError(SHOULD_APPEAR + (count++)); foobarLogger.LogCritical(SHOULD_APPEAR + (count++)); // Should match: // "Foo.Bar.Baz": "Critical" var foobarbazLogger = loggerfactory.CreateLogger("Foo.Bar.Baz"); foobarbazLogger.LogTrace(SHOULD_NOT_APPEAR); foobarbazLogger.LogDebug(SHOULD_NOT_APPEAR); foobarbazLogger.LogInformation(SHOULD_NOT_APPEAR); foobarbazLogger.LogWarning(SHOULD_NOT_APPEAR); foobarbazLogger.LogError(SHOULD_NOT_APPEAR); foobarbazLogger.LogCritical(SHOULD_APPEAR + (count++)); // Should match: // "Foo.Bar.*": "Warning" var foobarbuzzLogger = loggerfactory.CreateLogger("Foo.Bar.Buzz"); foobarbuzzLogger.LogTrace(SHOULD_NOT_APPEAR); foobarbuzzLogger.LogDebug(SHOULD_NOT_APPEAR); foobarbuzzLogger.LogInformation(SHOULD_NOT_APPEAR); foobarbuzzLogger.LogWarning(SHOULD_APPEAR + (count++)); foobarbuzzLogger.LogError(SHOULD_APPEAR + (count++)); foobarbuzzLogger.LogCritical(SHOULD_APPEAR + (count++)); // Should match: // "*": "Error" var somethingLogger = loggerfactory.CreateLogger("something"); somethingLogger.LogTrace(SHOULD_NOT_APPEAR); somethingLogger.LogDebug(SHOULD_NOT_APPEAR); somethingLogger.LogInformation(SHOULD_NOT_APPEAR); somethingLogger.LogWarning(SHOULD_NOT_APPEAR); somethingLogger.LogError(SHOULD_APPEAR + (count++)); somethingLogger.LogCritical(SHOULD_APPEAR + (count++)); // get text and verify var text = writer.ToString(); // check that there are no unexpected strings in the text Assert.False(text.Contains(SHOULD_NOT_APPEAR)); // check that all expected strings are in the text for (int i = 0; i < count; i++) { var expected = SHOULD_APPEAR + i; Assert.True(text.Contains(expected), $"Expected to find '{expected}' in '{text}'"); } } }
public void TestConfiguration() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); Assert.False(loggerOptions.IncludeCategory); Assert.False(loggerOptions.IncludeLogLevel); Assert.False(loggerOptions.IncludeNewline); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); int count = 0; var defaultLogger = loggerfactory.CreateLogger("Default"); defaultLogger.LogTrace(SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_APPEAR + (count++)); defaultLogger.LogCritical(SHOULD_APPEAR + (count++)); defaultLogger = loggerfactory.CreateLogger(null); defaultLogger.LogTrace(SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_APPEAR + (count++)); defaultLogger.LogCritical(SHOULD_APPEAR + (count++)); // change settings int countAtChange = count; loggerOptions.IncludeCategory = true; loggerOptions.IncludeLogLevel = true; loggerOptions.IncludeNewline = true; var msLogger = loggerfactory.CreateLogger("Microsoft"); msLogger.LogTrace(SHOULD_NOT_APPEAR); msLogger.LogInformation(SHOULD_APPEAR + (count++)); msLogger.LogCritical(SHOULD_APPEAR + (count++)); var sdkLogger = loggerfactory.CreateLogger("AWSSDK"); sdkLogger.LogTrace(SHOULD_APPEAR + (count++)); sdkLogger.LogInformation(SHOULD_APPEAR + (count++)); sdkLogger.LogCritical(SHOULD_APPEAR + (count++)); // get text and verify var text = writer.ToString(); // check that there are no unexpected strings in the text Assert.False(text.Contains(SHOULD_NOT_APPEAR)); // check that all expected strings are in the text for (int i = 0; i < count; i++) { var expected = SHOULD_APPEAR + i; Assert.True(text.Contains(expected), $"Expected to find '{expected}' in '{text}'"); } // check extras that were added mid-way int numberOfExtraBits = count - countAtChange; // count levels var logLevelStrings = Enum.GetNames(typeof(LogLevel)).Select(ll => $"[{ll}").ToList(); Assert.Equal(numberOfExtraBits, CountMultipleOccurences(text, logLevelStrings)); // count categories var categoryStrings = new string[] { "Microsoft", "AWSSDK" }; Assert.Equal(numberOfExtraBits, CountMultipleOccurences(text, categoryStrings)); // count newlines Assert.Equal(numberOfExtraBits, CountOccurences(text, Environment.NewLine)); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(options => { options.Conventions.AuthorizeFolder("/CP"); options.Conventions.AllowAnonymousToPage("/CP/login"); options.Conventions.AllowAnonymousToPage("/CP/logout"); }); services.AddServerSideBlazor(); string a = new PathString("/cp/login"); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o => { o.Events = new CookieAuthenticationEvents() { OnRedirectToLogin = async(context) => { context.HttpContext.Response.Redirect(CachedData.BaseUrl + new PathString("/cp/login")); } }; }); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddHttpContextAccessor(); services.AddSession(); services.AddCors(o => o.AddPolicy("CorsPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); AWSOptions awsOptions = Configuration.GetAWSOptions(); //IAmazonS3 client = awsOptions.CreateServiceClient<IAmazonS3>(); if (CachedData.Environment.EnvironmentName == "Production") { //Store Session in DynamoDB services.AddDefaultAWSOptions(awsOptions); services.AddAWSService <IAmazonDynamoDB>(); services.AddSingleton <IXmlRepository, Session.DdbXmlRepository>(); services.AddDistributedDynamoDbCache(o => { o.TableName = "StreamingLiveSessionState"; o.IdleTimeout = TimeSpan.FromMinutes(30); }); services.AddSession(o => { o.IdleTimeout = TimeSpan.FromMinutes(30); o.Cookie.HttpOnly = false; }); var sp = services.BuildServiceProvider(); //***Not sure this is the proper way to access this services.AddDataProtection().AddKeyManagementOptions(o => o.XmlRepository = sp.GetService <IXmlRepository>()); //Log errors to Cloudwatch services.AddLogging(factory => { var loggerOptions = new LambdaLoggerOptions(); loggerOptions.IncludeCategory = false; loggerOptions.IncludeLogLevel = false; loggerOptions.IncludeNewline = true; loggerOptions.IncludeException = true; loggerOptions.IncludeEventId = true; loggerOptions.IncludeScopes = true; loggerOptions.Filter = (category, logLevel) => { //if (string.Equals(category, "Default", StringComparison.Ordinal)) return (logLevel >= LogLevel.Debug); //if (string.Equals(category, "Microsoft", StringComparison.Ordinal)) return (logLevel >= LogLevel.Debug); //return true; return(logLevel >= LogLevel.Debug); }; factory.AddLambdaLogger(loggerOptions); }); } services.AddAWSService <IAmazonS3>(); }
/// <summary> /// /// </summary> /// <param name="options"></param> /// <param name="applicationName"></param> /// <param name="environment"></param> public BunyanLambdaILoggerProvider(LambdaLoggerOptions options, string applicationName, string environment = null) { this.options = options ?? throw new ArgumentNullException(nameof(options)); this.applicationName = applicationName; this.environment = environment; }
/// <summary> /// /// </summary> /// <param name="options"></param> public BunyanLambdaILoggerProvider(LambdaLoggerOptions options) { this.options = options ?? throw new ArgumentNullException(nameof(options)); }
public void TestLoggingExceptionsAndEvents() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); int countMessage = 0; int countEvent = 0; int countException = 0; var defaultLogger = loggerfactory.CreateLogger("Default"); defaultLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR_EXCEPTION, SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++)); defaultLogger.LogCritical(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++)); defaultLogger = loggerfactory.CreateLogger(null); defaultLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++)); defaultLogger.LogCritical(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++)); // change settings loggerOptions.IncludeCategory = true; loggerOptions.IncludeLogLevel = true; loggerOptions.IncludeNewline = true; loggerOptions.IncludeException = true; loggerOptions.IncludeEventId = true; var msLogger = loggerfactory.CreateLogger("Microsoft"); msLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR_EXCEPTION, SHOULD_NOT_APPEAR); msLogger.LogInformation(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++)); msLogger.LogCritical(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++)); var sdkLogger = loggerfactory.CreateLogger("AWSSDK"); sdkLogger.LogTrace(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++)); sdkLogger.LogInformation(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++)); sdkLogger.LogCritical(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++)); // get text and verify var text = writer.ToString(); // check that there are no unexpected strings in the text Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); Assert.DoesNotContain(SHOULD_NOT_APPEAR_EVENT.Id.ToString(), text); Assert.DoesNotContain(SHOULD_NOT_APPEAR_EVENT.Name, text); Assert.DoesNotContain(SHOULD_NOT_APPEAR_EXCEPTION.Message, text); // check that all expected strings are in the text for (int i = 0; i < countMessage; i++) { var expectedMessages = SHOULD_APPEAR + i; Assert.True(text.Contains(expectedMessages), $"Expected to find '{expectedMessages}' in '{text}'"); } for (int i = 0; i < countException; i++) { var expectedMessages = SHOULD_APPEAR_EXCEPTION + i; Assert.True(text.Contains(expectedMessages), $"Expected to find '{expectedMessages}' in '{text}'"); } for (int i = 0; i < countEvent; i++) { var expectedMessages = SHOULD_APPEAR_EVENT + i; Assert.True(text.Contains(expectedMessages), $"Expected to find '{expectedMessages}' in '{text}'"); } } }