Skip to content

Commit befc3e3

Browse files
committed
Using existing logger functionality.
Messages will be shown to the console using the Logger functionality. Adding a test that listens to the logger and checks that logs are being sent to console. Fixing an issue when sending the log to a file, as the OnDriverProcessStarted method in the base class was not being invoked.
1 parent 1260f0e commit befc3e3

File tree

3 files changed

+129
-26
lines changed

3 files changed

+129
-26
lines changed

dotnet/src/webdriver/DriverService.cs

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
using System.Net;
2727
using System.Net.Http;
2828
using System.Threading.Tasks;
29+
using OpenQA.Selenium.Internal.Logging;
2930

3031
namespace OpenQA.Selenium;
3132

@@ -36,6 +37,8 @@ public abstract class DriverService : ICommandServer
3637
{
3738
private bool isDisposed;
3839
private Process? driverServiceProcess;
40+
41+
private static readonly ILogger _logger = Log.GetLogger(typeof(DriverService));
3942

4043
/// <summary>
4144
/// Initializes a new instance of the <see cref="DriverService"/> class.
@@ -156,7 +159,7 @@ public int ProcessId
156159
/// to the console. Defaults to <see langword="false"/>, meaning console output from the
157160
/// driver will be suppressed.
158161
/// </summary>
159-
public bool LogToConsole { get; set; }
162+
public bool LogToConsole { get; set; } = false;
160163

161164
/// <summary>
162165
/// Gets the command-line arguments for the driver service.
@@ -250,11 +253,8 @@ public void Start()
250253
this.driverServiceProcess.StartInfo.UseShellExecute = false;
251254
this.driverServiceProcess.StartInfo.CreateNoWindow = this.HideCommandPromptWindow;
252255

253-
if (!this.LogToConsole)
254-
{
255-
this.driverServiceProcess.StartInfo.RedirectStandardOutput = true;
256-
this.driverServiceProcess.StartInfo.RedirectStandardError = true;
257-
}
256+
this.driverServiceProcess.StartInfo.RedirectStandardOutput = this.LogToConsole;
257+
this.driverServiceProcess.StartInfo.RedirectStandardError = this.LogToConsole;
258258

259259
DriverProcessStartingEventArgs eventArgs = new DriverProcessStartingEventArgs(this.driverServiceProcess.StartInfo);
260260
this.OnDriverProcessStarting(eventArgs);
@@ -318,6 +318,16 @@ protected virtual void OnDriverProcessStarted(DriverProcessStartedEventArgs even
318318
throw new ArgumentNullException(nameof(eventArgs), "eventArgs must not be null");
319319
}
320320

321+
if (this.LogToConsole && eventArgs.StandardOutputStreamReader != null)
322+
{
323+
_ = Task.Run(() => ReadStreamAsync(eventArgs.StandardOutputStreamReader, "stdout"));
324+
}
325+
326+
if (this.LogToConsole && eventArgs.StandardErrorStreamReader != null)
327+
{
328+
_ = Task.Run(() => ReadStreamAsync(eventArgs.StandardErrorStreamReader, "stderr"));
329+
}
330+
321331
this.DriverProcessStarted?.Invoke(this, eventArgs);
322332
}
323333

@@ -399,4 +409,37 @@ private bool WaitForServiceInitialization()
399409

400410
return isInitialized;
401411
}
412+
413+
private async Task ReadStreamAsync(StreamReader reader, string streamType)
414+
{
415+
try
416+
{
417+
string? line;
418+
while ((line = await reader.ReadLineAsync()) != null)
419+
{
420+
if (streamType.Equals("stdout", StringComparison.OrdinalIgnoreCase))
421+
{
422+
if (_logger.IsEnabled(LogEventLevel.Info))
423+
{
424+
_logger.Info(line);
425+
}
426+
}
427+
else
428+
{
429+
if (_logger.IsEnabled(LogEventLevel.Error))
430+
{
431+
_logger.Error(line);
432+
}
433+
}
434+
}
435+
}
436+
catch (Exception ex)
437+
{
438+
if (_logger.IsEnabled(LogEventLevel.Error))
439+
{
440+
_logger.Error($"Error reading stream: {ex.Message}");
441+
}
442+
}
443+
}
444+
402445
}

dotnet/src/webdriver/Firefox/FirefoxDriverService.cs

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
using System.IO;
2424
using System.Text;
2525
using System.Threading.Tasks;
26+
using OpenQA.Selenium.Internal.Logging;
2627

2728
namespace OpenQA.Selenium.Firefox;
2829

@@ -32,7 +33,8 @@ namespace OpenQA.Selenium.Firefox;
3233
public sealed class FirefoxDriverService : DriverService
3334
{
3435
private const string DefaultFirefoxDriverServiceFileName = "geckodriver";
35-
36+
private static readonly ILogger _logger = Log.GetLogger(typeof(FirefoxDriverService));
37+
3638
/// <summary>
3739
/// Process management fields for the log writer.
3840
/// </summary>
@@ -210,15 +212,10 @@ protected override void OnDriverProcessStarting(DriverProcessStartingEventArgs e
210212
Directory.CreateDirectory(directory);
211213
}
212214

213-
// Initialize the log writer
214215
logWriter = new StreamWriter(this.LogPath, append: true) { AutoFlush = true };
215216

216-
// LogToConsole and LogPath are mutually exclusive, therefore we redirect log output.
217-
if (this.LogToConsole)
218-
{
219-
eventArgs.DriverServiceProcessStartInfo.RedirectStandardOutput = true;
220-
eventArgs.DriverServiceProcessStartInfo.RedirectStandardError = true;
221-
}
217+
eventArgs.DriverServiceProcessStartInfo.RedirectStandardOutput = true;
218+
eventArgs.DriverServiceProcessStartInfo.RedirectStandardError = true;
222219
}
223220

