public async Task Should_Redact_Dynamic_Multiple_Paths()
        {
            // Arrange
            var loggerMock = new Mock <ILogger <LoggingMiddleware> >();
            var options    = Options.Create(new LoggingSettings
            {
                PathsToRedact = new[] { "/api/v1/devices/{*}/activate/{*}" }
            });

            var middleware = new LoggingMiddleware(
                (innerHttpContext) => Task.CompletedTask,
                loggerMock.Object,
                options,
                new AppContextAccessorMock()
                );

            var context = CreateHttpContext();

            context.Request.Path = "/api/v1/devices/guid-identifier/activate/{another-guid}";

            //Act
            await middleware.Invoke(context);

            //Assert
            loggerMock.Verify(l => l.BeginScope(It.IsAny <It.IsAnyType>()), Times.Exactly(1));

            loggerMock.Verify(l => l.Log(
                                  LogLevel.Information,
                                  0,
                                  It.Is <It.IsAnyType>((v, _) => (v.ToString() ?? string.Empty).Contains("[redacted]")),
                                  It.IsAny <Exception>(),
                                  (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                              Times.Once
                              );
        }
        public async Task LoggingMiddleware_IgnoresLog_ForSwagger(string scheme, string host, string path,
                                                                  string queryString, string method, int statusCode)
        {
            // Arrange
            RequestDelegate next        = (innerHttpContext) => Task.FromResult(0);
            var             loggerMock  = new Mock <ILogger <LoggingMiddleware> >();
            var             contextMock = new Mock <HttpContext>();
            var             requestMock = new Mock <HttpRequest>();

            contextMock.SetupGet(x => x.Request).Returns(requestMock.Object);
            MockRequestGetDispayedUrl(requestMock, scheme, host, path, method, queryString);

            var logRequestMiddleware = new LoggingMiddleware(next: next, logger: loggerMock.Object);

            // Act
            await logRequestMiddleware.Invoke(contextMock.Object);

            // Assert
            loggerMock.VerifyAll();
            contextMock.VerifyAll();
            requestMock.VerifyAll();
            loggerMock.Verify(m =>
                              m.Log(It.IsAny <LogLevel>(), It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()),
                              Times.Never);
        }
        public async Task Should_Ignore_Authorization_Header()
        {
            // Arrange
            var loggerMock = new Mock <ILogger <LoggingMiddleware> >();

            var options    = Options.Create(new LoggingSettings());
            var middleware = new LoggingMiddleware(
                (innerHttpContext) => Task.CompletedTask,
                loggerMock.Object,
                options,
                new AppContextAccessorMock()
                );

            var context = CreateHttpContext();

            context.Request.Path = "/api/v1/tests";
            context.Request.Body = new MemoryStream();
            context.Request.Headers.Add("Authorization", "JWT_TOKEN");
            context.Request.Headers.Add("User-Agent", "android");

            //Act
            await middleware.Invoke(context);

            //Assert
            loggerMock.Verify(l => l.Log(
                                  LogLevel.Information,
                                  0,
                                  It.Is <It.IsAnyType>((v, _) => !(v.ToString() ?? string.Empty).Contains("Authorization")
                                                       ),
                                  It.IsAny <Exception>(),
                                  (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                              Times.Exactly(2)
                              );
        }
示例#4
0
 public void Setup()
 {
     _timerFake         = new TimerFake();
     _timerFactoryFake  = new TimerFactoryFake(_timerFake);
     _loggerFake        = new LoggerFake();
     _context           = new OwinContextFake();
     _nextFake          = new OwinMiddlewareFake();
     _loggingMiddleware = new LoggingMiddleware(_nextFake, _loggerFake, _timerFactoryFake);
 }
示例#5
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseRouting();
            app.UseGrpcWeb();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService <DataService>().EnableGrpcWeb();
                endpoints.MapHub <ConnectionsHub>("/connectionsHub");
                endpoints.MapHub <ExecuteHub>("/executeHub", o =>
                {
                    o.LongPolling.PollTimeout = TimeSpan.MaxValue;
                });
            });

            IMiddleware cookieMiddleware  = new CookieMiddleware();
            IMiddleware loggingMiddleware = new LoggingMiddleware(loggerFactory);

            if (env.IsDevelopment())
            {
                cookieMiddleware.Use(app);
                if (Program.Settings.LogRequests)
                {
                    loggingMiddleware.Use(app);
                }
                app.UseDevelopmentMiddleware();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                if (Program.Settings.LogRequests)
                {
                    app.UseResourceMiddleware(cookieMiddleware, loggingMiddleware);
                }
                else
                {
                    app.UseResourceMiddleware(cookieMiddleware);
                }
            }

            if (Program.Settings.LogPgCodeCommandNotice || Program.Settings.LogPgCodeDbCommands)
            {
                ConnectionManager.AddLoggers(loggerFactory);
            }

            if (Program.Settings.LogPgCodeCommandNotice)
            {
                ConnectionManager.AddNoticeHandlersToConnections(loggerFactory);
            }

            app.UseHttpsRedirection();
        }
示例#6
0
        public void MiddlewareTest()
        {
            var middleware = new LoggingMiddleware <AppState>();
            var store      = new Store <AppState>(
                new AppReducer(),
                new AppState(),
                middleware);

            store.Dispatch(new IncrementAction());

            Assert.Equal(1, store.State.Count);
            Assert.Equal(2, middleware.Logs.Count);
            Assert.Equal("Executing IncrementAction", middleware.Logs[0]);
            Assert.Equal("Executed IncrementAction", middleware.Logs[1]);
        }
        public async Task Should_Log_Error_Response()
        {
            // Arrange
            var loggerMock = new Mock <ILogger <LoggingMiddleware> >();

            var options    = Options.Create(new LoggingSettings());
            var middleware = new LoggingMiddleware(
                (innerHttpContext) => Task.CompletedTask,
                loggerMock.Object,
                options,
                new AppContextAccessorMock()
                );

            var context = CreateHttpContext();

            context.Request.Path        = "/api/v1/tests";
            context.Request.Body        = new MemoryStream();
            context.Request.Scheme      = "https";
            context.Response.StatusCode = 500;

            //Act
            await middleware.Invoke(context);

            //Assert
            loggerMock.Verify(l => l.BeginScope(It.IsAny <It.IsAnyType>()), Times.Exactly(1));

            loggerMock.Verify(l => l.Log(
                                  LogLevel.Information,
                                  0,
                                  It.Is <It.IsAnyType>((v, _) => (v.ToString() ?? string.Empty).StartsWith("Request")),
                                  It.IsAny <Exception>(),
                                  (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                              Times.Once
                              );

            loggerMock.Verify(l => l.Log(
                                  LogLevel.Information,
                                  0,
                                  It.Is <It.IsAnyType>((v, _) => (v.ToString() ?? string.Empty).StartsWith("Response")),
                                  It.IsAny <Exception>(),
                                  (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                              Times.Once
                              );
        }
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            IChannelProvider channelProvider,
            AuthenticationConfiguration authConfig,
            LocaleTemplateManager templateEngine,
            ConversationState conversationState,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient,
            ILogger <BotFrameworkHttpAdapter> logger,
            LoggingMiddleware loggingMiddleware,
            HandoffMiddleware handoffMiddleware,
            SkillsConfiguration skillsConfig = null,
            SkillHttpClient skillClient      = null)
            : base(credentialProvider, authConfig, channelProvider, logger: logger)
        {
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _logger            = logger ?? throw new ArgumentNullException(nameof(logger));
            _templateEngine    = templateEngine ?? throw new ArgumentNullException(nameof(templateEngine));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _skillClient       = skillClient;
            _skillsConfig      = skillsConfig;
            _settings          = settings;

            OnTurnError = HandleTurnErrorAsync;

            Use(telemetryMiddleware);
            Use(loggingMiddleware);
            Use(handoffMiddleware);

            // Uncomment the following line for local development without Azure Storage
            // Use(new TranscriptLoggerMiddleware(new MemoryTranscriptStore()));
            Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new SetSpeakMiddleware());
        }
        public async Task Should_Ignore_Paths()
        {
            // Arrange
            var loggerMock = new Mock <ILogger <LoggingMiddleware> >();

            var options    = Options.Create(new LoggingSettings());
            var middleware = new LoggingMiddleware(
                (innerHttpContext) => Task.CompletedTask,
                loggerMock.Object,
                options,
                new AppContextAccessorMock()
                );

            var context = CreateHttpContext();

            context.Request.Path = "/health";

            //Act
            await middleware.Invoke(context);

            //Assert
            loggerMock.Verify(l => l.BeginScope(It.IsAny <It.IsAnyType>()), Times.Never());
        }
        public async Task LoggingMiddleware_LogsContextInfo(string scheme, string host, string path,
                                                            string queryString, string method, int statusCode)
        {
            // Arrange
            RequestDelegate next         = (innerHttpContext) => Task.FromResult(0);
            var             loggerMock   = new Mock <ILogger <LoggingMiddleware> >();
            var             contextMock  = new Mock <HttpContext>();
            var             requestMock  = new Mock <HttpRequest>();
            var             responseMock = new Mock <HttpResponse>();

            contextMock.SetupGet(x => x.Request).Returns(requestMock.Object);
            MockRequestGetDispayedUrl(requestMock, scheme, host, path, method, queryString);
            requestMock.Setup(x => x.Method).Returns(method);
            contextMock.SetupGet(x => x.Response).Returns(responseMock.Object);
            responseMock.SetupGet(x => x.StatusCode).Returns(statusCode);
            var allParts = new[] { scheme, host, path, queryString, method, statusCode.ToString() };

            // Mock logger.LogDebug
            loggerMock.Setup(m => m.Log(
                                 LogLevel.Debug,
                                 It.IsAny <EventId>(),
                                 It.Is <FormattedLogValues>(v => allParts.All(x => v.ToString().Contains(x))),
                                 It.IsAny <Exception>(),
                                 It.IsAny <Func <object, Exception, string> >()
                                 ));

            var logRequestMiddleware = new LoggingMiddleware(next: next, logger: loggerMock.Object);

            // Act
            await logRequestMiddleware.Invoke(contextMock.Object);

            // Assert
            loggerMock.VerifyAll();
            contextMock.VerifyAll();
            requestMock.VerifyAll();
            responseMock.VerifyAll();
        }
        public LivePersonAdapter(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, HandoffMiddleware handoffMiddleware, LoggingMiddleware loggingMiddleware)
            : base(configuration, logger)
        {
            Use(handoffMiddleware);
            Use(loggingMiddleware);

            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");

                // Send a message to the user
                await turnContext.SendActivityAsync($"The bot encounted an error '{exception.Message}'.").ConfigureAwait(false);

                // Send a trace activity, which will be displayed in the Bot Framework Emulator
                await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError").ConfigureAwait(false);
            };
        }
 public LoggingMiddlewareTests()
 {
     _sut = new LoggingMiddleware(_next, _logger);
 }