Skip to content

Commit

Permalink
Merge pull request #29 from baoyachi/issue/21
Browse files Browse the repository at this point in the history
Fix bug
  • Loading branch information
baoyachi authored Aug 20, 2024
2 parents 96624ae + 98e356f commit 2c4d3fe
Show file tree
Hide file tree
Showing 7 changed files with 161 additions and 32 deletions.
16 changes: 16 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
version: 2
updates:
- package-ecosystem: cargo
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
labels:
- "\U0001F4E6 dependencies"
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
labels:
- "\U0001F4E6 dependencies"
32 changes: 26 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,15 +1,27 @@
[package]
name = "simple-log"
version = "1.6.0"
[workspace.package]
version = "1.7.0"
edition = "2021"
authors = ["baoyachi <liaoymxsdl@gmail.com>"]
description = "A simple log. It's really simple use"
edition = "2018"
keywords = ["log", "simple-log", "logger", "log4j", "log4rs"]
readme = "README.md"
categories = ["development-tools::debugging"]
documentation = "https://docs.rs/simple-log"
repository = "https://github.com/baoyachi/simple-log"
license = "MIT AND Apache-2.0"
license = "MIT Or Apache-2.0"

[package]
name = "simple-log"
version.workspace = true
authors.workspace = true
description.workspace = true
edition.workspace = true
keywords.workspace = true
readme.workspace = true
categories.workspace = true
documentation.workspace = true
repository.workspace = true
license.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand All @@ -20,8 +32,16 @@ once_cell = "1.15.0"
serde = { version = "1.0.145", features = ["derive"] }
is_debug = "1.0.1"
convert_case = "0.6.0"
simple-log-derive = { path = "simple-log-derive", optional = true }

[dev-dependencies]
serde_json = "1"
toml = "0.5.7"
serde_yaml = "0.9.13"
serde_yaml = "0.9.13"

[workspace]
members = ["./", "simple-log-derive"]


[features]
target = ["simple-log-derive"]
3 changes: 3 additions & 0 deletions examples/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,8 @@ fn main() -> Result<(), String> {

debug!("test console debug");
info!("test console info");
warn!("test console warn");
error!("test console error");

Ok(())
}
20 changes: 20 additions & 0 deletions simple-log-derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "simple-log-derive"
version.workspace = true
authors.workspace = true
description.workspace = true
edition.workspace = true
keywords.workspace = true
readme.workspace = true
categories.workspace = true
documentation.workspace = true
repository.workspace = true
license.workspace = true

[lib]
proc-macro = true


[dependencies]
syn = "2"
quote = "1"
38 changes: 38 additions & 0 deletions simple-log-derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Ident};

#[proc_macro]
pub fn log_target_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as Ident);

const LOG_LEVELS: [&str; 5] = ["trace", "debug", "info", "warn", "error"];

let mut parts = Vec::new();

