tracing_proc_macros_ink/
lib.rs#![doc = include_str!("../README.md")]
#![feature(proc_macro_diagnostic)]
extern crate proc_macro;
use std::{io, sync::Once};
use proc_macro::Diagnostic;
use tracing::Level;
use tracing_subscriber::{
fmt::{self, MakeWriter, time},
prelude::*,
};
const fn convert_level(level: Level) -> proc_macro::Level {
match level {
Level::ERROR => proc_macro::Level::Error,
Level::WARN => proc_macro::Level::Warning,
Level::INFO => proc_macro::Level::Note,
Level::DEBUG | Level::TRACE => proc_macro::Level::Help,
}
}
pub struct RustcDiagnosticsWriter {
level: Level,
}
impl RustcDiagnosticsWriter {
const fn new(level: Level) -> Self {
Self { level }
}
}
impl io::Write for RustcDiagnosticsWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let message = String::from_utf8_lossy(buf);
Diagnostic::new(convert_level(self.level), message).emit();
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
pub struct RustcDiagnosticsMakeWriter;
impl<'a> MakeWriter<'a> for RustcDiagnosticsMakeWriter {
type Writer = RustcDiagnosticsWriter;
fn make_writer(&'a self) -> Self::Writer {
RustcDiagnosticsWriter::new(Level::INFO)
}
fn make_writer_for(&'a self, meta: &tracing::Metadata<'_>) -> Self::Writer {
let level = *meta.level();
RustcDiagnosticsWriter::new(level)
}
}
#[cfg(feature = "default-setup")]
pub fn proc_macro_logger_default_setup() {
static SETUP_LOGGER: Once = Once::new();
SETUP_LOGGER.call_once(|| {
const FILE_INFO: bool = true;
tracing_subscriber::registry()
.with(
fmt::Layer::default()
.with_ansi(false)
.with_file(FILE_INFO)
.with_line_number(FILE_INFO)
.with_timer(time::OffsetTime::local_rfc_3339().expect("Could not get local offset!"))
.with_writer(RustcDiagnosticsMakeWriter),
)
.with(tracing_subscriber::EnvFilter::from_default_env())
.init();
});
}