Upload test terminal logs to BrowserStack

Qxf2 engineers have used BrowserStack for many years. We added it to our testing framework too. When we check test failures, we use the video from BrowserStack. But seeing the log messages from our framework also helps. Developers find it easier to fix problems when they can see the logs. We noticed that adding this feature made developers more likely to help find and report issues.

In this post, we will show you how to upload your logs to BrowserStack. We noticed there aren’t many guides for this.

Assumption: Your tests must create a log file.


How to upload the test terminal logs to BrowserStack Session:

To upload test terminal logs to BrowserStack, you need to follow the below steps.

  • Get BrowserStack session details
  • Choose the correct BrowserStack Cloud API endpoint
  • Upload the test logs to BrowserStack test session

Get BrowserStack session details:

There are many ways to get the BrowserStack session details, but a robust and easy way to get the session details is via driver. Use the following line of code to get BrowserStack session details and grab the session ID which we need in the upcoming steps.

current_session = driver.execute_script('browserstack_executor: {"action": "getSessionDetails"}')
session_details = json.loads(current_session)
session_id = session_details['hashed_id']

Above line of code runs the provided script to obtain the session details. This method is effective even when running tests in parallel, which is why we incorporate it into our framework to retrieve session details.


Choose the correct BrowserStack Cloud API endpoint:

BrowserStack has different API endpoints for web apps and mobile apps to upload terminal logs. So we need to select the correct BrowserStack Cloud API endpoint based on the test type. Whether your test is a mobile test or a web app/website test?

For Web app automation tests, use the endpoint:

url = https://api-cloud.browserstack.com/automate/sessions/{session_id}/terminallogs

For Mobile app automation tests, use the endpoint:

url = https://api-cloud.browserstack.com/app-automate/sessions/{session_id}/terminallogs

If you select the wrong endpoint, you end up with the session_id does not exist error.


Upload the test logs to the BrowserStack test session:

To upload the test logs to the respective BrowserStack test session, we use the following method. It is important to call this method at the end of the test after closing the browser. To execute the following method, we need the current session_id which you get from the previous step, your test file path and we need to know which test we are running. Look at our method below:

Note: This is highly simplified code to make this post illustrative. We do not use this quality of the code at clients.

import request
 
browserstack_cloud_api_server_url = "https://api-cloud.browserstack.com"
 
def upload_terminal_logs(file_path, session_id, appium_test = False, timeout=30):
    "Upload the terminal log to BrowserStack"
    try:
        # Determine the URL based on the type of test
        if appium_test:
            url = f'{browserstack_cloud_api_server_url}/app-automate/sessions/{session_id}/terminallogs'
        else:
            url = f'{browserstack_cloud_api_server_url}/automate/sessions/{session_id}/terminallogs'
 
        # Open the file using a context manager to ensure it is properly closed
        with open(file_path, 'rb') as file:
            files = {'file': file}
            # Make the POST request to upload the file
            response = requests.post(url, auth=self.auth, files=files, timeout=timeout)
 
        # Check if the request was successful
        if response.status_code == 200:
            print("Log file uploaded to BrowserStack session successfully.")
        else:
            print(f"Failed to upload log file. Status code: {response.status_code}")
            print(response.text)
 
        return response
 
    except FileNotFoundError as e:
        print(f"Error: Log file '{file_path}' not found.")
        return {"error": "Log file not found.", "details": str(e)}
 
    except requests.exceptions.RequestException as e:
        # Handle network-related errors
        print(f"Error: Failed to upload log file to BrowserStack. Network error: {str(e)}")
        return {"error": "Network error during file upload.", "details": str(e)}
 
    except Exception as e:
        # Catch any other unexpected errors
        print(f"An unexpected error occurred: {str(e)}")
        return {"error": "Unexpected error occurred during file upload.", "details": str(e)}

If you provided the correct test log file path, session_id and test type (appium_test = False/True), the above method executes and sends the test logs to BrowserStack without fail. And you notice, the message “Log file uploaded to BrowserStack session successfully.” on terminal logs.

You can verify the test logs uploaded to BrowserStack by navigating to the BrowserStack session. Once you land on the correct BrowserStack session, Click on the “Others” session and then click on the “Terminal Logs” panel. Now you will see logs uploaded to the session. Look at the attached screenshot below.

BrowserStack Terminal Logs
BrowserStack Terminal Logs


Hope our post helps you to learn and upload your tests terminal logs to BrowserStack.


Hire Qxf2 for your testing needs

Want to start your test automation? Qxf2 offers custom services to help teams reduce their test automation backlog. We provide innovative UI test automation and API test automation solutions. Interested? Send us a message.


Leave a Reply

Your email address will not be published. Required fields are marked *