diff --git a/Cargo.toml b/Cargo.toml index 25209bd..1d6f24f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,4 @@ msgpack = ["extism-convert/msgpack"] protobuf = ["extism-convert/protobuf"] [workspace] -members = [ - ".", - "derive" -] +members = [".", "derive"] diff --git a/src/lib.rs b/src/lib.rs index f0a878f..cfbb2c0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,9 +3,9 @@ #[cfg(target_arch = "wasm32")] pub use std::arch::wasm32::v128; -mod macros; - pub mod extism; +mod logging; +mod macros; pub mod memory; mod to_memory; @@ -21,8 +21,8 @@ pub mod http; pub use anyhow::Error; pub use extism_convert::*; -pub use extism_convert::{FromBytes, FromBytesOwned, ToBytes}; pub use extism_pdk_derive::{host_fn, plugin_fn, shared_fn}; +pub use logging::*; pub use memory::{ManagedMemory, Memory, MemoryPointer}; pub use to_memory::ToMemory; @@ -40,28 +40,6 @@ pub type FnResult = Result>; /// The return type of a `shared_fn` pub type SharedFnResult = Result; -/// Logging levels -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum LogLevel { - Trace, - Debug, - Info, - Warn, - Error, -} - -impl LogLevel { - pub const fn to_int(self) -> i32 { - match self { - LogLevel::Trace => 0, - LogLevel::Debug => 1, - LogLevel::Info => 2, - LogLevel::Warn => 3, - LogLevel::Error => 4, - } - } -} - /// Re-export of `serde_json` pub use serde_json as json; diff --git a/src/logging.rs b/src/logging.rs new file mode 100644 index 0000000..8fc5267 --- /dev/null +++ b/src/logging.rs @@ -0,0 +1,41 @@ +use crate::{Error, Memory}; +use extism_convert::TracingEvent; + +/// Logging levels +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LogLevel { + Trace, + Debug, + Info, + Warn, + Error, +} + +impl LogLevel { + pub const fn to_int(self) -> i32 { + match self { + LogLevel::Trace => 0, + LogLevel::Debug => 1, + LogLevel::Info => 2, + LogLevel::Warn => 3, + LogLevel::Error => 4, + } + } +} + +/// Log a message string. +pub fn log(level: LogLevel, message: String) -> Result<(), Error> { + let current_level = unsafe { crate::extism::get_log_level() }; + + if level.to_int() >= current_level && current_level != i32::MAX { + let memory = Memory::from_bytes(&message)?; + memory.log(level); + } + + Ok(()) +} + +/// Log a `tracing` event. +pub fn log_event(level: LogLevel, event: TracingEvent) -> Result<(), Error> { + log(level, serde_json::to_string(&event)?) +} diff --git a/src/macros.rs b/src/macros.rs index b511dff..0abdfe3 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -1,12 +1,7 @@ #[macro_export] macro_rules! log { ($lvl:expr, $($arg:tt)+) => {{ - let level = unsafe { $crate::extism::get_log_level() }; - if $lvl.to_int() >= level && level != i32::MAX { - let fmt = format!($($arg)+); - let memory = $crate::Memory::from_bytes(&fmt).unwrap(); - memory.log($lvl) - } + $crate::log($lvl, format!($($arg)+)).unwrap(); }} }