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

fix:reimplementing logging and OpenLogFile command #2459

Closed
wants to merge 2 commits into from
Closed
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
3 changes: 3 additions & 0 deletions Cargo.lock

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

4 changes: 3 additions & 1 deletion lapce-app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ lsp-types.workspace = true
smallvec.workspace = true
include_dir.workspace = true
regex.workspace = true
chrono.workspace = true
Inflector = "0.11.4"
open = "3.0.2"
unicode-width = "0.1.10"
Expand All @@ -48,7 +49,8 @@ floem = { git = "https://github.com/lapce/floem", rev = "5b1536bed7360d5a86fc3f4
# floem = { path = "../../workspaces/floem" }
config = { version = "0.13.2", default-features = false, features = ["toml"] }
structdesc = { git = "https://github.com/lapce/structdesc" }

fern = "0.6.0"
log-panics = { version = "2.1.0", features = ["with-backtrace"] }
[target.'cfg(target_os="macos")'.dependencies]
fs_extra = "1.2.0"
dmg = "0.1.1"
Expand Down
61 changes: 59 additions & 2 deletions lapce-app/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::os::windows::process::CommandExt;
use std::{
io::{BufReader, Read, Write},
ops::Range,
path::PathBuf,
process::Stdio,
sync::Arc,
};
Expand Down Expand Up @@ -64,6 +65,7 @@ use crate::{
focus_text::focus_text,
id::{EditorId, EditorTabId, SplitId},
listener::Listener,
logging::override_log_levels,
main_split::{MainSplitData, SplitContent, SplitData, SplitDirection},
palette::{
item::{PaletteItem, PaletteItemContent},
Expand Down Expand Up @@ -2380,6 +2382,51 @@ pub fn launch() {
#[cfg(feature = "updater")]
crate::update::cleanup();

let mut log_dispatch = fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(),
record.level(),
message
))
})
.level(log::LevelFilter::Debug)
.chain(override_log_levels(
fern::Dispatch::new()
.level(if cfg!(debug_assertions) {
log::LevelFilter::Warn
} else {
log::LevelFilter::Off
})
.chain(std::io::stderr()),
));

let log_file = LapceConfig::log_file();
if let Some(log_file) = log_file.clone().and_then(|f| fern::log_file(f).ok()) {
log_dispatch = log_dispatch.chain(
fern::Dispatch::new()
.level(log::LevelFilter::Debug)
.level_for("lapce_data::keypress::key_down", log::LevelFilter::Off)
.level_for("sled", log::LevelFilter::Off)
.level_for("tracing", log::LevelFilter::Off)
.level_for("druid::core", log::LevelFilter::Off)
.level_for("druid::window", log::LevelFilter::Off)
.level_for("druid::box_constraints", log::LevelFilter::Off)
.level_for("cranelift_codegen", log::LevelFilter::Off)
.level_for("wasmtime_cranelift", log::LevelFilter::Off)
.level_for("regalloc", log::LevelFilter::Off)
.level_for("hyper::proto", log::LevelFilter::Off)
.chain(log_file),
);
}

match log_dispatch.apply() {
Ok(()) => (),
Err(e) => eprintln!("Initialising logging failed {e:?}"),
}

let _ = lapce_proxy::register_lapce_path();
let db = Arc::new(LapceDb::new().unwrap());
let mut app = floem::Application::new();
Expand All @@ -2401,6 +2448,7 @@ pub fn launch() {
window_scale,
latest_release.read_only(),
app_command,
Arc::new(log_file),
);

