Skip to content

Commit

Permalink
feat(backend): better logging system
Browse files Browse the repository at this point in the history
  • Loading branch information
SpikeHD committed Oct 4, 2023
1 parent 3bcf1e5 commit c277fd4
Show file tree
Hide file tree
Showing 9 changed files with 157 additions and 24 deletions.
9 changes: 8 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,12 @@
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": ["javascript"]
"eslint.validate": [
"javascript"
],
"rust-analyzer.linkedProjects": [
"./backend/Cargo.toml",
"./backend/Cargo.toml",
"./backend/Cargo.toml"
]
}
61 changes: 55 additions & 6 deletions backend/Cargo.lock

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

2 changes: 2 additions & 0 deletions backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ edition = "2021"

[dependencies]
async-std = "1.12.0"
chrono = "0.4.31"
clap = { version = "4.3.21", features = ["derive"] }
colored = "2.0.4"
include_dir = "0.7.3"
mcping = { version = "0.2.0", optional = true }
mime_guess = "2.0.4"
Expand Down
57 changes: 57 additions & 0 deletions backend/src/logger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use colored::Colorize;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::sync::Mutex;

// Open a LOG_FILE in the default log directory
static mut LOG_FILE: Option<Mutex<File>> = None;

pub fn init(path: String) {
unsafe {
LOG_FILE = Some(Mutex::new(
OpenOptions::new()
.create(true)
.append(true)
.open(path)
.expect("Permission denied when opening log file"),
));
}
}

pub fn append_logfile(message: String) {
if unsafe { LOG_FILE.as_ref().is_none() } {
return;
}

let pretty_date = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
let mut file = unsafe { LOG_FILE.as_ref().unwrap().lock().unwrap() };
file
.write_all(format!("{} | {}\n", pretty_date, message).as_bytes())
.unwrap();
}

pub fn print_pretty(kind: String, message: String) {
let pretty_date = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
println!("[{}] {} {}", pretty_date, kind.bold(), message);
}

pub fn _print_error(message: String) {
print_pretty("[ERROR]".red().to_string(), message.clone());

// Write to log file
append_logfile(format!("[ERROR] {}", message));
}

pub fn _print_warning(message: String) {
print_pretty("[WARNING]".yellow().to_string(), message.clone());

// Write to log file
append_logfile(format!("[WARNING] {}", message));
}

pub fn print_info(message: String) {
print_pretty("[INFO]".blue().to_string(), message.clone());

// Write to log file
append_logfile(format!("[INFO] {}", message));
}
36 changes: 26 additions & 10 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use tide_acme::rustls_acme::caches::DirCache;
#[cfg(feature = "plugins")]
use crate::plugins::parse_enable_plugins;

mod logger;
mod resource_watcher;
mod util;
mod web;
Expand Down Expand Up @@ -89,6 +90,10 @@ pub struct Args {
/// Enable HTTPS. Not really needed for testing locally, but recommended for outside access
#[arg(short = 's', long)]
https: bool,

/// Log file path
#[arg(short = 'l', long, default_value = "")]
log_file: String,
}

fn main() {
Expand All @@ -97,6 +102,11 @@ fn main() {
let mut username = String::new();
let pwd;

// Init logger
if !args.log_file.is_empty() {
logger::init(args.log_file.clone());
}

if args.username.is_none() || args.password.is_none() {
// Prompt for username
print!("Username to use while authenticating: ");
Expand Down Expand Up @@ -157,15 +167,21 @@ fn main() {
#[cfg(feature = "plugins")]
parse_enable_plugins(&mut app, args.plugins.clone(), args.address.clone());

println!("Starting server on port {}...", args.port);
println!("Retaining {} elements of metric history", args.history_max);
println!("Updating every {} seconds", args.update_rate);
println!(
"Done! Access the web interface at http{}:https://{}:{}/",
// Lol this is so dumb
if args.https { "s" } else { "" },
args.address,
args.port
if args.https {
logger::print_info(format!("Putting ACME cache in {}/.acme_cache", tmp_dir.display().to_string()));
}

logger::print_info(format!("Starting server on port {}...", args.port));
logger::print_info(format!("Retaining {} elements of metric history", args.history_max));
logger::print_info(format!("Updating every {} seconds", args.update_rate));
logger::print_info(
format!(
"Done! Access the web interface at http{}:https://{}:{}/",
// Lol this is so dumb
if args.https { "s" } else { "" },
args.address,
args.port
)
);

task::block_on(async {
Expand Down Expand Up @@ -198,7 +214,7 @@ fn recursive_serve(app: &mut tide::Server<State>, path: Option<&Path>) {
for file in dir.files() {
let path = format!("{}", file.path().display());

println!("Serving {}", path);
logger::print_info(format!("Serving {}", path));

app
.at(&path)
Expand Down
4 changes: 2 additions & 2 deletions backend/src/plugins/minecraft.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use mcping;
use serde::Serialize;

use crate::State;
use crate::{State, logger};

#[derive(Serialize, Clone)]
struct McData {
Expand All @@ -15,7 +15,7 @@ struct McData {
static mut ACCESS_ADDRESS: String = String::new();

pub fn register(app: &mut tide::Server<State>, access_address: String) -> Vec<String> {
println!("Enabling Minecraft plugin");
logger::print_info("Enabling Minecraft plugin");

unsafe {
ACCESS_ADDRESS = access_address;
Expand Down
4 changes: 3 additions & 1 deletion backend/src/plugins/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::State;
use serde::Serialize;

use crate::logger;

mod minecraft;

#[derive(Serialize, Clone)]
Expand Down Expand Up @@ -38,7 +40,7 @@ pub fn parse_enable_plugins(
};

for endpoint in endpoints {
println!("Registered endpoint: {}", endpoint);
logger::print_info(format!("Registered endpoint: {}", endpoint));
registered_endpoints.push(Plugin {
name: plugin.to_string(),
endpoints: vec![endpoint],
Expand Down
4 changes: 2 additions & 2 deletions backend/src/web/middleware.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use tide::utils::async_trait;

use crate::User;
use crate::{User, logger};

pub struct AuthMiddleware {}

Expand All @@ -14,7 +14,7 @@ where
let mut res: tide::Response = tide::Response::new(401);
res.insert_header("WWW-Authenticate", "Basic");

println!("Attempted access by {}", req.remote().unwrap_or("unknown"));
logger::print_info(format!("Attempted access by {}", req.remote().unwrap_or("unknown")));

return Ok(res);
}
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"name": "procchi",
"version": "0.1.0",
"scripts": {
"start:bun": "cd ./frontend && bun run build && cd ../backend && cargo run -- -u test -k test -s",
"start": "cd ./frontend && npm run build && cd ../backend && cargo run -- -u test -k test -s",
"start:bun": "cd ./frontend && bun run build && cd ../backend && cargo run -- -u test -k test",
"start": "cd ./frontend && npm run build && cd ../backend && cargo run -- -u test -k test",
"build:bun": "cd ./frontend && bun run build && cd ../backend && cargo build --release",
"build": "cd ./frontend && npm run build && cd ../backend && cargo build --release",
"clippy:fix": "cargo clippy --manifest-path ./backend/Cargo.toml --all --fix",
Expand Down

0 comments on commit c277fd4

Please sign in to comment.