Skip to content

Commit

Permalink
v0.2.1
Browse files Browse the repository at this point in the history
增加移除/禁用log有关的功能
  • Loading branch information
SeaLoong committed Sep 22, 2020
1 parent 9056645 commit b138b61
Show file tree
Hide file tree
Showing 9 changed files with 226 additions and 81 deletions.
3 changes: 1 addition & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 6 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
[package]
name = "drcom4scut"
version = "0.2.0"
version = "0.2.1"
authors = ["SeaLoong <984391132@qq.com>"]
edition = "2018"
description = "A 3rd-party Drcom client for SCUT."

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

[dependencies]
rand = "0.7.3"
lazy_static = "1.4.0"
log = "0.4.11"
log4rs = "0.13.0"
chrono = "0.4"
Expand All @@ -26,4 +26,7 @@ crossbeam = "0.7.3"
[profile.release]
opt-level = 'z'
codegen-units = 1
lto = true
lto = true

[features]
nolog = []
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# drcom4scut

> 当前版本 0.2.0
> 当前版本 0.2.1
+ A 3rd DrCOM client for SCUT, written by Rust.
+ A 3rd-party DrCOM client for SCUT, written in Rust.
+ 华南理工大学第三方客户端,使用Rust语言编写。

------------------------------------------------------
Expand Down Expand Up @@ -31,6 +31,7 @@ USAGE:
FLAGS:
--debug Enable debug mode.
-h, --help Prints help information
--nolog !!!注意:如果构建时启用了nolog特性则不会有这项!!! Disable logger, no any output at all, unless PANIC or EXCEPTION of program occurred.
--noudp Disable UDP Process.
-V, --version Prints version information

