Moved `create_dir_all` to a separate function for easier portability for
implementing with `xi-lsp-plugin`.
Allowed fern to be setup with either the logfile or stdout as a backup.
Catching non-fatal issues gracefully.
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
-use std::io;
-use std::fs;
-use std::path::PathBuf;
#[macro_use]
extern crate log;
@@ -21,23 +18,39 @@ extern crate chrono;
extern crate fern;
extern crate dirs;
-use dirs::data_local_dir;
extern crate xi_core_lib;
extern crate xi_rpc;
+use std::io;
+use std::fs;
+use std::path::PathBuf;
+
use xi_core_lib::XiCore;
use xi_rpc::RpcLoop;
-fn get_logging_directory() -> Result<PathBuf, fern::InitError> {
- let xi_directory = "xi-core/";
- if let Some(mut log_dir) = data_local_dir() {
- log_dir.push(xi_directory);
- Ok(log_dir)
+const XI_DIRECTORY: &'static str = "xi-core";
+const XI_LOG_FILE: &'static str = "xi-core.log";
+
+fn get_logging_directory() -> Option<PathBuf> {
+ if let Some(mut log_dir) = dirs::data_local_dir() {
+ log_dir.push(XI_DIRECTORY);
+ Some(log_dir)
} else {
- let dir_error = io::Error::new(io::ErrorKind::Other, "dir was not able to find a directory");
- Err(fern::InitError::Io(dir_error))
+ eprintln!("[WARNING] The dir library was not able to find a directory for this platform");
+ None
+ }
}
+
+fn path_for_log_file<P: AsRef<str>>(filename: P) -> Option<PathBuf> {
+ if let Some(mut logging_directory) = get_logging_directory() {
+ // Create the logging directory
+ match fs::create_dir_all(&logging_directory) {
+ Ok(_) => (), Err(why) => eprintln!("[WARNING] {:?}", why)
+ }
+ logging_directory.push(filename.as_ref());
+ Some(logging_directory)
+ } else { None }
}
fn setup_logging() -> Result<(), fern::InitError> {
@@ -51,26 +64,30 @@ fn setup_logging() -> Result<(), fern::InitError> {
Err(_) => log::LevelFilter::Info,
};
- let logging_directory = get_logging_directory()?;
- // Create the logging directory
- fs::create_dir_all(&logging_directory)?;
-
- let xi_log_file = "xi-core.log";
- let mut logging_file_path = logging_directory;
- logging_file_path.push(xi_log_file);
- fern::Dispatch::new()
+ let fern_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
+ message,
))
- }).level(level_filter)
- .chain(io::stderr())
+ })
+ .level(level_filter)
+ .chain(io::stderr());
+
+ if let Some(logging_file_path) = path_for_log_file(XI_LOG_FILE) {
+ fern_dispatch
.chain(fern::log_file(logging_file_path)?)
.apply()?;
+ } else {
+ eprintln!("[WARNING] There was an issue getting the path for the log file, using stdout");
+ fern_dispatch
+ .chain(io::stdout())
+ .apply()?;
+ }
+ info!("Logging with fern setup");
Ok(())
}