for level in LOG_LEVELS.iter() {
let log_target = Ident::new(&format!("{}_{}", level, input), input.span());
let log_level = match *level {
"trace" => quote!($crate::log::Level::Trace),
"debug" => quote!($crate::log::Level::Debug),
"info" => quote!($crate::log::Level::Info),
"warn" => quote!($crate::log::Level::Warn),
"error" => quote!($crate::log::Level::Error),
_ => unreachable!(),
};

let expand = quote! {
#[macro_export]
macro_rules! #log_target {
($($arg:tt)*) => ($crate::log::log!(target: stringify!(#input), #log_level, $($arg),*));
}
};
parts.push(expand);
}

let combined = quote! {
#(#parts)*
};

TokenStream::from(combined)
}
71 changes: 45 additions & 26 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ use serde::{Deserialize, Serialize};
use std::sync::Mutex;

pub use is_debug::{is_debug, is_release};
#[cfg(feature = "target")]
pub use simple_log_derive::*;

pub type SimpleResult<T> = Result<T, String>;

Expand Down Expand Up @@ -247,7 +249,7 @@ pub fn get_log_conf() -> SimpleResult<LogConfig> {

#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct LogConfig {
pub path: String,
pub path: Option<String>,
pub level: String,
pub size: u64,
#[serde(deserialize_with = "deserialize_out_kind", default)]
Expand All @@ -257,8 +259,8 @@ pub struct LogConfig {
}

impl LogConfig {
pub fn get_path(&self) -> &String {
&self.path
pub fn get_path(&self) -> Option<&String> {
self.path.as_ref()
}

pub fn get_level(&self) -> &String {
Expand Down Expand Up @@ -323,11 +325,10 @@ impl LogConfigBuilder {
/// ```
///
pub fn path<S: Into<String>>(mut self, path: S) -> LogConfigBuilder {
self.0.path = path.into();
self.0.path = Some(path.into());
self
}

///
pub fn level<S: Into<String>>(mut self, level: S) -> LogConfigBuilder {
self.0.level = level.into();
self
Expand Down Expand Up @@ -361,7 +362,7 @@ impl LogConfigBuilder {
/// It's optional method.
/// Also support default data_time_format:%Y-%m-%d %H:%M:%S.%f
///
/// Support data_time_format with link:https://docs.rs/chrono/0.4.19/chrono/naive/struct.NaiveDateTime.html#method.parse_from_str
/// Support data_time_format with link:`<https://docs.rs/chrono/0.4.19/chrono/naive/struct.NaiveDateTime.html#method.parse_from_str>`
pub fn time_format<S: Into<String>>(mut self, time_format: S) -> LogConfigBuilder {
self.0.time_format = Some(time_format.into());
self
Expand Down Expand Up @@ -431,7 +432,7 @@ pub fn new(log_config: LogConfig) -> SimpleResult<()> {
/// This method can quick init simple-log with no configuration.
///
/// If your just want use in demo or test project. Your can use this method.
/// The [quick] method not add any params in method. It's so easy.
/// The [quick()] method not add any params in method. It's so easy.
///
/// The [`LogConfig`] filed just used inner default value.
///
Expand All @@ -443,7 +444,7 @@ pub fn new(log_config: LogConfig) -> SimpleResult<()> {
/// roll_count:10 //At the same time, it can save 10 files endwith .gz
///```
///
/// If you don't want use [quick] method.Also can use [new] method.
/// If you don't want use [quick!] method.Also can use [new] method.
///
/// # Examples
///
Expand All @@ -466,7 +467,7 @@ pub fn quick_log_level<S: Into<String>>(level: S, path: Option<S>) -> SimpleResu
let level = level.into();
log_level::validate_log_level(&level)?;
let mut config = LogConfig {
path: path.map(|x| x.into()).unwrap_or_else(|| "".into()),
path: path.map(|x| x.into()),
level,
..Default::default()
};
Expand All @@ -493,7 +494,7 @@ pub fn quick_log_level<S: Into<String>>(level: S, path: Option<S>) -> SimpleResu
/// ```
pub fn console<S: Into<String>>(level: S) -> SimpleResult<()> {
let config = LogConfig {
path: "".to_string(),
path: None,
level: level.into(),
size: 0,
out_kind: vec![OutKind::Console],
Expand Down Expand Up @@ -528,7 +529,7 @@ pub fn console<S: Into<String>>(level: S) -> SimpleResult<()> {
/// ```
pub fn file<S: Into<String>>(path: S, level: S, size: u64, roll_count: u32) -> SimpleResult<()> {
let config = LogConfig {
path: path.into(),
path: Some(path.into()),
level: level.into(),
size,
out_kind: vec![OutKind::File],
Expand All @@ -545,9 +546,11 @@ fn build_config(log: &LogConfig) -> SimpleResult<Config> {
for kind in &log.out_kind {
match kind {
OutKind::File => {
config_builder = config_builder
.appender(Appender::builder().build(SIMPLE_LOG_FILE, file_appender(log)?));
root_builder = root_builder.appender(SIMPLE_LOG_FILE);
if log.path.as_ref().is_some() {
config_builder = config_builder
.appender(Appender::builder().build(SIMPLE_LOG_FILE, file_appender(log)?));
root_builder = root_builder.appender(SIMPLE_LOG_FILE);
}
}
OutKind::Console => {
let console = ConsoleAppender::builder()
Expand All @@ -568,15 +571,17 @@ fn build_config(log: &LogConfig) -> SimpleResult<Config> {

/// check log config,and give default value
fn init_default_log(log: &mut LogConfig) {
if log.path.trim().is_empty() {
let file_name = std::env::vars()
.filter(|(k, _)| k == "CARGO_PKG_NAME")
.map(|(_, v)| v.to_case(Case::Snake))
.collect::<Vec<_>>()
.pop()
.unwrap_or_else(|| "simple_log".to_string());

log.path = format!("./tmp/{}.log", file_name);
if let Some(path) = &log.path {
if path.trim().is_empty() {
let file_name = std::env::vars()
.filter(|(k, _)| k == "CARGO_PKG_NAME")
.map(|(_, v)| v.to_case(Case::Snake))
.collect::<Vec<_>>()
.pop()
.unwrap_or_else(|| "simple_log".to_string());

log.path = Some(format!("./tmp/{}.log", file_name));
}
}

if log.size == 0 {
Expand Down Expand Up @@ -609,14 +614,28 @@ fn encoder(time_format: Option<&String>, color: bool) -> PatternEncoder {
false => "l",
};
let mut pattern = format!("{{d({})}} [{{{}}}] ", time_format, color_level);
pattern += "<{M}:{L}>:{m}{n}";

#[cfg(feature = "target")]
{
pattern += "[{t}] <{f}:{L}>:{m}{n}";
}
#[cfg(not(feature = "target"))]
{
pattern += "<{f}:{L}>:{m}{n}";
}

PatternEncoder::new(pattern.as_str())
}

fn file_appender(log: &LogConfig) -> SimpleResult<Box<RollingFileAppender>> {
// If the log is written to a file, the path parameter is required
let path = log
.path
.as_ref()
.expect("Expected the path to write the log file, but it is empty");
let roll = FixedWindowRoller::builder()
.base(0)
.build(format!("{}.{{}}.gz", log.path).as_str(), log.roll_count)
.build(format!("{}.{{}}.gz", path).as_str(), log.roll_count)
.map_err(|e| e.to_string())?;

let trigger = SizeTrigger::new(log.size * 1024 * 1024);
Expand All @@ -625,7 +644,7 @@ fn file_appender(log: &LogConfig) -> SimpleResult<Box<RollingFileAppender>> {

let logfile = RollingFileAppender::builder()
.encoder(Box::new(encoder(log.time_format.as_ref(), false)))
.build(log.path.clone(), Box::new(policy))
.build(path.clone(), Box::new(policy))
.map_err(|e| e.to_string())?;

Ok(Box::new(logfile))
Expand Down
13 changes: 13 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ macro_rules! trace {
)
}

#[cfg(feature = "target")]
#[macro_export(local_inner_macros)]
macro_rules! log_target {
($($x:expr),+ $(,)?) => {
$(
$crate::log_target_derive!($x);
)+
};
($arg:expr) => {
$crate::log_target_derive!($arg);
};
}

#[macro_export]
macro_rules! quick {
() => {
Expand Down

0 comments on commit 2c4d3fe

Please sign in to comment.