From 8e683d0fdb421e96f3516357a968ef2e74d5862f Mon Sep 17 00:00:00 2001 From: eternal-flame-AD Date: Fri, 15 Nov 2024 00:03:16 -0600 Subject: [PATCH] CF Workers logging Signed-off-by: eternal-flame-AD --- src/cf_utils.rs | 35 ++++++++++++++++++++++++++++ src/lib.rs | 6 +++++ src/post_process/image_processing.rs | 4 ++-- 3 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 src/cf_utils.rs diff --git a/src/cf_utils.rs b/src/cf_utils.rs new file mode 100644 index 0000000..a29e595 --- /dev/null +++ b/src/cf_utils.rs @@ -0,0 +1,35 @@ +use log::Log; + +#[allow(unsafe_code)] +mod bindings { + use wasm_bindgen::prelude::*; + + #[wasm_bindgen] + extern "C" { + #[wasm_bindgen(js_namespace = console)] + pub fn log(s: &str); + } +} + +pub struct CfLogger; + +impl Log for CfLogger { + fn enabled(&self, metadata: &log::Metadata) -> bool { + if metadata + .target() + .starts_with("yumechi_no_kuni_proxy_worker") + { + return metadata.level() <= log::Level::Debug; + } else if metadata.target().starts_with("usvg") || metadata.target().starts_with("resvg") { + return metadata.level() <= log::Level::Error; + } + + metadata.level() <= log::Level::Info + } + + fn log(&self, record: &log::Record) { + bindings::log(&format!("[{}] {}", record.level(), record.args())); + } + + fn flush(&self) {} +} diff --git a/src/lib.rs b/src/lib.rs index 65a8ce1..1e9dcb9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -48,6 +48,10 @@ pub mod config; /// Cross platform timing utilities pub mod timing; +/// Utilities for Cloudflare Workers +#[cfg(feature = "cf-worker")] +mod cf_utils; + const MAX_SIZE: usize = 32 << 20; #[cfg(all(not(feature = "cf-worker"), not(feature = "reqwest")))] @@ -72,6 +76,8 @@ async fn fetch( use sandbox::NoSandbox; use tower_service::Service; + log::set_logger(&cf_utils::CfLogger).ok(); + let config = match Config::load_from_cf_env(env) { Ok(config) => config, Err(e) => { diff --git a/src/post_process/image_processing.rs b/src/post_process/image_processing.rs index 5482911..feaee8f 100644 --- a/src/post_process/image_processing.rs +++ b/src/post_process/image_processing.rs @@ -1,4 +1,4 @@ -use std::{io::Cursor, sync::Arc}; +use std::io::Cursor; use image::{ codecs::{png::PngDecoder, webp::WebPDecoder}, @@ -115,7 +115,7 @@ pub fn postprocess_svg_image( db.load_font_data(font_data); } - Arc::new(db) + std::sync::Arc::new(db) }, ..Default::default() },