Esempio n. 1
0
#pragma warning disable RECS0154 // Parameter is never used
        public static void Configure(HttpConfiguration config)
#pragma warning restore RECS0154 // Parameter is never used
        {
            // Use Seriog for logging
            // More information can be found here https://github.com/serilog/serilog/wiki/Getting-Started

            var f    = new FileInfo(Assembly.GetExecutingAssembly().Location);
            var name = f.Name.Replace(f.Extension, "");

            // TODO: Adjust log file location and name.
            // By default log file is located in 'C:\Users\<username>\AppData\Roaming\Logs' folder and named as the current assembly name
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File(ExpandEnvironmentVariables($"%AppData%/Logs/{name}..txt"), rollingInterval: RollingInterval.Day)
                         .ReadFrom.AppSettings()

                         // Enrich with SerilogWeb.Classic (https://github.com/serilog-web/classic)
                         .Enrich.WithHttpRequestUrl()
                         .Enrich.WithHttpRequestType()

                         .Enrich.WithExceptionDetails()

                         .CreateLogger();

            // By defaut we don't want to see all HTTP requests in log file, but you can change this by ajusting this setting
            // Additional information can be found here https://github.com/serilog-web/classic
            // TODO: Change WebApi requests logging level
            SerilogWebClassic.Configure(cfg => cfg
                                        .LogAtLevel(LogEventLevel.Debug)); // All requests will

            config.Services.Replace(typeof(IExceptionLogger), new ExceptionLogger());
        }
