### Install Go Continuous Profiling Library Source: https://docs.blackfire.io/continuous-profiling-cookbooks/go Use 'go get' to download the Blackfire Continuous Profiling library for Go. ```bash go get github.com/blackfireio/go-continuous-profiling ``` -------------------------------- ### Run the Example Python Application Source: https://docs.blackfire.io/continuous-profiling-cookbooks/python Execute the Python example script to run the continuous profiler. This command will start the profiler, run the application logic, and then stop the profiler. ```bash python example.py ``` -------------------------------- ### Simple Example Application Source: https://docs.blackfire.io/continuous-profiling-cookbooks/nodejs/index A basic example demonstrating how to integrate the Blackfire Node.js tracer with an Express application. ```bash npm install express @blackfireio/node-tracing ``` ```javascript const Blackfire = require('@blackfireio/node-tracing'); const express = require('express') const crypto = require("crypto"); const app = express() const port = 3000 app.get('/', (req, res) => { const salt = crypto.randomBytes(128).toString("base64"); const hash = crypto.pbkdf2Sync("this is my password", salt, 10000, 512, "sha512"); res.send('Hello World!'); }) app.listen(port, () => { console.log(`Example app listening on port ${port}`) Blackfire.start({appName: 'blackfire-example'}); }) ``` ```bash node index.js ``` -------------------------------- ### Example Python Application with Continuous Profiler Source: https://docs.blackfire.io/continuous-profiling-cookbooks/python A simple Python application demonstrating how to initialize the Profiler, start profiling, execute a function, and then stop profiling. Ensure the application name and any custom labels are correctly set. ```python from blackfire_conprof.profiler import Profiler def foo(): import time time.sleep(1.0) profiler = Profiler(application_name="my-python-app", labels={'my-extra-label': 'data'}) profiler.start() foo() profiler.stop() ``` -------------------------------- ### Install Blackfire Package Source: https://docs.blackfire.io/up-and-running/installation?action=install&agent=&language=php&location=local&mode=full&os=debian&version=latest Installs the main Blackfire package, which includes the command-line client and agent. ```bash sudo apt install blackfire ``` -------------------------------- ### Install Blackfire PHP SDK Source: https://docs.blackfire.io/integrations/postman Install the Blackfire PHP SDK using Composer. This is a prerequisite for enabling profiling. ```bash composer require blackfire/php-sdk ``` -------------------------------- ### Install Express and Blackfire Node.js Library Source: https://docs.blackfire.io/continuous-profiling-cookbooks/nodejs/configuration Install both the Express framework and the Blackfire Node.js tracing library. This command is used when setting up a new Express application with continuous profiling. ```bash npm install express @blackfireio/node-tracing ``` -------------------------------- ### Install Blackfire PHP Probe Source: https://docs.blackfire.io/up-and-running/installation?action=install&agent=&language=php&location=local&mode=full&os=debian&version=latest Installs the `blackfire-php` package, which provides the PHP extension for profiling. ```bash sudo apt install blackfire-php ``` -------------------------------- ### Install Python Packages for Blackfire Source: https://docs.blackfire.io/integrations/paas/aws-lambda Install necessary Python packages, including Flask, Blinker, and Blackfire, and then generate a requirements.txt file. ```bash pip install flask pip install blinker pip install blackfire pip freeze > requirements.txt ``` -------------------------------- ### Install Blackfire Probe for Python Source: https://docs.blackfire.io/integrations/paas/heroku Install the Blackfire Probe for Python applications by listing 'blackfire' as a dependency in your requirements.txt file. ```text blackfire django jinja2 gunicorn ``` -------------------------------- ### Profile CLI script with Blackfire using wget Source: https://docs.blackfire.io/php/training-resources/book/08-profiling-all-the-things This example demonstrates profiling a CLI script using `blackfire run` and `wget` to send the `X-Blackfire-Query` header, similar to the `curl` example. ```bash # use wget instead of cURL blackfire run sh -c 'wget --header="X-Blackfire-Query: $BLACKFIRE_QUERY" http://example.com/ > /dev/null' ``` -------------------------------- ### Install Blackfire Agent Source: https://docs.blackfire.io/install/python Installs the APT package for the Blackfire Agent. May prompt for root privileges. ```bash BLACKFIRE_CLIENT_ID="CLIENT_ID" \ BLACKFIRE_CLIENT_TOKEN="CLIENT_TOKEN" \ bash -c "$(curl -L https://installer.blackfire.io/installer.sh)" ``` -------------------------------- ### Start Ruby Profiler with Preload Script Source: https://docs.blackfire.io/continuous-profiling-cookbooks/ruby Alternatively, if you cannot use 'ddprofrb exec', you can start the profiler by requiring 'datadog/profiling/preload' in your application's entry point. ```ruby require 'datadog/profiling/preload' ``` -------------------------------- ### Run the Go Application Source: https://docs.blackfire.io/continuous-profiling-cookbooks/go Execute the Go application using 'go run' to start the continuous profiler. ```bash go run main.go ``` -------------------------------- ### Install Blackfire PHP Probe Source: https://docs.blackfire.io/install/php Installs the Blackfire PHP Probe using the Blackfire CLI. Ensure your web server or PHP-FPM is restarted after installation. ```bash sudo blackfire php:install ``` -------------------------------- ### Install Bref Extra PHP Extensions Source: https://docs.blackfire.io/integrations/paas/aws-lambda Install the Bref extra PHP extensions package, which includes the Blackfire probe, using Composer. ```bash composer require bref/extra-php-extensions ``` -------------------------------- ### Install Blackfire Continuous Profiler Python Library Source: https://docs.blackfire.io/continuous-profiling-cookbooks/python Install the necessary library using pip. This is the first step for integrating continuous profiling into your Python application. ```bash pip install blackfire_conprof ``` -------------------------------- ### Install Blackfire Lando Plugin Source: https://docs.blackfire.io/integrations/paas/lando Move the extracted 'blackfire' folder to the Lando plugins directory. Create the directory if it does not exist. ```bash mv blackfire ~/.lando/plugins/ ``` ```bash mkdir -p ~/.lando/plugins ``` -------------------------------- ### Build Docker Image Source: https://docs.blackfire.io/php/integrations/php-docker Builds the Docker container with the Blackfire probe installed. ```docker docker build -t php-blackfire . ``` -------------------------------- ### Clone and Install phpmd Dependencies Source: https://docs.blackfire.io/php/training-resources/book/08-profiling-all-the-things Set up the phpmd project locally by cloning the repository and installing its Composer dependencies. This is necessary for modifying the source code for advanced profiling. ```bash git clone https://github.com/phpmd/phpmd.git cd phpmd git checkout -b 2.2.1 2.2.1 composer install ``` -------------------------------- ### PHP Class Example Source: https://docs.blackfire.io/testing-cookbooks/metrics A sample PHP class with a method that includes a usleep call, used for demonstrating metrics capture. ```php namespace App\Utils; class Greetings { public function phrase(string $greeting, string $extra): string { usleep(500000); return sprintf('%s %s', $greeting, $extra); } } ``` -------------------------------- ### Example Blackfire Configuration with Assertions Source: https://docs.blackfire.io/php/training-resources/book/11-writing-assertions This is a complete example of a .blackfire.yaml file demonstrating various assertion types for different performance aspects, including wall time, memory, Twig rendering, Symfony events, and memory evolution. ```yaml tests: "All pages are fast": path: "/.*" assertions: - main.wall_time < 75ms - main.memory < 5Mb "Twig displays": path: "/.*" assertions: - metrics.twig.display.count + metrics.twig.render.count < 5 "Symfony events dispatched": path: "/.*" assertions: - metrics.symfony.events.count < 10 "Memory evolution": path: "/.*" assertions: - percent(main.memory) < 10% - diff(main.memory) < 300kb ``` -------------------------------- ### Run Node.js Server Source: https://docs.blackfire.io/continuous-profiling-cookbooks/nodejs/configuration Execute the Node.js application using the `node` command. This starts the server and, if configured, the Blackfire continuous profiler. ```bash node index.js ``` -------------------------------- ### Start Ruby Application with ddprofrb exec Source: https://docs.blackfire.io/continuous-profiling-cookbooks/ruby Use the 'ddprofrb exec' command to start your Ruby application with the continuous profiler enabled. This is the recommended method for most applications, including Rails. ```bash bundle exec ddprofrb exec ruby myrubyapp.rb ``` ```bash # Rails example bundle exec ddprofrb exec bin/rails s ``` -------------------------------- ### Install Blackfire Client in Python Dockerfile Source: https://docs.blackfire.io/python/integrations/python-docker This Dockerfile snippet installs the Blackfire client binary within your Python container at build time. It downloads the appropriate binary for the host's architecture and places it in /usr/bin/blackfire. ```dockerfile FROM python:3.14 RUN pip install --upgrade pip blackfire RUN mkdir -p /tmp/blackfire \ && architecture=$(uname -m) \ && curl -A "Docker" -L https://blackfire.io/api/v1/releases/cli/linux/$architecture | tar zxp -C /tmp/blackfire \ && mv /tmp/blackfire/blackfire /usr/bin/blackfire \ && rm -Rf /tmp/blackfire ``` -------------------------------- ### Install Goutte Source: https://docs.blackfire.io/php/integrations/goutte Add Goutte as a project dependency using Composer. ```bash composer require fabpot/goutte ``` -------------------------------- ### Add Blackfire Client to Dockerfile Source: https://docs.blackfire.io/php/integrations/php-docker Installs the Blackfire client binary into a Docker PHP image for CLI profiling. This setup does not require the blackfire/blackfire image. ```dockerfile FROM php:8.5-fpm RUN mkdir -p /tmp/blackfire \ && architecture=$(uname -m) \ && curl -A "Docker" -L https://blackfire.io/api/v1/releases/cli/linux/$architecture | tar zxp -C /tmp/blackfire \ && mv /tmp/blackfire/blackfire /usr/bin/blackfire \ && rm -Rf /tmp/blackfire ``` -------------------------------- ### Example Node.js Application with Blackfire Source: https://docs.blackfire.io/continuous-profiling-cookbooks/nodejs/configuration A basic Express.js application that integrates the Blackfire continuous profiler. The profiler is started after the server begins listening, ensuring all requests are profiled. ```javascript const Blackfire = require('@blackfireio/node-tracing'); const express = require('express') const crypto = require("crypto"); const app = express() const port = 3000 app.get('/', (req, res) => { const salt = crypto.randomBytes(128).toString("base64"); const hash = crypto.pbkdf2Sync("this is my password", salt, 10000, 512, "sha512"); res.send('Hello World!'); }) app.listen(port, () => { console.log(`Example app listening on port ${port}`) Blackfire.start({appName: 'blackfire-example'}); }) ``` -------------------------------- ### Create SOAP Client Source: https://docs.blackfire.io/php/integrations/sdk Instantiate a SOAP client with specified options. ```php $client = new \SoapClient('some.wsdl', $soapOpts); ``` -------------------------------- ### Initializing the Blackfire Client Source: https://docs.blackfire.io/php/integrations/sdk Instantiate the main entry point of the SDK, the `Blackfire\Client` class. ```APIDOC ## Initialize Blackfire Client ### Description Instantiate the main entry point of the SDK, the `Blackfire\Client` class. ### Method ```php new \Blackfire\Client() ``` ### Usage ```php $blackfire = new \Blackfire\Client(); ``` ``` -------------------------------- ### Get Blackfire Main Probe Instance Source: https://docs.blackfire.io/php/training-resources/book/17-php-sdk Retrieve the main probe instance to control profiling manually. This class is part of the Blackfire C extension and does not require SDK installation. ```php $probe = \BlackfireProbe::getMainInstance(); ``` -------------------------------- ### Initialize Blackfire Client Source: https://docs.blackfire.io/php/integrations/sdk Instantiate the main entry point for the Blackfire PHP SDK. ```php $blackfire = new \Blackfire\Client(); ``` -------------------------------- ### Define Blackfire Scenarios Source: https://docs.blackfire.io/php/training-resources/book/16-performance-automation Scenarios are defined in a .blackfire.yaml file to profile main URLs or API endpoints. This example includes GET and POST requests with specific warmup configurations. ```yaml #!blackfire-player name "Bigfoot Sightings Scenarios" scenario visit url("/") name "Homepage" visit url("/sighting/88") name "Sighting #88" visit url("/sighting/135") name "Sighting #135" visit url("/about") name "About page" visit url("/login") name "Login page" visit url('/login') name 'Failed login attempt' method 'POST' warmup true ``` -------------------------------- ### Configure Job with Blackfire Setup Source: https://docs.blackfire.io/integrations/ci/github-actions Set up Blackfire Agent, CLI tool, and Player within a GitHub Actions job using the `setup-php` action. Ensure Blackfire credentials are provided as environment variables. ```yaml jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup Blackfire via setup-php Action uses: shivammathur/setup-php@v2 with: # PHP Only: Setup PHP extensions, including Blackfire Probe. # It is recommended to disable xdebug. # Not needed for other languages. extensions: blackfire, :xdebug # Setup Blackfire Agent and CLI tool, and Blackfire Player tools: blackfire, blackfire-player env: # Expose your Blackfire credentials stored in secrets # as environment variables. BLACKFIRE_SERVER_ID: ${{ secrets.BLACKFIRE_SERVER_ID }} BLACKFIRE_SERVER_TOKEN: ${{ secrets.BLACKFIRE_SERVER_TOKEN }} BLACKFIRE_CLIENT_ID: ${{ secrets.BLACKFIRE_CLIENT_ID }} BLACKFIRE_CLIENT_TOKEN: ${{ secrets.BLACKFIRE_CLIENT_TOKEN }} # Trigger a profile using Blackfire CLI tool. - name: Profile list-users command env: APP_ENV: prod APP_DEBUG: 0 run: blackfire run php bin/console app:list-users # Other example using Python: #run: blackfire run python my_script.py ``` -------------------------------- ### Install pip for Python Source: https://docs.blackfire.io/install/python Installs the pip package manager for Python. Required before installing the Blackfire Python probe. ```bash sudo apt install python-pip ``` -------------------------------- ### Install Blackfire Python Probe Source: https://docs.blackfire.io/install/python Installs the Blackfire Python package using pip. Ensure the installation directory is in your PATH. ```bash pip install blackfire --user ``` -------------------------------- ### Create a Simple Go Application with Profiler Source: https://docs.blackfire.io/continuous-profiling-cookbooks/go A basic Go application demonstrating the integration of the Blackfire continuous profiler. It includes a CPU-intensive function and starts/stops the profiler. ```go # main.go package main import ( "crypto/md5" "encoding/hex" "io" "time" profiler "github.com/blackfireio/go-continuous-profiling" ) func doSomethingCpuIntensive() { md5Hash := func(s string) string { h := md5.New() io.WriteString(h, s) return hex.EncodeToString(h.Sum(nil)) } for i := 0; i < 1_000_000; i++ { md5Hash("UpsunIsCoolAndSoAreYou") } } func main() { err := profiler.Start( profiler.WithAppName("my-app"), ) if err != nil { panic("Error while starting Profiler") } defer profiler.Stop() for i := 0; i < 15; i++ { doSomethingCpuIntensive() time.Sleep(1 * time.Second) } } ``` -------------------------------- ### Start Continuous Profiler with Options Source: https://docs.blackfire.io/continuous-profiling-cookbooks/go Initiates the continuous profiler probe, collecting and uploading profiling data. Configure CPU duration, profile rates, types, labels, and upload timeouts. ```go profiler.Start( profiler.WithCPUDuration(3 * time.Second), profiler.WithCPUProfileRate(1000), profiler.WithProfileTypes(profiler.CPUProfile, profiler.HeapProfile, profiler.GoroutineProfile), profiler.WithLabels(map[string]string{ "key1": "value1", "key2": "value2", }), profiler.WithUploadTimeout(5 * time.Second), ) deferr profiler.Stop() ``` -------------------------------- ### Initialize Blackfire Client Source: https://docs.blackfire.io/php/integrations/sdk Instantiate the Blackfire client with configuration. The default behavior sends profiles to your personal account. ```php $blackfire = new \Blackfire\Client($config); ``` -------------------------------- ### Visit a URL with GET method Source: https://docs.blackfire.io/builds-cookbooks/player Use `visit` to navigate to a URL. The default HTTP method is GET. ```gherkin scenario visit url('/') method 'POST' ``` -------------------------------- ### Install Blackfire Player using Docker Source: https://docs.blackfire.io/php/training-resources/book/18-player Set up the Blackfire Player command-line tool by creating a Docker alias. This command ensures the tool is available in your current shell session. ```bash alias blackfire-player=docker run --rm -it -e BLACKFIRE_CLIENT_ID -e BLACKFIRE_CLIENT_TOKEN -v "`pwd`:/app" blackfire/player ``` -------------------------------- ### Start Java Application with Profiler Agent Source: https://docs.blackfire.io/continuous-profiling-cookbooks/java Update your Java application's start command to include the dd-java-agent as a Java agent. ```java java \ -javaagent:dd-java-agent.jar \ -jar .jar ``` -------------------------------- ### Run PHPBench Benchmarks Source: https://docs.blackfire.io/php/training-resources/book/19-benchmarking Execute benchmarks using the `phpbench` command-line utility. Specify the benchmark file and desired report format. PHPBench supports various options for configuring iterations, data providers, and setup/teardown tasks. ```bash phpbench run benchmarks/SomeBench.php --report=default ``` -------------------------------- ### Run Distributed Profiling Example Source: https://docs.blackfire.io/academy/profiling/distributed-profiling Execute this command to experience distributed profiling with a sample application. Observe how subprofiles are automatically generated for each downstream call. Note that the first five subprofiles are prioritized, and subsequent ones may be throttled. ```bash blackfire curl -L https://www.book.b7e.io/cascade ``` -------------------------------- ### Install Blackfire Probe in Python Dockerfile Source: https://docs.blackfire.io/python/integrations/python-docker Add this to your Dockerfile to install the Blackfire probe and upgrade pip. This is based on the official Docker Python image. ```dockerfile FROM python:3.14 RUN pip install --upgrade pip blackfire ``` -------------------------------- ### Assertion Example for SQL Query Count Source: https://docs.blackfire.io/academy/testing/assertions This example shows how to assert that the number of SQL queries does not exceed a specified limit. It uses the 'metrics.sql.queries.count' metric. ```text metrics.sql.queries.count <= 10 ``` -------------------------------- ### Initialize Blackfire Probe Source: https://docs.blackfire.io/python/integrations/sdk Call `probe.initialize()` to set up the Blackfire probe. This is a prerequisite for other probe operations. ```python from blackfire import probe probe.initialize() ``` -------------------------------- ### Activate Blackfire on DDEV Project Start Source: https://docs.blackfire.io/integrations/paas/ddev Automatically activate Blackfire every time your DDEV project starts by defining a post-start hook in the `.ddev/config.yml` file. ```yaml # .ddev/config.yml hooks: post-start: - exec-host: 'ddev blackfire' ``` -------------------------------- ### Troubleshoot Remote Installation with Blackfire Doctor Source: https://docs.blackfire.io/up-and-running/doctor Use the `--socket` option with `blackfire doctor` to troubleshoot remote installations. Ensure the Blackfire Agent is not publicly exposed. ```bash blackfire doctor --socket /path/to/blackfire-agent.sock ``` -------------------------------- ### Schedule Consumer Profiling with Cron Source: https://docs.blackfire.io/php/training-resources/book/17-php-sdk This example shows how to schedule regular consumer profiling using a cron job. It sends a SIGUSR1 signal to the consumer process every hour to generate a profile. ```bash # generate a profile every hour 0 * * * * pkill -SIGUSR1 -f consumer.php ``` -------------------------------- ### Install Blackfire Cookbook in Chef Node Run List Source: https://docs.blackfire.io/integrations/chef Include the 'blackfire' recipe in your Chef node's run_list to install the Blackfire cookbook and its associated configurations. ```json { "name":"my_node", "run_list": [ "recipe[blackfire]" ] } ``` -------------------------------- ### Basic Blackfire Player Commands Source: https://docs.blackfire.io/builds-cookbooks/player Demonstrates basic commands for interacting with the Blackfire Player CLI after setting up the alias. ```bash blackfire-player --version ``` ```bash blackfire-player list ``` ```bash blackfire-player run my-scenario.bkf ``` -------------------------------- ### Install Node.js Continuous Profiler Library Source: https://docs.blackfire.io/continuous-profiling-cookbooks/nodejs/configuration Install the Blackfire Continuous Profiler Node.js library using npm. This is the first step to enable continuous profiling in your Node.js application. ```bash npm install @blackfireio/node-tracing ``` -------------------------------- ### Profile a Simple HTTP GET Request Source: https://docs.blackfire.io/profiling-cookbooks/profiling-http-via-cli Use the `blackfire curl` command to profile a basic HTTP GET request. This command accepts the same arguments as the standard `curl` utility. ```bash blackfire curl http://example.com/ ``` -------------------------------- ### Run Blackfire Agent Configuration Wizard Source: https://docs.blackfire.io/up-and-running/configuration/agent Use the interactive wizard to set up your agent credentials and configuration. This command collects and validates your server ID and token against the Blackfire API. ```bash blackfire agent:config ``` -------------------------------- ### PHP Hash Map Argument Example Source: https://docs.blackfire.io/testing-cookbooks/metrics A PHP class demonstrating a method that accepts a hash map (array) as an argument, used for hash map argument capture examples. ```php namespace App\Utils; class Greetings { public function phrase(array $greeting): string { usleep(500000); return sprintf('%s %s', $greeting['greetings'], $greeting['phrase']); } } ``` -------------------------------- ### Create Blackfire Client Configuration in PHP Source: https://docs.blackfire.io/php/integrations/sdk Instantiate the Blackfire ClientConfiguration with explicit credentials and environment. This is an alternative to using the default local configuration. ```php // all arguments are optional $config = new \Blackfire\ClientConfiguration($clientId, $clientToken, $defaultEnv); ``` -------------------------------- ### Example 'when' condition Source: https://docs.blackfire.io/testing-cookbooks/tests Use a 'when' expression to conditionally execute a test if the expression evaluates to true. This example ensures a database connection is only considered active when queries are made. ```yaml tests: 'A database connection should be opened only when queries are made': path: '/.*' when: "metrics.sql.connections.count > 0" assertions: - 'metrics.sql.queries.count > 0' ``` -------------------------------- ### Example .blackfire.yaml Configuration Source: https://docs.blackfire.io/testing-cookbooks/tests Define tests for HTTP requests and CLI commands, specifying assertions for performance metrics like wall time. This configuration runs assertions for all HTTP requests where wall time is less than 100ms and for all CLI commands where wall time is less than 2s. ```yaml tests: "Pages should be fast enough": path: "/.*" # run the assertions for all HTTP requests assertions: - "main.wall_time < 100ms" # wall clock time is less than 100ms "Commands should be fast enough": command: ".*" # run the assertions for all CLI commands assertions: - "main.wall_time < 2s" # wall clock time is less than 2s ``` -------------------------------- ### Create a Basic Blackfire Test Configuration Source: https://docs.blackfire.io/onboarding/testing/first-test This is the initial structure for your first Blackfire test. It defines a test case named 'The homepage should be super fast' and asserts that the main wall time should be less than 20ms. ```yaml tests: "The homepage should be super fast": path: "/" assertions: - "main.wall_time < 20ms" ``` -------------------------------- ### PHPUnit Test Failure Example Source: https://docs.blackfire.io/php/integrations/phpunit This example shows the output when Blackfire assertions fail within a PHPUnit test. It details the failed assertions and provides a link to the profile for further analysis. ```text There was 1 failure: 1) IntegrationTest::testSomething Failed asserting that Blackfire tests pass. 1 tests failures out of 2. failed: 1 write calls - metrics.twig.compile 2 == 0 More information at https://blackfire.io/profiles/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/graph. /.../vendor/blackfire/php-sdk/src/Blackfire/Bridge/PhpUnit/TestConstraint.php:60 /.../vendor/blackfire/php-sdk/src/Blackfire/Client.php:90 /.../Tests/IntegrationTest.php:56 FAILURES! Tests: 1, Assertions: 1, Failures: 1. ```