Using observers | rust-crawler | Spatie       

 SPATIE  

rust-crawler
============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Basic-usage  Using observers

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/rust-crawler/v1) 

  Using observers    
- [ Introduction ](https://spatie.be/docs/rust-crawler/v1/introduction)
- [ Installation &amp; setup ](https://spatie.be/docs/rust-crawler/v1/installation-setup)
- [ Support us ](https://spatie.be/docs/rust-crawler/v1/support-us)
- [ Questions and issues ](https://spatie.be/docs/rust-crawler/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/rust-crawler/v1/changelog)
- [ About us ](https://spatie.be/docs/rust-crawler/v1/about-us)

Basic usage
-----------

- [ Your first crawl ](https://spatie.be/docs/rust-crawler/v1/basic-usage/starting-your-first-crawl)
- [ Crawl responses ](https://spatie.be/docs/rust-crawler/v1/basic-usage/handling-crawl-responses)
- [ Using observers ](https://spatie.be/docs/rust-crawler/v1/basic-usage/using-observers)
- [ Collecting URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/collecting-urls)
- [ Filtering URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/filtering-urls)
- [ Testing ](https://spatie.be/docs/rust-crawler/v1/basic-usage/testing)
- [ Tracking progress ](https://spatie.be/docs/rust-crawler/v1/basic-usage/tracking-progress)

Configuring the crawler
-----------------------

- [ Concurrency &amp; throttling ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/crawl-behavior)
- [ Limits ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/setting-crawl-limits)
- [ Extracting resources ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/extracting-resources)
- [ Configuring requests ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/configuring-requests)
- [ Response filtering ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/handling-responses)
- [ Respecting robots.txt ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/respecting-robots-txt)

Advanced usage
--------------

- [ JavaScript rendering ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/rendering-javascript)
- [ Custom link extraction ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/extracting-custom-links)
- [ Custom request handlers ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/custom-request-handlers)
- [ Crawling across requests ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/crawling-across-requests)
- [ Custom crawl queue ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/using-a-custom-crawl-queue)
- [ Graceful shutdown ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/graceful-shutdown)

 Using observers
===============

###  On this page 

1. [ Multiple observers ](#content-multiple-observers)
2. [ Async work ](#content-async-work)

Register `on_event` closures for short synchronous logging or metrics. An observer receives a borrowed `CrawlEvent`, including its progress snapshot.

```
use spatie_crawler::{CrawlEvent, Crawler};

fn configured() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .on_will_crawl(|url| println!("Fetching {}", url.url))
        .on_event(|event| match event {
            CrawlEvent::Page { page, progress } => {
                println!("{}: {} ({} succeeded)", page.url, page.status, progress.succeeded);
            }
            CrawlEvent::Failed { url, error, .. } => eprintln!("{}: {error}", url.url),
            CrawlEvent::Finished { reason, .. } => println!("Finished: {reason:?}"),
            _ => {}
        })
        .build()
}
```

`on_will_crawl` runs once before a URL's first fetch, not before each retry. Request hooks run per attempt; see [configuring requests](../configuring-the-crawler/configuring-requests).

Multiple observers
--------------------------------------------------------------------------------------------------------------

Call `on_event` more than once to register multiple observers. They run in registration order, before the event enters the stream. Stream consumers still receive the same events.

Rust does not require an observer base class. Use a function or capture an owned service in a `move` closure. Closures must be `Send + Sync + 'static`; use `Arc` and suitable synchronization for shared mutable state.

```
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
use spatie_crawler::{CrawlEvent, Crawler};

fn configured() -> spatie_crawler::Result {
    let pages = Arc::new(AtomicUsize::new(0));
    let observed = Arc::clone(&pages);
    let crawler = Crawler::builder("https://example.com")?
        .on_event(move |event| {
            if matches!(event, CrawlEvent::Page { .. }) {
                observed.fetch_add(1, Ordering::Relaxed);
            }
        })
        .on_event(|event| {
            if let CrawlEvent::Finished { reason, .. } = event {
                println!("Finished: {reason:?}");
            }
        })
        .build()?;
    Ok((crawler, pages))
}
```

Async work
--------------------------------------------------------------------------------------

Observers run on the scheduler. Blocking or slow work delays crawling, cancellation and event delivery. Consume the async stream for database writes and file output, or implement `CrawlHandler` when you need to modify a page before completion. See [custom request handlers](../advanced-usage/custom-request-handlers).

Observers do not acknowledge durable output. A completed checkpoint entry may exist without a delivered event after a crash. See [crawling across requests](../advanced-usage/crawling-across-requests).

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