Esempio n. 2
0
 protected override void EnableFormDataLoggingAlways(LogEventLevel level)
 {
     SerilogWebClassic.Configure(cfg => cfg
                                 .EnableFormDataLogging(forms => forms
                                                        .AtLevel(level)
                                                        ));
 }
        public void LogPostedFormDataHandlesMultipleValuesPerKey()
        {
            var formData = new NameValueCollection
            {
                { "Foo", "Bar" },
                { "Foo", "Qux" }
            };

            SerilogWebClassic.Configure(cfg => cfg
                                        .EnableFormDataLogging()
                                        );

            TestContext.SimulateForm(formData);

            var formDataProperty = LastEvent.Properties["FormData"] as SequenceValue;

            Assert.NotNull(formDataProperty);
            Assert.Equal(2, formDataProperty.Elements.Count);
            var firstKvp = formDataProperty.Elements.First() as StructureValue;

            Assert.Equal("Foo", firstKvp?.Properties?.FirstOrDefault(p => p.Name == "Name")?.Value?.LiteralValue());
            Assert.Equal("Bar", firstKvp?.Properties?.FirstOrDefault(p => p.Name == "Value")?.Value?.LiteralValue());

            var secondKvp = formDataProperty.Elements.Skip(1).First() as StructureValue;

            Assert.Equal("Foo", secondKvp?.Properties?.FirstOrDefault(p => p.Name == "Name")?.Value?.LiteralValue());
            Assert.Equal("Qux", secondKvp?.Properties?.FirstOrDefault(p => p.Name == "Value")?.Value?.LiteralValue());
        }
        protected void Application_Start()
        {
            // Request logging disabled for this sample. You can have SerilogWeb.Classic log information messages
            // on all HTTP request by removing the following lines:
            SerilogWebClassic.Configure(cfg => cfg
                                        .Disable()
                                        );

            Log.Logger = new LoggerConfiguration()
                         // Write log messages to elmah.io:
                         .WriteTo.ElmahIo(new ElmahIoSinkOptions("API_KEY", new Guid("LOG_ID")))
                         // Use SerilogWeb.Classic to enrich log messages with HTTP contextual information:
                         .Enrich.WithHttpRequestClientHostIP()
                         .Enrich.WithHttpRequestRawUrl()
                         .Enrich.WithHttpRequestType()
                         .Enrich.WithHttpRequestUrl()
                         .Enrich.WithHttpRequestUserAgent()
                         .Enrich.WithUserName(anonymousUsername: null)
                         .CreateLogger();

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Esempio n. 5
0
 protected override void EnableFormDataLoggingOnMatch(Func <HttpContextBase, bool> matchFunction)
 {
     SerilogWebClassic.Configure(cfg => cfg
                                 .EnableFormDataLogging(forms => forms
                                                        .OnMatch(matchFunction)
                                                        ));
 }
        public void LogPostedFormDataHandlesNullKeyWhenFiltered()
        {
            var formData = new NameValueCollection
            {
                { "Foo", "Bar" },
                { "Qux", "Baz" },
                { null, "" }
            };

            SerilogWebClassic.Configure(cfg => cfg
                                        .EnableFormDataLogging(forms => forms
                                                               .FilterKeywords(new List <string>
            {
                "NA"
            }))
                                        );

            TestContext.SimulateForm(formData);

            var formDataProperty = LastEvent.Properties["FormData"];

            Assert.NotNull(formDataProperty);
            var expected = formData.ToSerilogNameValuePropertySequence();

            Assert.Equal(expected.ToString(), formDataProperty.ToString());
        }
Esempio n. 7
0
#pragma warning disable RECS0154 // Parameter is never used
        public static void Configure(HttpConfiguration config)
#pragma warning restore RECS0154 // Parameter is never used
        {
            // Use Seriog for logging
            // More information can be found here https://github.com/serilog/serilog/wiki/Getting-Started
            var basedir = AppDomain.CurrentDomain.BaseDirectory;

            // By default log file is located in 'C:\Users\<username>\AppData\Roaming\Logs' folder and named as the current assembly name
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File(basedir + "/Logs/log-.txt", rollingInterval: RollingInterval.Day)
                         .ReadFrom.AppSettings()

                         // Enrich with SerilogWeb.Classic (https://github.com/serilog-web/classic)
                         .Enrich.WithHttpRequestUrl()
                         .Enrich.WithHttpRequestType()

                         .Enrich.WithExceptionDetails()

                         .CreateLogger();

            // By defaut we don't want to see all HTTP requests in log file, but you can change this by ajusting this setting
            // Additional information can be found here https://github.com/serilog-web/classic
            SerilogWebClassic.Configure(cfg => cfg
                                        .LogAtLevel(LogEventLevel.Debug));

            config.Services.Replace(typeof(IExceptionLogger), new ExceptionLogger());
        }
        public void PasswordFilteringCanBeDisabled()
        {
            SerilogWebClassic.Configure(cfg => cfg
                                        .EnableFormDataLogging(forms => forms
                                                               .AtLevel(LogEventLevel.Information)
                                                               .DisablePasswordFiltering()
                                                               ));

            var formData = new NameValueCollection
            {
                { "password", "Foo" },
                { "PASSWORD", "Bar" },
                { "EndWithPassword", "Qux" },
                { "PasswordPrefix", "Baz" },
                { "Other", "Value" }
            };

            TestContext.SimulateForm(formData);
            var formDataProperty = LastEvent.Properties["FormData"];

            Assert.NotNull(formDataProperty);
            var expectedLoggedData = formData.ToSerilogNameValuePropertySequence();

            Assert.Equal(expectedLoggedData.ToString(), formDataProperty.ToString());
        }
        public void PasswordBlackListCanBeCustomized()
        {
            SerilogWebClassic.Configure(cfg => cfg
                                        .EnableFormDataLogging(forms => forms
                                                               .AtLevel(LogEventLevel.Information)
                                                               .FilterKeywords(new List <string>
            {
                "badword", "forbidden", "restricted"
            })
                                                               ));

            var formData = new NameValueCollection
            {
                { "password", "Foo" },
                { "badword", "Bar" },
                { "VeryBadWord", "Qux" },
                { "forbidden", "Baz" },
                { "ThisIsRestricted", "Value" }
            };
            var expectedLoggedData = new NameValueCollection
            {
                { "password", "Foo" },
                { "badword", "********" },
                { "VeryBadWord", "********" },
                { "forbidden", "********" },
                { "ThisIsRestricted", "********" }
            }.ToSerilogNameValuePropertySequence();

            TestContext.SimulateForm(formData);

            var formDataProperty = LastEvent.Properties["FormData"];

            Assert.NotNull(formDataProperty);
            Assert.Equal(expectedLoggedData.ToString(), formDataProperty.ToString());
        }
Esempio n. 10
0
 protected override void EnableFormDataLoggingOnlyOnError()
 {
     SerilogWebClassic.Configure(cfg => cfg
                                 .EnableFormDataLogging(forms => forms
                                                        .OnlyOnError()
                                                        ));
 }
Esempio n. 11
0
 protected override void EnableFormDataLoggingAlways(LogEventLevel level, IEnumerable <string> customBlackList)
 {
     SerilogWebClassic.Configure(cfg => cfg
                                 .EnableFormDataLogging(forms => forms
                                                        .AtLevel(level)
                                                        .FilterKeywords(customBlackList)
                                                        ));
 }
 public WebRequestLoggingHandlerTests()
 {
     SerilogWebClassic.ResetConfiguration();
     TestContext = new TestContext(new FakeHttpApplication());
     Events      = new List <LogEvent>();
     LevelSwitch = new LoggingLevelSwitch(LogEventLevel.Verbose);
     Log.Logger  = new LoggerConfiguration()
                   .MinimumLevel.ControlledBy(LevelSwitch)
                   .WriteTo.Sink(new DelegatingSink(ev => Events.Add(ev)))
                   .CreateLogger();
 }
Esempio n. 13
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            DisplayConfig.RegisterDisplayModes(DisplayModeProvider.Instance.Modes);
            ModelBinderConfig.RegisterModelBinders(ModelBinders.Binders);

            // Set the application's start date for easy reference
            ApplicationStartDate = DateTime.Now;

            #region Serilog
            var version = this.GetType().Assembly.GetName().Version;

            SerilogWebClassic.Configure(cfg => cfg.LogAtLevel(LogEventLevel.Verbose));
            SerilogWebClassic.Configure(cfg => cfg.EnableFormDataLogging());

            Log.Logger = new LoggerConfiguration()
                         .Enrich.WithMachineName()
                         .Enrich.WithProperty("App", Common.GlobalSettings.Exigo.Api.CompanyKey + ".ReplicatedSite")
                         .Enrich.WithProperty("Version", $"{version.Major}.{version.Minor}.{version.Build}")
                         .WriteTo.Seq("https://log.exigo.com")
                         .CreateLogger();

            Log.Information("Starting up web");
            #endregion

            #region UseDbOrRedisforSessionData
            //First we determine if we are going to use Redis (client must have purchased redis in azure) or SQL in memory caching.
            //If SQL than we fire off operation that will check the sql db to ensure that everything is set up to run in memory caching.
            var sessionCacheProvider = (GlobalSettings.Exigo.UserSession.UseDbSessionCaching)
                ? new SqlInMemoryCacheProvider(GlobalSettings.Exigo.Api.Sql.ConnectionStrings.SqlReporting)
                : new RedisCacheProvider(GlobalSettings.Exigo.Caching.RedisConnectionString) as ICacheProvider;

            CacheConfig.RegisterCache(sessionCacheProvider);
            #endregion

            ResourceSetManager.Start(new ResourceSetUpdaterOptions
            {
                SubscriptionKeys = ConfigurationManager.AppSettings["ResourceSet.SubscriptionKeys"],
                EnvironmentCode  = ConfigurationManager.AppSettings["ResourceSet.EnvironmentCode"],

                LoginName = ConfigurationManager.AppSettings["Api.LoginName"],
                Password  = ConfigurationManager.AppSettings["Api.Password"],
                Company   = ConfigurationManager.AppSettings["Api.CompanyKey"],

                LocalPath        = Server.MapPath("~/App_Data"),
                UpdateClassFiles = HttpContext.Current.IsDebuggingEnabled
            });
        }