Expand Down Expand Up @@ -73,7 +74,9 @@ retry:
count: 2 # (可选) 错误重试次数
interval: 5000 # (可选) 数据包重发间隔、错误重试间隔
log:
directory: ./logs # (可选) 日志目录
enable_console: false # (可选) 是否输出日志到控制台
enable_file: false # (可选) 是否输出日志到文件
file_directory: ./logs # (可选) 日志文件目录
level: INFO # (可选) 日志等级
data: # (可选) 以下参数通常不需要填写,填写错误可能会导致不可预计的问题
response_identity:
Expand Down Expand Up @@ -102,6 +105,11 @@ data: # (可选) 以下参数通常不需要填写,填写错误可能会导
cargo build --release
```

+ 如果你想去掉程序的日志(log)功能,可以启用 `nolog` 特性
```bash
cargo build --release --features nolog
```

+ 需要使用 *Nightly* 版本的 Rust 进行编译。

+ 由于使用了 [**libpnet**](https://crates.io/crates/pnet) ,在Windows下需要安装 *WinPcap**pcap* 才能进行编译,详见[**libpnet**](https://crates.io/crates/pnet)。
Expand Down
10 changes: 9 additions & 1 deletion src/eap.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use std::sync::Arc;
use std::time::Duration;

#[cfg(feature = "nolog")]
use crate::{debug, error, info, log, trace, warn};
use bytes::{Buf, BufMut, Bytes, BytesMut};
#[cfg(not(feature = "nolog"))]
use log::{debug, error, info, warn};
use md5::Digest;
use pnet::datalink::MacAddr;
Expand All @@ -10,7 +13,7 @@ use crate::constants;
use crate::device::Device;
use crate::eap::packet::*;
use crate::settings::Settings;
use crate::util::*;
use crate::util::{ip_to_vec, sleep, ChannelData};
use chrono::Local;
use crossbeam::{Receiver, Sender, TryRecvError};
use std::str::FromStr;
Expand Down Expand Up @@ -644,3 +647,8 @@ fn test_md5_calc() {
let r = hex::encode(md5::Md5::digest(data.bytes())).to_lowercase();
assert_eq!(&r, "313a3758ad589ce03dc6af0371c31239");
}

#[test]
fn test_log() {
debug!("debug test");
}
160 changes: 99 additions & 61 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,34 @@
// #![allow(unused_must_use, dead_code, unused_variables, unused_imports)]
#![allow(unused_must_use, dead_code, unused_variables, unused_imports)]
#![feature(ip)]
extern crate lazy_static;
mod constants;
mod device;
mod eap;
mod settings;
mod socket;
mod udp;
#[macro_use]
mod util;

use std::str::FromStr;
use std::sync::Arc;
use std::thread;
use std::time::Duration;

use clap::clap_app;
use log::LevelFilter::{Debug, Info};
use log::{error, info, LevelFilter};

use crate::settings::Settings;
use crate::socket::Socket;
use crate::util::{sleep_at, ChannelData};
use clap::{clap_app, ArgMatches};
#[cfg(not(feature = "nolog"))]
use log::{
debug, error, info, trace, warn, LevelFilter,
LevelFilter::{Debug, Info},
};

mod constants;
mod device;
mod eap;
mod settings;
mod socket;
mod udp;
mod util;

fn init_logger(settings: &Settings) -> log4rs::Handle {
#[cfg(not(feature = "nolog"))]
fn init_logger(settings: &Settings) {
if !settings.debug && settings.nolog {
return;
}
use log4rs::{
append::{
console::ConsoleAppender,
Expand All @@ -38,53 +43,73 @@ fn init_logger(settings: &Settings) -> log4rs::Handle {
config::{Appender, Config, Root},
encode::pattern::PatternEncoder,
};
let directory = &settings.log.directory;
let stdout = ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new(
"{h([{d(%Y-%m-%d %H:%M:%S)}][{l}][{T}] {m}{n})}",
)))
.build();

let logfile = RollingFileAppender::builder()
.encoder(Box::new(PatternEncoder::new(
"[{d(%Y-%m-%d %H:%M:%S)}][{l}][{T}][{M}:{L}] {m}{n}",
)))
.build(
directory.clone() + "/latest.log",
Box::new(CompoundPolicy::new(
Box::new(SizeTrigger::new(1 << 20)),
Box::new(
FixedWindowRoller::builder()
.base(1)
.build(&(directory.clone() + "/log-{}.gz"), 10)
.unwrap(),
),
)),
let stdout = if settings.debug || settings.log.enable_console {
Some(
ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new(
"{h([{d(%Y-%m-%d %H:%M:%S)}][{l}][{T}] {m}{n})}",
)))
.build(),
)
.unwrap();
} else {
None
};
let logfile = if settings.log.enable_file {
let directory = &settings.log.file_directory;
Some(
RollingFileAppender::builder()
.encoder(Box::new(PatternEncoder::new(
"[{d(%Y-%m-%d %H:%M:%S)}][{l}][{T}][{M}:{L}] {m}{n}",
)))
.build(
directory.clone() + "/latest.log",
Box::new(CompoundPolicy::new(
Box::new(SizeTrigger::new(1 << 22)),
Box::new(
FixedWindowRoller::builder()
.base(1)
.build(&(directory.clone() + "/log-{}.gz"), 10)
.expect("Can't build FixedWindowRoller!"),
),
)),
)
.expect("Can't build RollingFileAppender!"),
)
} else {
None
};

if stdout.is_none() && logfile.is_none() {
return;
}

let level = if settings.debug {
Debug
} else {
LevelFilter::from_str(&*settings.log.level).unwrap_or(Info)
};

let config = Config::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout)))
.appender(Appender::builder().build("logfile", Box::new(logfile)))
.build(
Root::builder()
.appender("stdout")
.appender("logfile")
.build(level),
)
.unwrap();
let mut config = Config::builder();
let mut root = Root::builder();
if let Some(stdout) = stdout {
config = config.appender(Appender::builder().build("stdout", Box::new(stdout)));
root = root.appender("stdout");
}
if let Some(logfile) = logfile {
config = config.appender(Appender::builder().build("logfile", Box::new(logfile)));
root = root.appender("logfile");
}

log4rs::init_config(config).unwrap()
let config = config
.build(root.build(level))
.expect("Can't build log config!");

log4rs::init_config(config).expect("Can't init log config!");
}

#[test]
fn test_logger() {
#[cfg(not(feature = "nolog"))]
init_logger(&Settings::default());
trace!("trace test");
debug!("debug test");
Expand All @@ -93,11 +118,12 @@ fn test_logger() {
error!("error test");
}

fn main() {
let matches = clap_app!(drcom4scut =>
(version: "0.1.0")
(author: "SeaLoong")
(about: "A 3rd-party Drcom client for SCUT.")
fn get_matches<'a>() -> ArgMatches<'a> {
use clap::*;
let app = clap_app!((crate_name!()) =>
(version: crate_version!())
(author: crate_authors!())
(about: crate_description!())
(@arg debug: --debug "Enable debug mode.")
(@arg config: -c --config +takes_value "(Optional) Path to config file. Some settings only can be set by config file.")
(@arg mac: -m --mac +takes_value "(Optional) Ethernet Device MAC address.")
Expand All @@ -109,14 +135,24 @@ fn main() {
(@arg hostname: -N --hostname +takes_value "(Optional) Default value is current computer host name.")
(@arg time: -t --time +takes_value "(Optional) Time to reconnect automatically after you are not allowed to access Internet. Default value is 7:00.")
(@arg noudp: --noudp "Disable UDP Process.")
)
.get_matches();
);
#[cfg(not(feature = "nolog"))]
let app = app.arg(clap::Arg::with_name("nolog").long("nolog").help(
"Disable logger, no any output at all, unless PANIC or EXCEPTION of program occurred.",
));
app.get_matches()
}

fn main() {
let matches = get_matches();

let (mut settings, cfg) = settings::Settings::new(&matches).expect("Can't read config file.");
init_logger(&settings);

settings.done(matches, cfg);

#[cfg(not(feature = "nolog"))]
init_logger(&settings);

info!("Start to run...");
let device =
device::get_device(settings.mac, settings.ip).expect("Fail on getting ethernet device!");
Expand All @@ -131,7 +167,7 @@ fn main() {
info!("Host: {}", settings.host);
info!("Hostname: {}", settings.hostname);
info!("Time to wake up: {}", settings.time);
info!("Reconnect Seconds: {}s", settings.reconnect);
info!("Reconnect Interval: {}s", settings.reconnect);
info!(
"Heartbeat timeout of EAP: {}s",
settings.heartbeat.eap_timeout
Expand All @@ -142,7 +178,9 @@ fn main() {
);
info!("Retry Count: {}", settings.retry.count);
info!("Retry Interval: {}ms", settings.retry.interval);
info!("Log Directory: {}", settings.log.directory);
info!("Log to console: {}", settings.log.enable_console);
info!("Log to file: {}", settings.log.enable_file);
info!("Log File Directory: {}", settings.log.file_directory);
info!("Log Level: {}", settings.log.level);

let settings = Arc::new(settings);
Expand Down Expand Up @@ -224,8 +262,8 @@ fn main() {
}
})
.expect("Can't create EAP Process generator thread!");
if settings.no_udp {
info!("UDP Process is disabled.")
if settings.noudp {
info!("UDP Process is disabled.");
} else {
let tx = tx.clone();
loop {
Expand Down
Loading

0 comments on commit b138b61

Please sign in to comment.