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

add slog #15

Merged
merged 1 commit into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v2
with:
token: ${{ secrets.GITHUB_TOKEN }}

- name: Set up Rust
uses: actions-rs/toolchain@v1
Expand All @@ -26,6 +28,9 @@ jobs:

- name: Check Linting
run: cargo clippy -- -D warnings

- name: Unit test
run: cargo test

- name: Build project
run: cargo build
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ bincode = "1.3.1"
serde = { version = "1.0", features = ["derive"] }
hex = "0.4"
sha2 = "0.10.8"
slog = "2.7.0"
slog-term = "2.9.1"
chrono = "0.4"

[[example]]
name = "simple_run"
Expand Down
10 changes: 7 additions & 3 deletions examples/simple_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

// make this file executable with `chmod +x examples/simple_run.rs`

use raft_rs::log::get_logger;
use slog::{error, info};
use std::collections::HashMap;
use std::thread;
use tokio::runtime::Runtime;
Expand Down Expand Up @@ -60,8 +62,10 @@ async fn main() {
}

async fn client_request(client_id: u32, data: u32) {
let log = get_logger();

let server_address = "127.0.0.1"; // Assuming server 1 is the leader
let network_manager = TCPManager::new(server_address.to_string(), 5001);
let network_manager = TCPManager::new(server_address.to_string(), 5001, log.clone());

let request_data = vec![
client_id.to_be_bytes().to_vec(),
Expand All @@ -75,12 +79,12 @@ async fn client_request(client_id: u32, data: u32) {
.send(server_address, "5001", &request_data)
.await
{
eprintln!("Failed to send client request: {}", e);
error!(log, "Failed to send client request: {}", e);
}

// sleep for a while to allow the server to process the request
tokio::time::sleep(Duration::from_secs(5)).await;

let response = network_manager.receive().await.unwrap();
println!("Received response: {:?}", response);
info!(log, "Received response: {:?}", response);
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod log;
pub mod network;
pub mod server;
pub mod storage;
Expand Down
31 changes: 31 additions & 0 deletions src/log.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use chrono::prelude::*;
use slog::{o, Drain, Logger};

pub fn get_logger() -> Logger {
let decorator = slog_term::PlainSyncDecorator::new(std::io::stdout());
let drain = slog_term::FullFormat::new(decorator)
.use_custom_timestamp(|io| write!(io, "{}", Utc::now().format("%Y-%m-%d %H:%M:%S")))
.build()
.fuse();

Logger::root(drain, o!())
}

#[cfg(test)]
mod tests {
use slog::{crit, debug, error, info, trace, warn};

use crate::log::get_logger;

#[tokio::test]
async fn test_slog() {
let log = get_logger();

trace!(log, "trace log message");
debug!(log, "debug log message");
info!(log, "info log message");
warn!(log, "warn log message");
error!(log, "error log message");
crit!(log, "crit log message");
}
}
20 changes: 16 additions & 4 deletions src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use crate::parse_ip_address;
use async_trait::async_trait;
use futures::future::join_all;
use slog::info;
use std::error::Error;
use std::net::SocketAddr;
use std::sync::Arc;
Expand Down Expand Up @@ -36,15 +37,17 @@ pub struct TCPManager {
port: u16,
listener: Arc<Mutex<Option<TcpListener>>>,
is_open: Arc<Mutex<bool>>,
log: slog::Logger,
}

impl TCPManager {
pub fn new(address: String, port: u16) -> Self {
pub fn new(address: String, port: u16, log: slog::Logger) -> Self {
TCPManager {
address,
port,
listener: Arc::new(Mutex::new(None)),
is_open: Arc::new(Mutex::new(false)),
log,
}
}

Expand Down Expand Up @@ -114,7 +117,7 @@ impl NetworkLayer for TCPManager {
let listener = TcpListener::bind(addr).await?;
*self.listener.lock().await = Some(listener);
*is_open = true;
println!("Listening on {}", addr);
info!(self.log, "Listening on {}", addr);
Ok(())
}

Expand All @@ -125,18 +128,27 @@ impl NetworkLayer for TCPManager {
}
*self.listener.lock().await = None;
*is_open = false;
println!("Listener closed");
info!(self.log, "Listener closed");
Ok(())
}
}

#[cfg(test)]
mod tests {
use slog::{o, Drain};

use super::*;

fn get_logger() -> slog::Logger {
let decorator = slog_term::PlainSyncDecorator::new(std::io::stdout());
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let log = slog::Logger::root(drain, o!());
return log;
}

#[tokio::test]
async fn test_send() {
let network = TCPManager::new("127.0.0.1".to_string(), 8082);
let network = TCPManager::new("127.0.0.1".to_string(), 8082, get_logger());
let data = vec![1, 2, 3];
network.open().await.unwrap();
let network_clone = network.clone();
Expand Down
Loading
Loading