IC Canister Serve

This package provides helpful methods for serving logs and metrics via the http_request endpoint of smart contracts running in the Internet Computer (also known as canisters).

Usage

This crate builds on top of ic-canister-log and ic-metrics-encoder to make serving metrics and logs easy from a canister's http_request method.

```rust use iccanisterlog::{declarelogbuffer, log}; use iccanisterserve::{servelogs, servemetrics}; use iccdk::api::managementcanister::httprequest::{CanisterHttpRequestArgument, HttpResponse}; use icmetrics_encoder::MetricsEncoder;

// Keep up to 100 last messages. declarelogbuffer!(name = INFO, capacity = 100); declarelogbuffer!(name = ERROR, capacity = 100);

fn encodemetrics(w: &mut MetricsEncoder>) -> std::io::Result<()> { w.encodegauge("examplemetricname", 0 as f64, "Example metric description")?; Ok(()) }

[ic_cdk::query]

fn http_request(request: CanisterHttpRequestArgument) -> HttpResponse { log!(INFO, "This is an INFO log"); log!(ERROR, "This is an ERROR log");

let path = match request.url.find('?') {
    None => &request.url[..],
    Some(index) => &request.url[..index],
};

match path {
    "/metrics" => serve_metrics(encode_metrics),
    "/logs" => serve_logs(request, &INFO, &ERROR),
    _ => HttpResponse {
            status: 404.into(),
            body: "not_found".into(),
            ..Default::default()
        }

} } ```

Example Request

To request the metrics, execute the following curl request:

shell $ curl https://example-canister.raw.ic0.app/metrics

To request all the logs, execute the following curl request:

shell $ curl https://example-canister.raw.ic0.app/logs

To request just the INFO logs, execute the following curl request:

shell $ curl https://example-canister.raw.ic0.app/logs?severity=Info

To request just the ERROR logs, execute the following curl request:

shell $ curl https://example-canister.raw.ic0.app/logs?severity=Error

To request logs before a certain timestamp, execute the following curl request: shell $ curl https://example-canister.raw.ic0.app/logs?time=1683837947035