224221
base.OnDriverProcessStarting(eventArgs);
@@ -233,13 +230,12 @@ protected override void OnDriverProcessStarting(DriverProcessStartingEventArgs e
233230
/// </remarks>
234231
protected override void OnDriverProcessStarted(DriverProcessStartedEventArgs eventArgs)
235232
{
236-
if (logWriter == null) return;
237-
if (eventArgs.StandardOutputStreamReader != null)
233+
if (!string.IsNullOrEmpty(this.LogPath) && eventArgs.StandardOutputStreamReader != null)
238234
{
239235
_ = Task.Run(() => ReadStreamAsync(eventArgs.StandardOutputStreamReader));
240236
}
241237

242-
if (eventArgs.StandardErrorStreamReader != null)
238+
if (!string.IsNullOrEmpty(this.LogPath) && eventArgs.StandardErrorStreamReader != null)
243239
{
244240
_ = Task.Run(() => ReadStreamAsync(eventArgs.StandardErrorStreamReader));
245241
}
@@ -362,8 +358,10 @@ private async Task ReadStreamAsync(StreamReader reader)
362358
}
363359
catch (Exception ex)
364360
{
365-
// Log or handle the exception appropriately
366-
System.Diagnostics.Debug.WriteLine($"Error reading stream: {ex.Message}");
367-
}
361+
if (_logger.IsEnabled(LogEventLevel.Error))
362+
{
363+
_logger.Error($"Error reading stream: {ex.Message}");
364+
}
365+
}
368366
}
369367
}

dotnet/test/firefox/FirefoxDriverServiceTest.cs

Lines changed: 68 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,26 +17,51 @@
1717
// under the License.
1818
// </copyright>
1919

20+
using System;
21+
using System.Collections.Generic;
2022
using NUnit.Framework;
2123
using System.IO;
24+
using OpenQA.Selenium.Internal.Logging;
2225

2326
namespace OpenQA.Selenium.Firefox;
2427

2528
[TestFixture]
26-
public class FirefoxDriverServiceTest : DriverTestFixture
29+
public class FirefoxDriverServiceTest
2730
{
31+
private TestLogHandler testLogHandler;
32+
33+
private void ResetGlobalLog()
34+
{
35+
Log.SetLevel(LogEventLevel.Info);
36+
Log.Handlers.Clear().Handlers.Add(new TextWriterHandler(Console.Error));
37+
}
38+
39+
[SetUp]
40+
public void SetUp()
41+
{
42+
ResetGlobalLog();
43+
44+
testLogHandler = new TestLogHandler();
45+
}
46+
47+
[TearDown]
48+
public void TearDown()
49+
{
50+
ResetGlobalLog();
51+
}
52+
2853
[Test]
2954
public void ShouldRedirectGeckoDriverLogsToFile()
3055
{
3156
FirefoxOptions options = new FirefoxOptions();
3257
string logPath = Path.GetTempFileName();
3358
options.LogLevel = FirefoxDriverLogLevel.Trace;
34-
59+
3560
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();
3661
service.LogPath = logPath;
37-
38-
IWebDriver driver2 = new FirefoxDriver(service, options);
39-
62+
63+
IWebDriver firefoxDriver = new FirefoxDriver(service, options);
64+
4065
try
4166
{
4267
Assert.That(File.Exists(logPath), Is.True);
@@ -45,9 +70,46 @@ public void ShouldRedirectGeckoDriverLogsToFile()
4570
}
4671
finally
4772
{
48-
driver2.Quit();
73+
firefoxDriver.Quit();
4974
File.Delete(logPath);
5075
}
5176
}
77+
78+
[Test]
79+
public void ShouldRedirectGeckoDriverLogsToConsole()
80+
{
81+
Log.SetLevel(LogEventLevel.Info).Handlers.Add(testLogHandler);
82+
FirefoxOptions options = new FirefoxOptions();
83+
options.LogLevel = FirefoxDriverLogLevel.Info;
84+
85+
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();
86+
service.LogToConsole = true;
87+
88+
IWebDriver firefoxDriver = new FirefoxDriver(service, options);
89+
90+
try
91+
{
92+
Assert.That(testLogHandler.Events, Has.Count.AtLeast(1));
93+
Assert.That(testLogHandler.Events[0].Message, Does.Contain("geckodriver"));
94+
}
95+
finally
96+
{
97+
firefoxDriver.Quit();
98+
}
99+
}
100+
}
101+
102+
class TestLogHandler : ILogHandler
103+
{
104+
public ILogHandler Clone()
105+
{
106+
return this;
107+
}
108+
109+
public void Handle(LogEvent logEvent)
110+
{
111+
Events.Add(logEvent);
112+
}
52113

114+
public IList<LogEvent> Events { get; internal set; } = new List<LogEvent>();
53115
}

0 commit comments

Comments
 (0)