Using logger from host in module

I'm implementing a runtime environment for wasm using wasmi and I'd like to implement a way for my logger in my host environment to be used in my wasm modules. My logger is custom:

struct Logger;

impl Log for Logger {
    fn enabled(&self, _: &Metadata) -> bool {
        true
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            printkln!(
                "[{}] [{}] {}",
                record.level(),
                record.target(),
                record.args()
            );
        }
    }

    fn flush(&self) {}
}

The problem, however, is that I can't see how to export a function to wasm modules that takes variatic arguments (yes, I know, the C standard allows this, but I don't think this is necessarily supported in wasm), and I have no idea how the web-sys crate manages it (because console.log in javascript, I think, can take infinite arguments). What's the proper way of doing this? I am running in an embedded environment if that helps.

Implementing the Externals trait in wasmi should allow you to handle this.

I know, but how? I mean, I could make an external function to log strings as bytes, but that seems hacky. Is that the only way?

It does get a bit tricky with wasmi's implementation. Here is some example code that I found which you could start from and implement your logging function. I believe the approach would be to just check for the function's name, accepting any signature, iterate through the supplied parameter values to determine their value types and perform the expected functionality based on those. Hopefully it works out for you!

Sadly that didn't really help. I thought of something like a log_start(), log_byte(), and log_end() export; the first wold prepare the host for logging, the second would store the bytes logged into a temporary buffer, and the third would log the bytes to the console or wherever the logger is going. I also thought of passing pointers to the host but I'm not very good at that and I can't seem to find much info about it using wasmi.

So I'm considering doing my log_start()/log_byte()/log_end() function since I can't seem to find a better way of doing it. How bad is the overhead for calling host-designated functions from modules?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.