Skip to content

Commit

Permalink
use tracing-appender (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaszKielar authored Sep 25, 2024
1 parent fbc289d commit 51f4128
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 25 deletions.
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ authors = ["Lukasz Kielar <[email protected]>"]
chrono = { version = "0.4", features = ["serde"] }
clap = { version = "4.5", features = ["derive"] }
crossterm = { version = "0.28", features = ["event-stream"] }
dirs = "5.0"
futures = "0.3"
once_cell = "1.19"
ratatui = "0.28"
Expand Down Expand Up @@ -36,7 +37,8 @@ tokio = { version = "1", features = [
] }
tokio-util = "0.7"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = [ "json" ] }
tracing-appender = "0.2"
tracing-subscriber = "0.3"
tui-textarea = { version = "0.6", features = ["ratatui", "crossterm"] }

[profile.dev]
Expand Down
43 changes: 31 additions & 12 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
use clap::Parser;
use serde::Deserialize;

use crate::LOKAI_DIR;

static OLLAMA_URL: &str = "http://localhost:11434";
static DEFAULT_LLM_MODEL: &str = "phi3:3.8b";

#[derive(Deserialize, Debug)]
pub struct AppConfig {
// TODO: replace with Kalosm
ollama_url: String,
// TODO: I need to be opinionated and allow to define only one model
default_llm_model: String,
// TODO: rename to sqlite_url
database_url: String,
}

impl Default for AppConfig {
fn default() -> Self {
impl AppConfig {
pub fn init() -> Self {
Self {
ollama_url: "http://localhost:11434".into(),
default_llm_model: "phi3:3.8b".into(),
database_url: "sqlite::memory:".into(),
ollama_url: "".to_string(),
default_llm_model: "".to_string(),
database_url: "".to_string(),
}
}
}

impl AppConfig {
pub fn get_ollama_url(&self) -> &str {
&self.ollama_url
}
Expand All @@ -31,10 +37,6 @@ impl AppConfig {
&self.database_url
}

pub fn set_default_llm_model(&mut self, default_llm_model: String) {
self.default_llm_model = default_llm_model;
}

pub fn update_from_cli_args(&mut self, cli_args: AppConfigCliArgs) {
if let Some(ref ollama_url) = cli_args.ollama_url {
self.ollama_url = ollama_url.to_string();
Expand All @@ -58,7 +60,24 @@ pub struct AppConfigCliArgs {
/// Default LLM Model user want to use
#[arg(long)]
default_llm_model: Option<String>,
/// Sqlite database URL
/// Sqlite database URL ["sqlite::memory:" (in-memory), "sqlite://db.slite3" (persistent), "db.sqlite3" (persitent)]
#[arg(long)]
database_url: Option<String>,
}

impl From<AppConfigCliArgs> for AppConfig {
fn from(value: AppConfigCliArgs) -> Self {
Self {
ollama_url: value.ollama_url.unwrap_or_else(|| OLLAMA_URL.to_string()),
default_llm_model: value
.default_llm_model
.unwrap_or_else(|| DEFAULT_LLM_MODEL.to_string()),
database_url: value.database_url.unwrap_or_else(|| {
format!(
"sqlite://{}/db.sqlite",
LOKAI_DIR.to_str().expect("Cannot get lokai config dir")
)
}),
}
}
}
35 changes: 23 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use std::{error::Error, io, result::Result, time::Duration};
use std::{error::Error, io, path::PathBuf, result::Result, time::Duration};

use clap::Parser;
use config::{AppConfig, AppConfigCliArgs};
use once_cell::sync::Lazy;
use ratatui::{backend::CrosstermBackend, Terminal};
use std::fs::OpenOptions;
use sqlx::{migrate::MigrateDatabase, sqlite::SqlitePoolOptions, Executor, SqlitePool};
use tokio::sync::{mpsc, RwLock};
use tracing::{info, Level};
use tracing_subscriber;

use crate::{app::App, event::EventHandler, tui::Tui};

Expand All @@ -26,27 +24,40 @@ pub mod ui;

pub type AppResult<T> = Result<T, Box<dyn Error>>;

static APP_CONFIG: Lazy<RwLock<AppConfig>> = Lazy::new(|| RwLock::new(AppConfig::default()));
static LOKAI_DIR: Lazy<PathBuf> = Lazy::new(|| {
let lokai_dir = dirs::home_dir()
.unwrap_or_else(|| std::env::current_dir().expect("Cannot get current working directory"))
.join(".lokai");

if !lokai_dir.exists() {
std::fs::create_dir(&lokai_dir)
.unwrap_or_else(|_| panic!("cannot create {:?} directory", lokai_dir))
}

lokai_dir
});
static APP_CONFIG: Lazy<RwLock<AppConfig>> = Lazy::new(|| RwLock::new(AppConfig::init()));

#[tokio::main]
async fn main() -> AppResult<()> {
let file = OpenOptions::new()
.create(true)
.append(true)
.open("app.log")?;

let logs_dir = LOKAI_DIR.join("logs");
if !logs_dir.exists() {
std::fs::create_dir(&logs_dir)?
}
let log_file = tracing_appender::rolling::daily(logs_dir, "lokai.log");
let (non_blocking, _guard) = tracing_appender::non_blocking(log_file);
tracing_subscriber::fmt()
.json()
.with_max_level(Level::INFO)
.with_writer(file)
.with_writer(non_blocking)
.with_ansi(false)
.init();

info!("starting");

let cli_args = AppConfigCliArgs::parse();
{
let mut app_config = APP_CONFIG.write().await;
app_config.update_from_cli_args(cli_args);
*app_config = cli_args.into();
}

if let Err(err) = verify_ollama_server().await {
Expand Down

0 comments on commit 51f4128

Please sign in to comment.