// 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) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // Configure JSNLog var jsnlogConfiguration = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
// 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) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } // Configure JSNLog var jsnlogConfiguration = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
// 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, IApplicationLifetime applicationLifetime) { // Disabilito il livelli di log di default dell'infrastruttura loggerFactory = new LoggerFactory(); // Serilog loggerFactory.AddSerilog(Log.Logger, false); applicationLifetime.ApplicationStopped.Register(Log.CloseAndFlush); // Configure JSNLog JsnlogConfiguration jsnlogConfiguration = new JsnlogConfiguration { corsAllowedOriginsRegex = ".*", serverSideMessageFormat = "Sent: %date, Browser: %userAgent, Message: %message" }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
// 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) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } // Configure JSNLog var jsnlogConfiguration = new JsnlogConfiguration(); // See jsnlog.com/Documentation/Configuration app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseStaticFiles(); // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
// 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) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } var jsnlogConfiguration = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); }
// 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) { loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } // Configure JSNLog // See http://jsnlog.com/Documentation/Configuration/JSNLog var jsnlogConfiguration = new JsnlogConfiguration() { serverSideMessageFormat = "%newline>>>>>> LOG ITEM: %message%newline" }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseDefaultFiles(); // allow index.html to be served as the default file app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public void Configure(IApplicationBuilder app) { if (_hostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseExceptionHandling(); var loggerFactory = app.ApplicationServices.GetService <ILoggerFactory>(); var jslogconf = new JsnlogConfiguration { corsAllowedOriginsRegex = _configuration.GetValue <string>("JSNlogCorsRegex") }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jslogconf); if (_hostingEnvironment.IsDevelopment() || _hostingEnvironment.IsStaging() || _hostingEnvironment.EnvironmentName == "Utv") { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "STICOS COMMON API"); }); } app.UseCors("AllowAll"); if (!_hostingEnvironment.IsDevelopment()) { app.UseAuthentication(); } app.UseMvc(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { //Logging loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); var jsnlogConfiguration = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseStatusCodePages(); } //Startup File var options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(options); if (env.IsDevelopment()) { app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = context => { context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store"; context.Context.Response.Headers["Pragma"] = "no-cache"; context.Context.Response.Headers["Expires"] = "-1"; } }); } else { app.UseStaticFiles(); } //Cors app.UseCors("AllowAll"); //SignalR app.UseSignalR(routes => { routes.MapHub <MarkerHub> ("/markerhub"); }); //Swagger app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Skills API V1"); c.RoutePrefix = string.Empty; }); // Uncomment this line to enable auth // app.UseAuthentication(); app.UseMvcWithDefaultRoute(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, VouchersDBContext dbcontext) { //Logging loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); var jsnlogConfiguration = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseStatusCodePages(); } //Startup File for serving a *.html as default // DefaultFilesOptions options = new DefaultFilesOptions(); // options.DefaultFileNames.Clear(); // options.DefaultFileNames.Add("crud.html"); // app.UseDefaultFiles(options); if (env.IsDevelopment()) { app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = context => { context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store"; context.Context.Response.Headers["Pragma"] = "no-cache"; context.Context.Response.Headers["Expires"] = "-1"; } }); } else { app.UseStaticFiles(); } //Cors app.UseCors("AllowAll"); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Vouchers API V1"); c.RoutePrefix = string.Empty; }); //Auth app.UseAuthentication(); app.UseMvc(); }
/// <summary> /// Processes the incoming request. This method is not depended on the environment and so can be unit tested. /// Note that the incoming request may not be the POST request with log data. /// /// Effect of this method: /// * setting StatusCode on the response parameter /// * adding headers to the response parameter /// * logging contents of log request /// </summary> /// <param name="json"> /// JSON payload in the incoming request /// </param> /// <param name="logRequestBase"> /// * Type of browser that sent the request /// * IP address that sent the address /// * Url that the request was sent to /// * Request Id sent as part of the request /// * Request data to be given to onLogging event handler /// </param> /// <param name="serverSideTimeUtc">Current time in UTC</param> /// <param name="httpMethod">HTTP method of the request</param> /// <param name="origin">Value of the Origin request header</param> /// <param name="response"> /// Empty response object. This method can add headers, etc. /// </param> internal static void ProcessLogRequest(string json, LogRequestBase logRequestBase, DateTime serverSideTimeUtc, string httpMethod, string origin, LogResponse response) { JsnlogConfiguration jsnlogConfiguration = JavascriptLogging.GetJsnlogConfiguration(); ILoggingAdapter logger = JavascriptLogging.GetLogger(); if ((httpMethod != "POST") && (httpMethod != "OPTIONS")) { response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; return; } string corsAllowedOriginsRegex = jsnlogConfiguration.corsAllowedOriginsRegex; bool originIsAllowed = ((!string.IsNullOrEmpty(corsAllowedOriginsRegex)) && (!string.IsNullOrEmpty(origin)) && Regex.IsMatch(origin, corsAllowedOriginsRegex)); if (originIsAllowed) { response.AppendHeader("Access-Control-Allow-Origin", origin); } response.StatusCode = (int)HttpStatusCode.OK; if (httpMethod == "OPTIONS") { // Standard HTTP response (not related to CORS) response.AppendHeader("Allow", "POST"); // Only if the origin is allowed send CORS headers if (originIsAllowed) { response.AppendHeader("Access-Control-Max-Age", Constants.CorsAccessControlMaxAgeInSeconds.ToString()); response.AppendHeader("Access-Control-Allow-Methods", "POST"); response.AppendHeader("Access-Control-Allow-Headers", "jsnlog-requestid, content-type"); } return; } // httpMethod must be POST List <FinalLogData> logDatas = ProcessLogRequestExec(json, logRequestBase, serverSideTimeUtc, jsnlogConfiguration); // --------------------------------- // Pass log data to Common Logging foreach (FinalLogData logData in logDatas) { logger.Log(logData); } }
// 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) { var jsnlogConfiguration = new JsnlogConfiguration { corsAllowedOriginsRegex = ".*", defaultAjaxUrl = "logging", serverSideMessageFormat = "%date | %requestId | %userAgent| %logger | %url | %userHostAddress | %level | %message" }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseMvc(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { //Logging //Logging loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); var jsnlogConfiguration = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); if (env.IsDevelopment()) { loggerFactory.AddConsole(); loggerFactory.AddDebug(); app.UseDeveloperExceptionPage(); app.UseStatusCodePages(); } //Startup File var options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(options); if (env.IsDevelopment()) { app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = context => { context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store"; context.Context.Response.Headers["Pragma"] = "no-cache"; context.Context.Response.Headers["Expires"] = "-1"; } }); } else { app.UseStaticFiles(); } //Cors app.UseCors("AllowAll"); app.UseSignalR(routes => { routes.MapHub <MarkerHub>("/markerhub"); }); app.UseMvcWithDefaultRoute(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, VouchersDBContext dbcontext) { //Logging loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); var jsnlogConfiguration = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); if (env.IsDevelopment()) { loggerFactory.AddConsole(); loggerFactory.AddDebug(); app.UseDeveloperExceptionPage(); app.UseStatusCodePages(); } //Startup File DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("crud.html"); app.UseDefaultFiles(options); if (env.IsDevelopment()) { app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = context => { context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store"; context.Context.Response.Headers["Pragma"] = "no-cache"; context.Context.Response.Headers["Expires"] = "-1"; } }); } else { app.UseStaticFiles(); } //Cors app.UseCors("AllowAll"); //Auth //app.UseAuthentication(); app.UseMvcWithDefaultRoute(); }
// 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) { // Allors var databaseService = app.ApplicationServices.GetRequiredService <IDatabaseService>(); databaseService.Database = new Database( app.ApplicationServices, new Configuration { ObjectFactory = new ObjectFactory(MetaPopulation.Instance, typeof(User)), ConnectionString = this.Configuration.GetConnectionString("DefaultConnection"), CommandTimeout = 600, }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } var jsnlogConfiguration = new JsnlogConfiguration { corsAllowedOriginsRegex = ".*", serverSideMessageFormat = env.IsDevelopment() ? "%requestId | %url | %message" : "%requestId | %url | %userHostAddress | %userAgent | %message", }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.ConfigureExceptionHandler(env, loggerFactory); app.UseResponseCaching(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllers(); }); }
public void SetConfigWithJsnlogInWebConfig() { // Arrange string configXml = @" <jsnlog maxMessages=""5""> </jsnlog> "; XmlElement xe = CommonTestHelpers.ConfigToXe(configXml); JsnlogConfiguration jsnlogConfiguration = new JsnlogConfiguration(); // Act Exception ex = Assert.Throws <ConflictingConfigException>(() => JavascriptLogging.SetJsnlogConfiguration(() => xe, jsnlogConfiguration)); }
public static void EnsureEqualJsnlogConfiguration(JsnlogConfiguration jc1, JsnlogConfiguration jc2) { Assert.Equal(jc1.enabled, jc2.enabled); Assert.Equal(jc1.maxMessages, jc2.maxMessages); Assert.Equal(jc1.defaultAjaxUrl, jc2.defaultAjaxUrl); Assert.Equal(jc1.corsAllowedOriginsRegex, jc2.corsAllowedOriginsRegex); Assert.Equal(jc1.serverSideLogger, jc2.serverSideLogger); Assert.Equal(jc1.serverSideLevel, jc2.serverSideLevel); Assert.Equal(jc1.serverSideMessageFormat, jc2.serverSideMessageFormat); Assert.Equal(jc1.dateFormat, jc2.dateFormat); Assert.Equal(jc1.productionLibraryPath, jc2.productionLibraryPath); EnsureListsEqual(jc1.ajaxAppenders, jc2.ajaxAppenders, EnsureEqualAjaxAppender); EnsureListsEqual(jc1.consoleAppenders, jc2.consoleAppenders, EnsureEqualConsoleAppender); EnsureListsEqual(jc1.loggers, jc2.loggers, EnsureEqualLogger); }
public void SetConfigWithJsnlogInWebConfig() { // Arrange string configXml = @" <jsnlog maxMessages=""5""> </jsnlog> "; XmlElement xe = CommonTestHelpers.ConfigToXe(configXml); JsnlogConfiguration jsnlogConfiguration = new JsnlogConfiguration(); // Act Exception ex = Assert.Throws<ConflictingConfigException>(() => JavascriptLogging.SetJsnlogConfiguration(() => xe, jsnlogConfiguration)); }
public void Configure(IApplicationBuilder app) { if (_hostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseExceptionHandling(); var loggerFactory = app.ApplicationServices.GetService <ILoggerFactory>(); var jslogconf = new JsnlogConfiguration { corsAllowedOriginsRegex = _configuration.GetValue <string>("JSNlogCorsRegex") }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jslogconf); if (_hostingEnvironment.IsDevelopment() || _hostingEnvironment.IsStaging() || _hostingEnvironment.EnvironmentName == "Utv") { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "STICOS NEWS API"); }); } app.UseCors("AllowAll"); if (!_hostingEnvironment.IsDevelopment()) { app.UseAuthentication(); } app.UseMvc(config => { config .Select() .Expand() .Filter() .OrderBy() .MaxTop(100) .Count(); config.MapODataServiceRoute("odata", "odata/{customerId}", GetEdmModel()); config.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public void AppenderNameNull() { // Arrange JsnlogConfiguration jsnlogConfiguration = new JsnlogConfiguration() { ajaxAppenders = new List <AjaxAppender>() }; jsnlogConfiguration.ajaxAppenders.Add(new AjaxAppender() { name = null }); // Act and Assert Exception ex = Assert.Throws <GeneralAppenderException>(() => RunTest(jsnlogConfiguration)); }
// 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) { // Configure the server side logging package Serilog to write to a file. // JSNLog is not aware what server side logging package you use, so you can use any package you like or none at all. // // Note that the default level of .Net Core loggers is Information, so Trace and Debug messages are not logged. loggerFactory.AddFile("Logs/log.txt"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } // Configure JSNLog // Do this before calling UseStaticFiles. // // You can initialize jsnlogConfiguration in code as shown here, or from configuration, such as from an appsettings.json file. // If you use the default JsnlogConfiguration object (without setting any properties), you get the default configuration, which will work fine. // For a description of the properties, see // http://jsnlog.com/Documentation/Configuration/JSNLog // http://jsnlog.com/Documentation/Configuration/JSNLog/AjaxAppender // http://jsnlog.com/Documentation/Configuration/JSNLog/Logger var jsnlogConfiguration = new JsnlogConfiguration() { maxMessages = 50 }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime) { // Disabilito il livelli di log di default dell'infrastruttura loggerFactory = new LoggerFactory(); // Serilog loggerFactory.AddSerilog(Log.Logger, false); applicationLifetime.ApplicationStopped.Register(Log.CloseAndFlush); // Configure JSNLog JsnlogConfiguration jsnlogConfiguration = new JsnlogConfiguration { corsAllowedOriginsRegex = ".*" }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseFileServer(enableDirectoryBrowsing: false); app.UseCors(cors => cors.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); app.UseMvc(); }
// 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) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseStaticFiles(); app.UseRouting(); app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseAuthentication(); app.UseAuthorization(); // loggerFactory.AddProvider(new LoggerFileProvider("c:\\log.txt")); // add file provider // Logger logger = loggerFactory.CreateLogger(); // <-- creates a console logger and a file logger // Configure JSNLog var jsnlogConfiguration = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapHub <ChatHub>("/chatHub"); endpoints.MapHub <AuthChatHub>("/authHub"); endpoints.MapHub <LidarHub>("/lidarHub"); }); }
// 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) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // Configure JSNLog var jsnlogConfiguration = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { //spa.UseReactDevelopmentServer(npmScript: "start"); spa.UseProxyToSpaDevelopmentServer("http://localhost:3000"); } }); }
// 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) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); // Configure JSNLog // See http://jsnlog.com/Documentation/Configuration/JSNLog var jsnlogConfiguration = new JsnlogConfiguration() { // Format "%message" will break logging. serverSideMessageFormat = "JL: %message", }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); }
// 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) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var jsnlogger = new JsnlogConfiguration(); app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogger); app.UseFileServer(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub <InOutHub>("/signal"); }); }
public void SetConfigWithoutJsnlogInWebConfig() { // Arrange JsnlogConfiguration jsnlogConfiguration = new JsnlogConfiguration { maxMessages = 5 }; JavascriptLogging.SetJsnlogConfiguration(() => null, jsnlogConfiguration); // Act JsnlogConfiguration retrievedJsnlogConfiguration = JavascriptLogging.GetJsnlogConfiguration(); // Assert // Retrieved object is expected to be the exact same object that was put in Assert.Equal(jsnlogConfiguration, retrievedJsnlogConfiguration); Assert.Equal(jsnlogConfiguration.maxMessages, retrievedJsnlogConfiguration.maxMessages); }
public void GetConfigFromWebConfig() { // Arrange string configXml = @" <jsnlog maxMessages=""5""> </jsnlog> "; XmlElement xe = CommonTestHelpers.ConfigToXe(configXml); JavascriptLogging.SetJsnlogConfiguration(null); JavascriptLogging.GetJsnlogConfiguration(() => xe); // Act JsnlogConfiguration retrievedJsnlogConfiguration = JavascriptLogging.GetJsnlogConfiguration(); // Assert // Retrieved object is expected to be the exact same object that was put in Assert.Equal((uint)5, retrievedJsnlogConfiguration.maxMessages); }
/// <summary> /// Ensures that the xml will be serialised by JSNLog to the code in csharp. /// Also writes HTML to d:\temp\demos.html with premade html for example tabs. /// /// In that HTML, you may want to apply strikethrough or the "new code" style. /// To do that, use these meta tags: /// /// <![CDATA[ /// (S}...striked through text ...{S)"/> /// (N}...striked through text ...{N)"/> /// ]]> /// </summary> /// <param name="configXml"></param> /// <param name="csharp"></param> public void TestDemo(string configXml, string csharp, string demoId) { // Testing to ensure xml and code are the same XmlElement xe = CommonTestHelpers.ConfigToXe(CodeWithoutMeta(configXml)); var jsnlogConfigurationFromXml = XmlHelpers.DeserialiseXml <JsnlogConfiguration>(xe); JsnlogConfiguration jsnlogConfigurationFromCode = (JsnlogConfiguration)UnitTestHelpers.Eval(CodeWithoutMeta(csharp)); UnitTestHelpers.EnsureEqualJsnlogConfiguration(jsnlogConfigurationFromXml, jsnlogConfigurationFromCode); // Write partial var sb = new StringBuilder(); sb.AppendLine(string.Format("@* GENERATED CODE - by class DemoTests in JSNLog.Tests project. Demo {0}. *@", demoId)); sb.AppendLine(@"<div class=""commontabs""><div data-tab=""Web.config"">"); sb.AppendLine(@""); sb.AppendLine(string.Format(@"<pre>{0}</pre>", CodeToHtml(configXml))); sb.AppendLine(@""); sb.AppendLine(@"</div><div data-tab=""JsnlogConfiguration"">"); sb.AppendLine(@""); sb.AppendLine(string.Format(@"<pre>JavascriptLogging.{0}({1});</pre>", LinkedText("SetJsnlogConfiguration", _setJsnlogConfigurationUrl), CodeToHtml(csharp))); sb.AppendLine(@""); sb.AppendLine(@"</div></div>"); string path = Path.Combine(TestConstants._demosDirectory, string.Format("_{0}.cshtml", demoId)); string content = sb.ToString(); bool fileExists = File.Exists(path); Assert.False(fileExists, string.Format("{0} already exists", path)); System.IO.File.WriteAllText(path, content); }
// 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) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } // Configure JSNLog // Do this before calling UseStaticFiles. // // You can initialize jsnlogConfiguration in code as shown here, or from configuration, such as from an appsettings.json file. // If you use the default JsnlogConfiguration object (without setting any properties), you get the default configuration, which will work fine. // For a description of the properties, see // http://jsnlog.com/Documentation/Configuration/JSNLog // http://jsnlog.com/Documentation/Configuration/JSNLog/AjaxAppender // http://jsnlog.com/Documentation/Configuration/JSNLog/Logger var jsnlogConfiguration = new JsnlogConfiguration() { maxMessages = 50 }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public void AppenderNameDuplicate2() { // Arrange JsnlogConfiguration jsnlogConfiguration = new JsnlogConfiguration() { ajaxAppenders = new List <AjaxAppender>(), consoleAppenders = new List <ConsoleAppender>() }; jsnlogConfiguration.ajaxAppenders.Add(new AjaxAppender() { name = "samename" }); jsnlogConfiguration.consoleAppenders.Add(new ConsoleAppender() { name = "samename" }); // Act and Assert Exception ex = Assert.Throws <GeneralAppenderException>(() => RunTest(jsnlogConfiguration)); }
/// <summary> /// Returns true if a request with the given url is a logging request that should be handled /// by JSNLog. /// /// Note that the user may have set the defaultUrl or an appender url because they want to use /// the standard url /jsnlog.logger for something else. So you don't want to always allow /// /jsnlog.logger. /// /// On the other hand, it is impossible to figure out exactly what urls the user has used, because you /// don't know which loggers are being used in the user's code. /// So you can't only match against the urls specified with the appenders. /// /// So this method assumes that in addition to the appenders that have been configured, /// the default appender is also used. That is, it also passes the defaultUrl set by the user /// (and if that is not set, the defaultDefaultUrl). /// </summary> /// <param name="url"></param> /// <returns></returns> public static bool IsLoggingUrl(string url) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(url); } JsnlogConfiguration jsnlogConfiguration = JavascriptLogging.GetJsnlogConfiguration(); if (jsnlogConfiguration == null) { return(UrlMatchesAppenderUrl(Constants.DefaultDefaultAjaxUrl, url)); } string resolvedDefaultUrl = ResolvedAppenderUrl(Constants.DefaultDefaultAjaxUrl, jsnlogConfiguration.defaultAjaxUrl, null); if (UrlMatchesAppenderUrl(resolvedDefaultUrl, url)) { return(true); } if (jsnlogConfiguration.ajaxAppenders != null) { foreach (AjaxAppender ajaxAppender in jsnlogConfiguration.ajaxAppenders) { string resolvedAppenderUrl = ResolvedAppenderUrl( Constants.DefaultDefaultAjaxUrl, jsnlogConfiguration.defaultAjaxUrl, ajaxAppender.url); if (UrlMatchesAppenderUrl(resolvedAppenderUrl, url)) { return(true); } } } return(false); }
/// <summary> /// Processes a request with logging info. Unit testable. /// /// Returns log info in easily digestable format. /// </summary> /// <param name="json">JSON sent from client by AjaxAppender</param> /// <param name="serverSideTimeUtc">Current time in UTC</param> /// <param name="jsnlogConfiguration">Contains all config info</param> internal static List<FinalLogData> ProcessLogRequestExec(string json, LogRequestBase logRequestBase, DateTime serverSideTimeUtc, JsnlogConfiguration jsnlogConfiguration) { var logDatas = new List<FinalLogData>(); FinalLogData logData = null; try { LogRequestData logRequestData = LogMessageHelpers.DeserializeJson<LogRequestData>(json); foreach (var logItem in logRequestData.lg) { logData = null; // in case ProcessLogItem throws exception logData = ProcessLogItem(logItem, logRequestBase, serverSideTimeUtc, jsnlogConfiguration); if (logData != null) { logDatas.Add(logData); } } } catch (Exception e) { try { string message = string.Format("Exception: {0}, json: {1}, FinalLogData: {{{2}}}, logRequestBase: {{{3}}}", e, json, logData, logRequestBase); var internalErrorFinalLogData = new FinalLogData(null) { FinalMessage = message, FinalLogger = Constants.JSNLogInternalErrorLoggerName, FinalLevel = Level.ERROR }; logDatas.Add(internalErrorFinalLogData); } catch { } } return logDatas; }
private static FinalLogData ProcessLogItem(LogRequestSingleMsg logItem, LogRequestBase logRequestBase, DateTime serverSideTimeUtc, JsnlogConfiguration jsnlogConfiguration) { string serversideLoggerNameOverride = jsnlogConfiguration.serverSideLogger; string messageFormat = jsnlogConfiguration.serverSideMessageFormat; string levelOverride = jsnlogConfiguration.serverSideLevel; string dateFormat = jsnlogConfiguration.dateFormat; try { LevelUtils.ValidateLevel(levelOverride); } catch (Exception e) { throw new PropertyException("levelOverride", e); } // ---------------- string message = logItem.m; string logger = logItem.n; string level = logItem.l; // note that level as sent by the javascript is a number DateTime utcDate = DateTime.UtcNow; string timestampMs = logItem.t; try { double ms = double.Parse(timestampMs); utcDate = DateTime.SpecifyKind((new DateTime(1970, 1, 1)).AddMilliseconds(ms), DateTimeKind.Utc); } catch { } // ---------------- string jsonmessage = ""; if (messageFormat.Contains("%jsonmessage")) { jsonmessage = LogMessageHelpers.EnsureValidJson(message); } // ---------------- var logRequest = new LogRequest(message, logger, level, utcDate, jsonmessage, logRequestBase); var loggingEventArgs = new LoggingEventArgs(logRequest) { Cancel = false, ServerSideMessageFormat = messageFormat }; // ---------------- if (string.IsNullOrWhiteSpace(logger)) { logger = Constants.RootLoggerNameServerSide; } loggingEventArgs.FinalLogger = serversideLoggerNameOverride ?? logger; string consolidatedLevel = levelOverride ?? level; loggingEventArgs.FinalLevel = LevelUtils.ParseLevel(consolidatedLevel).Value; // ---------------- loggingEventArgs.FinalMessage = messageFormat .Replace("%message", message) .Replace("%jsonmessage", jsonmessage) .Replace("%utcDateServer", serverSideTimeUtc.ToString(dateFormat)) .Replace("%utcDate", utcDate.ToString(dateFormat)) .Replace("%dateServer", Utils.UtcToLocalDateTime(serverSideTimeUtc).ToString(dateFormat)) .Replace("%date", Utils.UtcToLocalDateTime(utcDate).ToString(dateFormat)) .Replace("%level", level) .Replace("%newline", System.Environment.NewLine) .Replace("%userAgent", logRequestBase.UserAgent) .Replace("%userHostAddress", logRequestBase.UserHostAddress) .Replace("%requestId", logRequestBase.RequestId ?? "") .Replace("%url", logRequestBase.Url) .Replace("%logger", logger); // ---------------- JavascriptLogging.RaiseLoggingEvent(loggingEventArgs); // If user wrote event handler that decided not to log the message, return null if (loggingEventArgs.Cancel) { return null; } return loggingEventArgs; }