use mlua::{Lua, Table, Value};
fn fields_json(fields: Option<Table>) -> Option<String> {
let fields = Value::Table(fields?);
if crate::utils::check_json_depth(&fields).is_err() {
return Some("\"<unserializable fields>\"".to_string());
}
Some(
serde_json::to_string(&fields)
.unwrap_or_else(|_| "\"<unserializable fields>\"".to_string()),
)
}
pub(crate) fn create_log_table(lua: &Lua) -> mlua::Result<Table> {
let table = lua.create_table()?;
for level in ["debug", "info", "warn", "error"] {
table.set(
level,
lua.create_function(move |_, (msg, fields): (String, Option<Table>)| {
match (level, fields_json(fields)) {
("debug", Some(f)) => tracing::debug!(target: "lua", fields = %f, "{msg}"),
("debug", None) => tracing::debug!(target: "lua", "{msg}"),
("info", Some(f)) => tracing::info!(target: "lua", fields = %f, "{msg}"),
("info", None) => tracing::info!(target: "lua", "{msg}"),
("warn", Some(f)) => tracing::warn!(target: "lua", fields = %f, "{msg}"),
("warn", None) => tracing::warn!(target: "lua", "{msg}"),
("error", Some(f)) => tracing::error!(target: "lua", fields = %f, "{msg}"),
("error", None) => tracing::error!(target: "lua", "{msg}"),
_ => unreachable!("unknown log level"),
}
Ok(())
})?,
)?;
}
Ok(table)
}