C# 获取 chrome 的控制台日志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18261338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:43:23  来源:igfitidea点击:

Get chrome's console log

c#javascriptasp.net-mvcselenium

提问by Alon Shmiel

I want to build an automation testing, so I have to know the errors that appear in the console of chrome.

我想建立一个自动化测试,所以我必须知道chrome控制台中出现的错误。

there is an option to get the error lines that appear in the console?

有一个选项可以获取出现在控制台中的错误行吗?

In order to see the console: right click somewhere in the page, click "inspect element" and then go to "console".

为了看到控制台:右键单击页面中的某处,单击“检查元素”,然后转到“控制台”。

采纳答案by JacekM

I don't know C# but here's Java code that does the job, I hope you can translate it to C#

我不懂 C# 但这里有 Java 代码,我希望你能把它翻译成 C#

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ChromeConsoleLogging {
    private WebDriver driver;


    @BeforeMethod
    public void setUp() {
        System.setProperty("webdriver.chrome.driver", "c:\path\to\chromedriver.exe");        
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.ALL);
        caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
        driver = new ChromeDriver(caps);
    }

    @AfterMethod
    public void tearDown() {
        driver.quit();
    }

    public void analyzeLog() {
        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
        for (LogEntry entry : logEntries) {
            System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
            //do something useful with the data
        }
    }

    @Test
    public void testMethod() {
        driver.get("http://mypage.com");
        //do something on page
        analyzeLog();
    }
}

Pay attention to setUp method in above code. We use LoggingPreferences object to enable logging. There are a few types of logs, but if you want to track console errors then LogType.BROWSER is the one that you should use. Then we pass that object to DesiredCapabilities and further to ChromeDriver constructor and voila - we have an instance of ChromeDriver with logging enabled.

注意上面代码中的setUp方法。我们使用 LoggingPreferences 对象来启用日志记录。有几种类型的日志,但如果您想跟踪控制台错误,那么 LogType.BROWSER 是您应该使用的一种。然后我们将该对象传递给 DesiredCapabilities 并进一步传递给 ChromeDriver 构造函数,瞧——我们有一个启用了日志记录的 ChromeDriver 实例。

After performing some actions on page we call analyzeLog() method. Here we simply extract the log and iterate through its entries. Here you can put assertions or do any other reporting you want.

在页面上执行一些操作后,我们调用analyzeLog() 方法。在这里,我们只是提取日志并遍历其条目。您可以在此处放置断言或进行任何其他您想要的报告。

My inspiration was this code by Michael Klepikovthat explains how to extract performance logs from ChromeDriver.

我的灵感来自 Michael Klepikov 的这段代码,它解释了如何从 ChromeDriver 中提取性能日志。

回答by Shouvik Roy

As per issue 6832logging is not implemented yet for C# bindings. So there might not be an easy way to get this working as of now.

根据问题 6832尚未为 C# 绑定实现日志记录。因此,到目前为止,可能没有一种简单的方法可以使此工作正常进行。

回答by Agent Shoulder

You can get logs this way:

您可以通过以下方式获取日志:

Driver().Manage().Logs.GetLog();

By specifying what log you are interested in you can get the browser log, that is:

通过指定你感兴趣的日志可以得到浏览器日志,即:

Driver().Manage().Logs.GetLog(LogType.Browser);

Also remember to setup your driver accordingly:

还要记住相应地设置您的驱动程序:

ChromeOptions options = new ChromeOptions();
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
driver = new ChromeDriver("path to driver", options);

回答by Beau Bridges

This is the c# code for logging the brower log from chrome.

这是用于从 chrome 记录浏览器日志的 C# 代码。

private void CheckLogs()
    {
        List<LogEntry> logs = Driver.Manage().Logs.GetLog(LogType.Browser).ToList();
        foreach (LogEntry log in logs)
        {
            Log(log.Message);
        }
    }

here is my code for the actual log:

这是我的实际日志代码:

        public void Log(string value, params object[] values)
    {
        // allow indenting
        if (!String.IsNullOrEmpty(value) && value.Length > 0 && value.Substring(0, 1) != "*")
        {
            value = "      " + value;
        }

        // write the log
        Console.WriteLine(String.Format(value, values));
    }

回答by Sangam Shankar

driver.manage().logs().get("browser")

Gets all logs printed on the console. I was able to get all logs except Violations. Please have a look here Chrome Console logs not printing Violations

获取打印在控制台上的所有日志。我能够获得除 Violations 之外的所有日志。请在此处查看Chrome 控制台日志不打印违规

回答by Raj K Lama

public void Test_DetectMissingFilesToLoadWebpage()
    {
        try
        {
            List<LogEntry> logs = driver.Manage().Logs.GetLog(LogType.Browser).ToList();
            foreach (LogEntry log in logs)
            {
                while(logs.Count > 0)
                {
                    String logInfo = log.ToString();
                    if (log.Message.Contains("Failed to load resource: the server responded with a status of 404 (Not Found)"))
                    {
                        Assert.Fail();
                    }
                    else
                    {
                        Assert.Pass();
                    }
                }
            }
        }
        catch (NoSuchElementException e)
        {
            test.Fail(e.StackTrace);
        }
    }

You could do something like this in C#. It is a complete test case. Then print the console output as String i.e logInfo in your report. For some reason, Log(log.Message) from the solution above this one gave me build errors.So, I replaced it.

你可以在 C# 中做这样的事情。这是一个完整的测试用例。然后在您的报告中将控制台输出打印为字符串,即 logInfo。出于某种原因,上面这个解决方案中的 Log(log.Message) 给了我构建错误。所以,我替换了它。