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

Read the ROSCONSOLE_FORMAT env var to format the logs #174

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions rosrust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ yaml-rust = "0.4.5"
crossbeam = "0.8.1"
socket2 = "0.4.1"
colored = "2.0.0"
thread-id = "4.0.0"

[dependencies.ros_message]
path = "../ros_message"
Expand Down
31 changes: 27 additions & 4 deletions rosrust/src/api/ros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::msg::std_msgs::Header;
use crate::tcpros::{Client, Message, ServicePair, ServiceResult};
use crate::{RawMessage, RawMessageDescription};
use error_chain::bail;
use lazy_static::lazy_static;
use log::error;
use ros_message::{Duration, Time};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -347,15 +348,37 @@ impl Ros {
}

fn log_to_terminal(&self, level: i8, msg: &str, file: &str, line: u32) {
lazy_static! {
static ref FORMAT_LINE: String = std::env::var("ROSCONSOLE_FORMAT")
.unwrap_or("[${severity}] [${time}]: ${message}".to_string());
}

use colored::{Color, Colorize};

let format_string =
|prefix, color| format!("[{} @ {}:{}]: {}", prefix, file, line, msg).color(color);
let format_string = |prefix, color| {
// 'walltime', 'logger' and 'function' missing

// Direct replace for common and cheap to replace items
let mut log_line = FORMAT_LINE
.replace("${severity}", prefix)
.replace("${time}", &self.now().to_string())
.replace("${message}", msg)
.replace("${node}", &self.name)
.replace("${file}", file);
if let Some(_index) = log_line.find("${thread}") {
log_line = log_line.replace("${thread}", &format!("{:x}", thread_id::get()));
}
if let Some(_index) = log_line.find("${line}") {
log_line = log_line.replace("${line}", &line.to_string());
}

log_line.color(color)
};

match level {
Log::DEBUG => println!("{}", format_string("DEBUG", Color::White)),
Log::INFO => println!("{}", format_string("INFO", Color::White)),
Log::WARN => eprintln!("{}", format_string("WARN", Color::Yellow)),
Log::INFO => println!("{}", format_string(" INFO", Color::White)),
Log::WARN => eprintln!("{}", format_string(" WARN", Color::Yellow)),
Log::ERROR => eprintln!("{}", format_string("ERROR", Color::Red)),
Log::FATAL => eprintln!("{}", format_string("FATAL", Color::Red)),
_ => {}
Expand Down