Esempio n. 14
0
        public static void ConfigureLogging()
        {
            var configuration = ApplicationConfiguration.Read <UlearnConfiguration>();
            var log           = LoggerSetup.Setup(configuration.HostLog, configuration.GraphiteServiceName, false)
                                .WithProperty("user", () => new HttpContextUserNameProvider().ToString())
                                .WithProperty("address", () => new HttpContextAddressProvider().ToString());

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Sink(new VostokSink(log))
                         .CreateLogger();
            SerilogWebClassic.Configure(cfg => cfg.UseLogger(Log.Logger));
            LogProvider.Configure(log);
        }
        public void ErrorIfMethodFilterKeywordsCalledWithNullCollection()
        {
            var actualException = Assert.Throws <ArgumentNullException>(() =>
                                                                        SerilogWebClassic.Configure(cfg => cfg
                                                                                                    .EnableFormDataLogging(forms => forms
                                                                                                                           .FilterKeywords(null)
                                                                                                                           ))
                                                                        );

            Assert.NotNull(actualException);
            Assert.IsType <ArgumentNullException>(actualException);
            Assert.Equal("Value cannot be null.\r\nParameter name: keywordBlackList", actualException.Message);
        }
        public void DynamicRequestLogLevelEvaluator()
        {
            SerilogWebClassic.Configure(cfg => cfg
                                        .LogAtLevel((context, elapsed) => elapsed.TotalMilliseconds > 3000 ? LogEventLevel.Warning : LogEventLevel.Information)
                                        );

            TestContext.SimulateRequest(sleepDurationMilliseconds: 4000);

            var evt = LastEvent;

            Assert.NotNull(evt);
            Assert.Equal(LogEventLevel.Warning, evt.Level);
        }
        public void RequestLoggingLevel(LogEventLevel requestLoggingLevel)
        {
            SerilogWebClassic.Configure(cfg => cfg
                                        .LogAtLevel(requestLoggingLevel)
                                        );

            TestContext.SimulateRequest();

            var evt = LastEvent;

            Assert.NotNull(evt);
            Assert.Equal(requestLoggingLevel, evt.Level);
        }
        public void LogPostedFormDataAddsNoPropertyWhenThereIsNoFormData()
        {
            SerilogWebClassic.Configure(cfg => cfg
                                        .EnableFormDataLogging()
                                        );

            TestContext.SimulateForm(new NameValueCollection());

            var evt = LastEvent;

            Assert.NotNull(evt);
            Assert.False(evt.Properties.ContainsKey("FormData"), "evt.Properties.ContainsKey('FormData')");
        }
