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

Target maybe static #477

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ name = "macros"
path = "tests/macros.rs"
harness = true

[[test]]
name = "targets"
path = "tests/targets.rs"
harness = false

[features]
max_level_off = []
max_level_error = []
Expand Down
88 changes: 83 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -892,6 +892,12 @@ impl<'a> Record<'a> {
self.metadata.target()
}

/// The name of the target of the directive.
#[inline]
pub fn target_static(&self) -> Option<&'static str> {
self.metadata.target_static()
}

/// The module path of the message.
#[inline]
pub fn module_path(&self) -> Option<&'a str> {
Expand Down Expand Up @@ -1051,7 +1057,14 @@ impl<'a> RecordBuilder<'a> {
/// Set [`Metadata::target`](struct.Metadata.html#method.target)
#[inline]
pub fn target(&mut self, target: &'a str) -> &mut RecordBuilder<'a> {
self.record.metadata.target = target;
self.record.metadata.target = MaybeStaticStr::Borrowed(target);
self
}

/// Set [`Metadata::target`](struct.Metadata.html#method.target) to a `'static` string
#[inline]
pub fn target_static(&mut self, target: &'static str) -> &mut RecordBuilder<'a> {
self.record.metadata.target = MaybeStaticStr::Static(target);
self
}

Expand Down Expand Up @@ -1146,7 +1159,7 @@ impl<'a> RecordBuilder<'a> {
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Metadata<'a> {
level: Level,
target: &'a str,
target: MaybeStaticStr<'a>,
}

impl<'a> Metadata<'a> {
Expand All @@ -1165,7 +1178,16 @@ impl<'a> Metadata<'a> {
/// The name of the target of the directive.
#[inline]
pub fn target(&self) -> &'a str {
self.target
self.target.get()
}

/// The name of the target of the directive.
#[inline]
pub fn target_static(&self) -> Option<&'static str> {
match self.target {
MaybeStaticStr::Static(s) => Some(s),
_ => None,
}
}
}

Expand Down Expand Up @@ -1202,7 +1224,7 @@ impl<'a> MetadataBuilder<'a> {
MetadataBuilder {
metadata: Metadata {
level: Level::Info,
target: "",
target: MaybeStaticStr::Static(""),
},
}
}
Expand All @@ -1217,7 +1239,14 @@ impl<'a> MetadataBuilder<'a> {
/// Setter for [`target`](struct.Metadata.html#method.target).
#[inline]
pub fn target(&mut self, target: &'a str) -> &mut MetadataBuilder<'a> {
self.metadata.target = target;
self.metadata.target = MaybeStaticStr::Borrowed(target);
self
}

/// Setter for [`target`](struct.Metadata.html#method.target_static) to a `'static` string.
#[inline]
pub fn target_static(&mut self, target: &'static str) -> &mut MetadataBuilder<'a> {
self.metadata.target = MaybeStaticStr::Static(target);
self
}

Expand Down Expand Up @@ -1561,6 +1590,33 @@ pub fn __private_api_log(
);
}

// WARNING: this is not part of the crate's public API and is subject to change at any time
#[doc(hidden)]
#[cfg(not(feature = "kv_unstable"))]
pub fn __private_api_log_target_static(
args: fmt::Arguments,
level: Level,
&(target, module_path, file, line): &(&'static str, &'static str, &'static str, u32),
kvs: Option<&[(&str, &str)]>,
) {
if kvs.is_some() {
panic!(
"key-value support is experimental and must be enabled using the `kv_unstable` feature"
)
}

logger().log(
&Record::builder()
.args(args)
.level(level)
.target_static(target)
.module_path_static(Some(module_path))
.file_static(Some(file))
.line(Some(line))
.build(),
);
}

// WARNING: this is not part of the crate's public API and is subject to change at any time
#[doc(hidden)]
#[cfg(feature = "kv_unstable")]
Expand All @@ -1583,6 +1639,28 @@ pub fn __private_api_log(
);
}

// WARNING: this is not part of the crate's public API and is subject to change at any time
#[doc(hidden)]
#[cfg(feature = "kv_unstable")]
pub fn __private_api_log_target_static(
args: fmt::Arguments,
level: Level,
&(target, module_path, file, line): &(&'static str, &'static str, &'static str, u32),
kvs: Option<&[(&str, &dyn kv::ToValue)]>,
) {
logger().log(
&Record::builder()
.args(args)
.level(level)
.target_static(target)
.module_path_static(Some(module_path))
.file_static(Some(file))
.line(Some(line))
.key_values(&kvs)
.build(),
);
}

// WARNING: this is not part of the crate's public API and is subject to change at any time
#[doc(hidden)]
pub fn __private_api_enabled(level: Level, target: &str) -> bool {
Expand Down
45 changes: 44 additions & 1 deletion src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@
/// ```
#[macro_export(local_inner_macros)]
macro_rules! log {
(target: $target:literal, $lvl:expr, $($key:ident = $value:expr),* ; $fmt:expr, $($arg:tt)+) => ({
let lvl = $lvl;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
$crate::__private_api_log_target_static(
__log_format_args!($fmt, $($arg)+),
lvl,
&($target, __log_module_path!(), __log_file!(), __log_line!()),
Some(&[$((__log_stringify!($key), &$value)),*])
);
}
});
(target: $target:expr, $lvl:expr, $($key:ident = $value:expr),* ; $fmt:expr, $($arg:tt)+) => ({
let lvl = $lvl;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
Expand All @@ -40,6 +51,17 @@ macro_rules! log {
);
}
});
(target: $target:literal, $lvl:expr, $($arg:tt)+) => ({
let lvl = $lvl;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
$crate::__private_api_log_target_static(
__log_format_args!($($arg)+),
lvl,
&($target, __log_module_path!(), __log_file!(), __log_line!()),
None,
);
}
});
(target: $target:expr, $lvl:expr, $($arg:tt)+) => ({
let lvl = $lvl;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
Expand All @@ -51,7 +73,28 @@ macro_rules! log {
);
}
});
($lvl:expr, $($arg:tt)+) => (log!(target: __log_module_path!(), $lvl, $($arg)+))
($lvl:expr, $($key:ident = $value:expr),* ; $fmt:expr, $($arg:tt)+) => ({
let lvl = $lvl;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
$crate::__private_api_log_target_static(
__log_format_args!($($arg)+),
lvl,
&(__log_module_path!(), __log_module_path!(), __log_file!(), __log_line!()),
Some(&[$((__log_stringify!($key), &$value)),*])
);
}
});
($lvl:expr, $($arg:tt)+) => ({
let lvl = $lvl;
if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() {
$crate::__private_api_log_target_static(
__log_format_args!($($arg)+),
lvl,
&(__log_module_path!(), __log_module_path!(), __log_file!(), __log_line!()),
None,
);
}
});
}

/// Logs a message at the error level.
Expand Down
10 changes: 10 additions & 0 deletions tests/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ fn with_args() {
info!("hello {}", "cats",);
}

#[test]
fn with_target() {
info!(target : "static_target", "hello");
info!(target : "static_target", "hello {}", "cats");
info!(target : "static_target", "hello {}", "cats",);
info!(target : format!("{}", "dynamic_target").as_str(), "hello");
info!(target : format!("{}", "dynamic_target").as_str(), "hello {}", "cats");
info!(target : format!("{}", "dynamic_target").as_str(), "hello {}", "cats");
}

#[test]
fn with_args_expr_context() {
match "cats" {
Expand Down
6 changes: 5 additions & 1 deletion tests/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! This crate is intentionally left empty.
//!
//!
//! We have an empty library depending on `log` here so we can run integration tests
//! on older compilers without depending on the unstable `no-dev-deps` flag.

Expand All @@ -16,3 +16,7 @@ mod filters;
#[cfg(test)]
#[path = "../macros.rs"]
mod macros;

#[cfg(test)]
#[path = "../targets.rs"]
mod targets;
59 changes: 59 additions & 0 deletions tests/targets.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#![allow(dead_code, unused_imports)]

#[cfg(not(lib_build))]
#[macro_use]
extern crate log;

use log::{Level, LevelFilter, Log, Metadata, Record};
use std::sync::{Arc, Mutex};

#[cfg(feature = "std")]
use log::set_boxed_logger;

#[cfg(not(feature = "std"))]
fn set_boxed_logger(logger: Box<dyn Log>) -> Result<(), log::SetLoggerError> {
log::set_logger(Box::leak(logger))
}

struct State {
is_target_static: Mutex<Option<bool>>,
}

struct Logger(Arc<State>);

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

fn log(&self, record: &Record) {
*self.0.is_target_static.lock().unwrap() = Some(record.target_static().is_some());
}
fn flush(&self) {}
}

#[cfg_attr(lib_build, test)]
fn main() {
#[cfg(not(any(feature = "max_level_off", feature = "release_max_level_off",)))]
{
let me = Arc::new(State {
is_target_static: Mutex::new(None),
});
let a = me.clone();
set_boxed_logger(Box::new(Logger(me))).unwrap();
log::set_max_level(log::LevelFilter::Error);

let dynamic_target = "dynamic";
error!("");
last(&a, Some(true));
error!(target: "","");
last(&a, Some(true));
error!(target: dynamic_target, "");
last(&a, Some(false));
}
}

fn last(state: &State, expected: Option<bool>) {
let is_static = state.is_target_static.lock().unwrap().take();
assert_eq!(is_static, expected);
}