let (tx, rx) = crossbeam_channel::bounded(1);
Expand Down Expand Up @@ -2497,6 +2545,7 @@ fn create_windows(
window_scale: RwSignal<f64>,
latest_release: ReadSignal<Arc<Option<ReleaseInfo>>>,
app_command: Listener<AppCommand>,
log_file: Arc<Option<PathBuf>>,
) -> floem::Application {
// Split user input into known existing directors and
// file paths that exist or not
Expand Down Expand Up @@ -2549,6 +2598,7 @@ fn create_windows(
window_scale,
latest_release,
app_command,
log_file.clone(),
);
windows.push_back(window_data.clone());
app = app.window(move || app_view(window_data), Some(config));
Expand All @@ -2565,6 +2615,7 @@ fn create_windows(
window_scale,
latest_release,
app_command,
log_file.clone(),
);
windows.push_back(window_data.clone());
app = app.window(move || app_view(window_data), Some(config));
Expand All @@ -2587,8 +2638,14 @@ fn create_windows(
workspaces: vec![LapceWorkspace::default()],
};
let config = WindowConfig::default().size(info.size).position(info.pos);
let window_data =
WindowData::new(scope, info, window_scale, latest_release, app_command);
let window_data = WindowData::new(
scope,
info,
window_scale,
latest_release,
app_command,
log_file,
);
windows.push_back(window_data.clone());
app = app.window(|| app_view(window_data), Some(config));
}
Expand Down
17 changes: 17 additions & 0 deletions lapce-app/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,23 @@ impl LapceConfig {
Some(path)
}

pub fn log_file() -> Option<PathBuf> {
let time = chrono::Local::now().format("%Y%m%d-%H%M%S");

let file_name = format!("{time}.log");

let path = Directory::logs_directory()?.join(file_name);

if !path.exists() {
let _ = std::fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(&path);
}

Some(path)
}