Esempio n. 19
0
        protected void Application_Start(object sender, EventArgs e)
        {
            // ReSharper disable once PossibleNullReferenceException
            SerilogWebClassic.Configure(cfg => cfg
                                        .IgnoreRequestsMatching(ctx => ctx.Request.Url.PathAndQuery.StartsWith("/__browserLink"))
                                        .EnableFormDataLogging(formData => formData
                                                               .AtLevel(LogEventLevel.Debug)
                                                               .OnMatch(ctx => ctx.Response.StatusCode >= 400))
                                        );

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.AppSettings()
                         .CreateLogger();
        }
        public void EnableDisable()
        {
            SerilogWebClassic.Configure(cfg => cfg
                                        .Disable()
                                        );
            TestContext.SimulateRequest();
            Assert.Null(LastEvent);

            SerilogWebClassic.Configure(cfg => cfg
                                        .Enable()
                                        );
            TestContext.SimulateRequest();
            Assert.NotNull(LastEvent);
        }
        public void ErrorIfMethodFilterKeywordsCalledWithCollectionContainingNull()
        {
            string nullKeyword     = null;
            var    actualException = Assert.Throws <ArgumentException>(() =>
                                                                       SerilogWebClassic.Configure(cfg => cfg
                                                                                                   .EnableFormDataLogging(forms => forms
                                                                                                                          .FilterKeywords(new[] { nullKeyword })
                                                                                                                          ))
                                                                       );

            Assert.NotNull(actualException);
            Assert.IsType <ArgumentException>(actualException);
            Assert.Equal("The parameter is invalid. Keywords cannot be null.\r\nParameter name: keywordBlackList", actualException.Message);
        }
        public void DisableFormDataLoggingShouldNotLogPostedFormData()
        {
            var formData = new NameValueCollection
            {
                { "Foo", "Bar" },
                { "Qux", "Baz" }
            };

            SerilogWebClassic.Configure(cfg => cfg
                                        .DisableFormDataLogging()
                                        );

            TestContext.SimulateForm(formData);

            Assert.False(LastEvent.Properties.ContainsKey("FormData"), "LastEvent.Properties.ContainsKey('FormData')");
        }
        public void LogPostedFormDataSetOnMatchMustUseResultOfShouldLogPostedFormData(bool shouldLogFormData)
        {
            var formData = new NameValueCollection
            {
                { "Foo", "Bar" },
                { "Qux", "Baz" }
            };

            SerilogWebClassic.Configure(cfg => cfg
                                        .EnableFormDataLogging(forms => forms
                                                               .OnMatch(ctx => shouldLogFormData)
                                                               ));

            TestContext.SimulateForm(formData);

            Assert.Equal(shouldLogFormData, LastEvent.Properties.ContainsKey("FormData"));
        }
        public void LogPostedFormDataSetToOnlyOnErrorShouldLogPostedFormDataOnErrorStatusCodes(int statusCode, bool shouldLogFormData)
        {
            var formData = new NameValueCollection
            {
                { "Foo", "Bar" },
                { "Qux", "Baz" }
            };

            SerilogWebClassic.Configure(cfg => cfg
                                        .EnableFormDataLogging(forms => forms
                                                               .OnlyOnError()
                                                               ));

            TestContext.SimulateForm(formData, statusCode);

            Assert.Equal(shouldLogFormData, LastEvent.Properties.ContainsKey("FormData"));
        }
