Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make try_log public so that custom loggers can use it #104

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

Boscop
Copy link

@Boscop Boscop commented Jun 4, 2022

My use case that requires this change is:
From my DLL plugin I want to log to a file but also to the host, by sending it strings (one per log record).
I need to log each line separately to the host, but Write doesn't let me know when each record starts/ends.
So I need to log to a String (actually Cursor<Vec<u8>>, then str::from_utf8, then send the String to the host) and I need to be able to call try_log for that.

Copy link
Owner

@Drakulix Drakulix left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In principle I don't mind to do this, but right now try_log has no documentation.

If you could try to add those (and make sure to explain potential use-cases and reasons this function is public) I would gladly merge this!

@Boscop
Copy link
Author

Boscop commented Dec 2, 2022

I'm not sure what kind of doc to add.
In my use case, my DLL logger has to call try_log and then logs to the host via host_log.
(I need to log each line separately to the host, but Write wouldn't let me know when each record starts/ends.)

Like this:

pub struct HostLogger {
	level: LevelFilter,
	config: Config,
}

impl HostLogger {
	pub fn new(log_level: LevelFilter, config: Config) -> Box<HostLogger> {
		Box::new(HostLogger { level: log_level, config })
	}
}

impl Log for HostLogger {
	fn enabled(&self, metadata: &Metadata<'_>) -> bool {
		metadata.level() <= self.level
	}

	fn log(&self, record: &Record<'_>) {
		if self.enabled(record.metadata()) {
			let mut s = Vec::new();
			let _ = try_log(&self.config, record, &mut Cursor::new(&mut s));
			let s = std::str::from_utf8(&s).expect("utf8").trim();
			host_log(s);
		}
	}

	fn flush(&self) {}
}

impl SharedLogger for HostLogger {
	fn level(&self) -> LevelFilter {
		self.level
	}

	fn config(&self) -> Option<&Config> {
		Some(&self.config)
	}

	fn as_log(self: Box<Self>) -> Box<dyn Log> {
		Box::new(*self)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants