[wasm][debugger] Improving logging control for tests (#42175)
authorAnkit Jain <radical@gmail.com>
Thu, 17 Sep 2020 00:58:16 +0000 (20:58 -0400)
committerGitHub <noreply@github.com>
Thu, 17 Sep 2020 00:58:16 +0000 (19:58 -0500)
- replace CWLs with log messages
- Fix use of loggerFactory, and logger to correctly configure them, and
allow being controlled via appsettings.json

- Also, add default settings for proxy also, just an example:

```
     "LogLevel": {
       "Default": "Error",
       "Microsoft": "Warning",
       "Microsoft.WebAssembly.Diagnostics.TestHarnessProxy": "Information",
       "Microsoft.WebAssembly.Diagnostics.DevToolsProxy": "Information",
       "DebuggerTests.Inspector": "Information"
    }
```

Eg. to see trace messages (eg. protocol chat) for the test proxy:
    `"Microsoft.WebAssembly.Diagnostics.TestHarnessProxy": "Trace"`

src/mono/wasm/debugger/DebuggerTestSuite/TestHarnessProxy.cs
src/mono/wasm/debugger/DebuggerTestSuite/TestHarnessStartup.cs
src/mono/wasm/debugger/DebuggerTestSuite/appsettings.json

index 3995dcc..d50a845 100644 (file)
@@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Builder;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
 
 namespace Microsoft.WebAssembly.Diagnostics
 {
@@ -35,6 +36,10 @@ namespace Microsoft.WebAssembly.Diagnostics
                     {
                         config.AddEnvironmentVariables(prefix: "WASM_TESTS_");
                     })
+                    .ConfigureLogging(logging =>
+                    {
+                        logging.AddConsole();
+                    })
                     .ConfigureServices((ctx, services) =>
                     {
                         services.Configure<TestHarnessOptions>(ctx.Configuration);
index 7c5906b..e7be495 100644 (file)
@@ -32,6 +32,9 @@ namespace Microsoft.WebAssembly.Diagnostics
         }
 
         public IConfiguration Configuration { get; set; }
+        public ILogger<TestHarnessProxy> Logger { get; private set; }
+
+        private ILoggerFactory _loggerFactory;
 
         // This method gets called by the runtime. Use this method to add services to the container.
         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
@@ -43,7 +46,7 @@ namespace Microsoft.WebAssembly.Diagnostics
 
         async Task SendNodeVersion(HttpContext context)
         {
-            Console.WriteLine("hello chrome! json/version");
+            Logger.LogTrace("hello chrome! json/version");
             var resp_obj = new JObject();
             resp_obj["Browser"] = "node.js/v9.11.1";
             resp_obj["Protocol-Version"] = "1.1";
@@ -54,7 +57,7 @@ namespace Microsoft.WebAssembly.Diagnostics
 
         async Task SendNodeList(HttpContext context)
         {
-            Console.WriteLine("hello chrome! json/list");
+            Logger.LogTrace("webserver: hello chrome! json/list");
             try
             {
                 var response = new JArray(JObject.FromObject(new
@@ -68,10 +71,10 @@ namespace Microsoft.WebAssembly.Diagnostics
                     webSocketDebuggerUrl = "ws://localhost:9300/91d87807-8a81-4f49-878c-a5604103b0a4"
                 })).ToString();
 
-                Console.WriteLine($"sending: {response}");
+                Logger.LogTrace($"webserver: sending: {response}");
                 await context.Response.WriteAsync(response, new CancellationTokenSource().Token);
             }
-            catch (Exception e) { Console.WriteLine(e); }
+            catch (Exception e) { Logger.LogError(e, "webserver: SendNodeList failed"); }
         }
 
         public async Task LaunchAndServe(ProcessStartInfo psi, HttpContext context, Func<string, Task<string>> extract_conn_url)
@@ -91,7 +94,7 @@ namespace Microsoft.WebAssembly.Diagnostics
                 proc.ErrorDataReceived += (sender, e) =>
                 {
                     var str = e.Data;
-                    Console.WriteLine($"stderr: {str}");
+                    Logger.LogTrace($"browser-stderr: {str}");
 
                     if (tcs.Task.IsCompleted)
                         return;
@@ -105,7 +108,7 @@ namespace Microsoft.WebAssembly.Diagnostics
 
                 proc.OutputDataReceived += (sender, e) =>
                 {
-                    Console.WriteLine($"stdout: {e.Data}");
+                    Logger.LogTrace($"browser-stdout: {e.Data}");
                 };
 
                 proc.BeginErrorReadLine();
@@ -113,27 +116,24 @@ namespace Microsoft.WebAssembly.Diagnostics
 
                 if (await Task.WhenAny(tcs.Task, Task.Delay(5000)) != tcs.Task)
                 {
-                    Console.WriteLine("Didnt get the con string after 5s.");
+                    Logger.LogError("Didnt get the con string after 5s.");
                     throw new Exception("node.js timedout");
                 }
                 var line = await tcs.Task;
                 var con_str = extract_conn_url != null ? await extract_conn_url(line) : line;
 
-                Console.WriteLine($"launching proxy for {con_str}");
-
-                using var loggerFactory = LoggerFactory.Create(
-                    builder => builder.AddConsole().AddFilter(null, LogLevel.Information));
+                Logger.LogInformation($"launching proxy for {con_str}");
 
-                var proxy = new DebuggerProxy(loggerFactory, null);
+                var proxy = new DebuggerProxy(_loggerFactory, null);
                 var browserUri = new Uri(con_str);
                 var ideSocket = await context.WebSockets.AcceptWebSocketAsync();
 
                 await proxy.Run(browserUri, ideSocket);
-                Console.WriteLine("Proxy done");
+                Logger.LogInformation("Proxy done");
             }
             catch (Exception e)
             {
-                Console.WriteLine("got exception {0}", e);
+                Logger.LogError("got exception {0}", e);
             }
             finally
             {
@@ -146,8 +146,11 @@ namespace Microsoft.WebAssembly.Diagnostics
         }
 
         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
-        public void Configure(IApplicationBuilder app, IOptionsMonitor<TestHarnessOptions> optionsAccessor, IWebHostEnvironment env)
+        public void Configure(IApplicationBuilder app, IOptionsMonitor<TestHarnessOptions> optionsAccessor, IWebHostEnvironment env, ILogger<TestHarnessProxy> logger, ILoggerFactory loggerFactory)
         {
+            this.Logger = logger;
+            this._loggerFactory = loggerFactory;
+
             app.UseWebSockets();
             app.UseStaticFiles();
 
@@ -169,7 +172,7 @@ namespace Microsoft.WebAssembly.Diagnostics
             {
                 router.MapGet("launch-chrome-and-connect", async context =>
                 {
-                    Console.WriteLine("New test request");
+                    Logger.LogInformation("New test request");
                     try
                     {
                         var client = new HttpClient();
@@ -195,7 +198,7 @@ namespace Microsoft.WebAssembly.Diagnostics
                                 await Task.Delay(100);
 
                                 var res = await client.GetStringAsync(new Uri(new Uri(str), "/json/list"));
-                                Console.WriteLine("res is {0}", res);
+                                Logger.LogTrace("res is {0}", res);
 
                                 if (!String.IsNullOrEmpty(res))
                                 {
@@ -208,29 +211,29 @@ namespace Microsoft.WebAssembly.Diagnostics
                                 var elapsed = DateTime.Now - start;
                                 if (elapsed.Milliseconds > 5000)
                                 {
-                                    Console.WriteLine($"Unable to get DevTools /json/list response in {elapsed.Seconds} seconds, stopping");
+                                    Logger.LogError($"Unable to get DevTools /json/list response in {elapsed.Seconds} seconds, stopping");
                                     return null;
                                 }
                             }
 
                             var wsURl = obj[0]?["webSocketDebuggerUrl"]?.Value<string>();
-                            Console.WriteLine(">>> {0}", wsURl);
+                            Logger.LogTrace(">>> {0}", wsURl);
 
                             return wsURl;
                         });
                     }
                     catch (Exception ex)
                     {
-                        Console.WriteLine($"launch-chrome-and-connect failed with {ex.ToString()}");
+                        Logger.LogError($"launch-chrome-and-connect failed with {ex.ToString()}");
                     }
                 });
             });
 
             if (options.NodeApp != null)
             {
-                Console.WriteLine($"Doing the nodejs: {options.NodeApp}");
+                Logger.LogTrace($"Doing the nodejs: {options.NodeApp}");
                 var nodeFullPath = Path.GetFullPath(options.NodeApp);
-                Console.WriteLine(nodeFullPath);
+                Logger.LogTrace(nodeFullPath);
                 var psi = new ProcessStartInfo();
 
                 psi.UseShellExecute = false;
index 0cda8d4..4d7c82a 100644 (file)
@@ -3,7 +3,10 @@
     "LogLevel": {
       "Default": "Error",
       "Microsoft": "Warning",
-      "Microsoft.Hosting.Lifetime": "Information"
+      "Microsoft.Hosting.Lifetime": "Information",
+      "Microsoft.WebAssembly.Diagnostics.TestHarnessProxy": "Information",
+      "Microsoft.WebAssembly.Diagnostics.DevToolsProxy": "Information",
+      "DebuggerTests.Inspector": "Information"
     }
   }
 }