pub async fn save_log(
env: &Env,
url: &str,
message: &str,
code: u16,
data: &Value,
severity: Severity,
) -> Result<()>Expand description
Saves a log message to the logging service.
Automatically determines the service name from the SERVICE_NAME environment variable
if not provided. Sends the log to the logger service’s /log endpoint via HTTP.
The timestamp is automatically set to the current time if not provided.
§Arguments
env: The Cloudflare Workers environment for accessing variables.url: The route or URL associated with the log.message: The log message.code: The HTTP status code or error code.data: Optional JSON context data.severity: The severity of the log.
§Returns
Ok(())if the log was sent successfully.Err(anyhow::Error)if the operation failed.
§Environment Variables
SERVICE_NAME: The name of the service (optional, defaults to “unknown”).LOGGER_URL: The base URL of the logger service (required, e.g., “https://logger.example.com”).LOGGER_AUTH: The authentication token for the logger service (required, e.g., “zoK86OpyGp2R+ia2RcC4TyXLKHZQ8Gpu48CQekQCcDM=”).
§Example
use serde_json::json;
use worker::Env;
use logging::{save_log, Severity};
async fn example(env: &Env) -> anyhow::Result<()> {
save_log(
env,
"/api/example",
"Something happened",
200,
&json!({"user_id": 123}),
Severity::Info,
).await?;
Ok(())
}