Esempio n. 25
0
 protected override void EnableFormDataLoggingAlways(LogEventLevel level, bool filterPasswords)
 {
     if (filterPasswords)
     {
         SerilogWebClassic.Configure(cfg => cfg
                                     .EnableFormDataLogging(forms => forms
                                                            .AtLevel(level)
                                                            .FilterKeywords()
                                                            ));
     }
     else
     {
         SerilogWebClassic.Configure(cfg => cfg
                                     .EnableFormDataLogging(forms => forms
                                                            .AtLevel(level)
                                                            .DisablePasswordFiltering()
                                                            ));
     }
 }
        public void RequestFiltering()
        {
            var ignoredPath   = "/ignoreme/";
            var ignoredMethod = "HEAD";

            SerilogWebClassic.Configure(cfg => cfg
                                        .IgnoreRequestsMatching(ctx =>
                                                                ctx.Request.RawUrl.ToLowerInvariant().Contains(ignoredPath.ToLowerInvariant()) ||
                                                                ctx.Request.HttpMethod == ignoredMethod));

            TestContext.SimulateRequest("GET", $"{ignoredPath}widgets");
            Assert.Null(LastEvent); // should be filtered out

            TestContext.SimulateRequest(ignoredMethod, "/index.html");
            Assert.Null(LastEvent); // should be filtered out

            TestContext.SimulateRequest("GET", "/index.html");
            Assert.NotNull(LastEvent);
        }
        public void LogPostedFormData()
        {
            var formData = new NameValueCollection
            {
                { "Foo", "Bar" },
                { "Qux", "Baz" }
            };

            SerilogWebClassic.Configure(cfg => cfg
                                        .EnableFormDataLogging()
                                        );

            TestContext.SimulateForm(formData);

            var formDataProperty = LastEvent.Properties["FormData"];

            Assert.NotNull(formDataProperty);
            var expected = formData.ToSerilogNameValuePropertySequence();

            Assert.Equal(expected.ToString(), formDataProperty.ToString());
        }
        public void CustomLogger()
        {
            var myLogEvents = new List <LogEvent>();

            using (var myLogger = new LoggerConfiguration()
                                  .WriteTo.Sink(new DelegatingSink(ev => myLogEvents.Add(ev)))
                                  .CreateLogger())
            {
                SerilogWebClassic.Configure(cfg => cfg
                                            .UseLogger(myLogger)
                                            );

                TestContext.SimulateRequest();

                Assert.Null(LastEvent);

                var myEvent = myLogEvents.FirstOrDefault();
                Assert.NotNull(myEvent);
                Assert.Equal($"{typeof(ApplicationLifecycleModule)}",
                             myEvent.Properties[Constants.SourceContextPropertyName].LiteralValue());
            }
        }
Esempio n. 29
0
        public static LoggerConfiguration UseSqlServerConfiguration(this LoggerConfiguration loggerConfiguration)
        {
            var appDataPath = HostingEnvironment.MapPath(@"~\App_Data");

            Serilog.Debugging.SelfLog.Enable(msg =>
            {
                Directory.CreateDirectory(appDataPath ?? throw new InvalidOperationException());
                var path = $@"{appDataPath}\SerilogInternals-{DateTime.Now:yyyy-MM-dd}.txt";
                File.AppendAllText(path, msg + Environment.NewLine);
            });
            SerilogWebClassic.Configure(config => config.Disable());//Install-Package SerilogWeb.Classic

            loggerConfiguration
            .Enrich.WithExceptionDetails() //Install-Package Serilog.Exceptions
            .Enrich.WithHttpRequestClientHostIP()
            .Enrich.WithUserName()
            .Enrich.WithHttpRequestUrl()
            .Enrich.With(new ActionParametersEnricher());

            loggerConfiguration.WriteTo.Sink <MsSqlServerAuditSink>();

            return(loggerConfiguration);
        }
        public void LogPostedFormDataTakesIntoAccountFormDataLoggingLevel()
        {
            var formData = new NameValueCollection
            {
                { "Foo", "Bar" },
                { "Qux", "Baz" }
            };

            SerilogWebClassic.Configure(cfg => cfg
                                        .EnableFormDataLogging(forms => forms
                                                               .AtLevel(LogEventLevel.Verbose)
                                                               ));

            LevelSwitch.MinimumLevel = LogEventLevel.Information;
            TestContext.SimulateForm(formData);

            // logging postedFormData in Verbose only
            // but current level is Information
            Assert.False(LastEvent.Properties.ContainsKey("FormData"), "evt.Properties.ContainsKey('FormData')");

            LevelSwitch.MinimumLevel = LogEventLevel.Debug;
            TestContext.SimulateForm(formData);

            // logging postedFormData in Verbose only
            // but current level is Debug
            Assert.False(LastEvent.Properties.ContainsKey("FormData"), "evt.Properties.ContainsKey('FormData')");

            LevelSwitch.MinimumLevel = LogEventLevel.Verbose;
            TestContext.SimulateForm(formData);

            var formDataProperty = LastEvent.Properties["FormData"];

            Assert.NotNull(formDataProperty);
            var expected = formData.ToSerilogNameValuePropertySequence();

            Assert.Equal(expected.ToString(), formDataProperty.ToString());
        }