pub fn ui_svg(&self, icon: &'static str) -> String {
let svg = self.icon_theme.ui.get(icon).and_then(|path| {
let path = self.icon_theme.path.join(path);
Expand Down
1 change: 1 addition & 0 deletions lapce-app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub mod history;
pub mod id;
pub mod keypress;
pub mod listener;
mod logging;
pub mod main_split;
pub mod palette;
pub mod panel;
Expand Down
77 changes: 77 additions & 0 deletions lapce-app/src/logging.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use fern::Dispatch;
use log::LevelFilter;

fn apply(dispatch: Dispatch, module: Option<&str>, level: LevelFilter) -> Dispatch {
if let Some(module) = module {
dispatch.level_for(module.to_string(), level)
} else {
dispatch.level(level)
}
}

fn set_level(dispatch: Dispatch, module: Option<&str>, level: &str) -> Dispatch {
use LevelFilter::*;
match level {
"off" => apply(dispatch, module, Off),
"error" => apply(dispatch, module, Error),
"warn" => apply(dispatch, module, Warn),
"info" => apply(dispatch, module, Info),
"debug" => apply(dispatch, module, Debug),
"trace" => apply(dispatch, module, Trace),
val => {
eprint!("RUST_LOG: ");
if let Some(module) = module {
eprint!("module '{module}' ");
}
eprintln!("ignored unknown log level: '{val}'");
dispatch
}
}
}

fn parse_log_levels(value: &str, mut dispatch: fern::Dispatch) -> fern::Dispatch {
println!("Parsing RUST_LOG");

// To set the threshold at Error for all modules: RUST_LOG=error
//
// To set the threshold at Info for all but 'module1':
// RUST_LOG=info,path::to::module1=off
//
// To set the threshold at Trace for 'module1' and keep the rest at Off:
// RUST_LOG=path::to::module1=trace
//
// This would set the threshold at Info for all: RUST_LOG=error,info
//
// This sets the threshold at Error for all modules but 'module1' and
// 'module2' which are at Info and Debug, respectively:
// RUST_LOG="error,path::to::module1=info,path::to::module2=debug"
for section in value.split(',').filter(|s| !s.is_empty()) {
if let Some((module, level)) = section.split_once('=') {
println!("module='{module}', level='{level}'");
// "module=level"
//
// NOTE: The dash characters in crate names are converted into
// underscores by the compiler. For example, path to this
// module will be "lapce_ui::loggings".
dispatch = set_level(dispatch, Some(module), level);
} else {
println!("level='{section}' for all modules");
// just "level"
dispatch = set_level(dispatch, None, section);
}
}
dispatch
}

pub(super) fn override_log_levels(dispatch: Dispatch) -> Dispatch {
match std::env::var("RUST_LOG") {
// Not an error if the env var does not exist.
Err(std::env::VarError::NotPresent) => dispatch,
Err(std::env::VarError::NotUnicode(val)) => {
let val = val.to_string_lossy();
eprintln!("RUST_LOG: ignored invalid unicode value: '{val}'");
dispatch
}
Ok(val) => parse_log_levels(&val, dispatch),
}
}
9 changes: 8 additions & 1 deletion lapce-app/src/window.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::sync::Arc;
use std::{path::PathBuf, sync::Arc};

use floem::{
glazier::KeyEvent,
Expand Down Expand Up @@ -55,6 +55,7 @@ pub struct WindowData {
pub window_scale: RwSignal<f64>,
pub latest_release: ReadSignal<Arc<Option<ReleaseInfo>>>,
pub config: RwSignal<Arc<LapceConfig>>,
pub log_file: Arc<Option<PathBuf>>,
}

impl WindowData {
Expand All @@ -64,6 +65,7 @@ impl WindowData {
window_scale: RwSignal<f64>,
latest_release: ReadSignal<Arc<Option<ReleaseInfo>>>,
app_command: Listener<AppCommand>,
log_file: Arc<Option<PathBuf>>,
) -> Self {
let config = LapceConfig::load(&LapceWorkspace::default(), &[]);
let config = create_rw_signal(cx, Arc::new(config));
Expand All @@ -81,6 +83,7 @@ impl WindowData {
window_command,
window_scale,
latest_release,
log_file.clone(),
));
window_tabs.push_back((create_rw_signal(cx, 0), window_tab));
}
Expand All @@ -92,6 +95,7 @@ impl WindowData {
window_command,
window_scale,
latest_release,
log_file.clone(),
));
window_tabs.push_back((create_rw_signal(cx, 0), window_tab));
}
Expand All @@ -113,6 +117,7 @@ impl WindowData {
latest_release,
app_command,
config,
log_file,
};

{
Expand Down Expand Up @@ -154,6 +159,7 @@ impl WindowData {
self.window_command,
self.window_scale,
self.latest_release,
self.log_file.clone(),
));
self.window_tabs.update(|window_tabs| {
if window_tabs.is_empty() {
Expand Down Expand Up @@ -181,6 +187,7 @@ impl WindowData {
self.window_command,
self.window_scale,
self.latest_release,
self.log_file.clone(),
));
let active = self.active.get_untracked();
let active = self
Expand Down
23 changes: 22 additions & 1 deletion lapce-app/src/window_tab.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
use std::{collections::HashSet, env, path::Path, sync::Arc, time::Instant};
use std::{
collections::HashSet,
env,
path::{Path, PathBuf},
sync::Arc,
time::Instant,
};

use crossbeam_channel::Sender;
use floem::{
Expand Down Expand Up @@ -124,6 +130,7 @@ pub struct WindowTabData {
pub update_in_progress: RwSignal<bool>,
pub latest_release: ReadSignal<Arc<Option<ReleaseInfo>>>,
pub common: CommonData,
pub log_file: Arc<Option<PathBuf>>,
}

impl KeyPressFocus for WindowTabData {
Expand Down Expand Up @@ -159,6 +166,7 @@ impl WindowTabData {
window_command: Listener<WindowCommand>,
window_scale: RwSignal<f64>,
latest_release: ReadSignal<Arc<Option<ReleaseInfo>>>,
log_file: Arc<Option<PathBuf>>,
) -> Self {
let (cx, _) = cx.run_child_scope(|cx| cx);
let db: Arc<LapceDb> = use_context(cx).unwrap();
Expand Down Expand Up @@ -361,6 +369,7 @@ impl WindowTabData {
update_in_progress: create_rw_signal(cx, false),
latest_release,
common,
log_file,
};

{
Expand Down Expand Up @@ -587,6 +596,18 @@ impl WindowTabData {
}
OpenLogFile => {
// TODO:
if let Some(path) = (*self.log_file).clone() {
self.main_split.jump_to_location(
EditorLocation {
path,
position: None,
scroll_offset: None,
ignore_unconfirmed: false,
same_editor_tab: false,
},
None,
);
}
}
OpenLogsDirectory => {
if let Some(dir) = Directory::logs_directory() {
Expand Down
Loading