ROS2的日志级别定义在文件/opt/ros/humble/include/rcutils/rcutils/logging.h
的167-175行。
/// The severity levels of log messages / loggers.
enum RCUTILS_LOG_SEVERITY
{
RCUTILS_LOG_SEVERITY_UNSET = 0, ///< The unset log level
RCUTILS_LOG_SEVERITY_DEBUG = 10, ///< The debug log level
RCUTILS_LOG_SEVERITY_INFO = 20, ///< The info log level
RCUTILS_LOG_SEVERITY_WARN = 30, ///< The warn log level
RCUTILS_LOG_SEVERITY_ERROR = 40, ///< The error log level
RCUTILS_LOG_SEVERITY_FATAL = 50, ///< The fatal log level
};
ros2中日志是属于节点对象的,也就是需要通过节点对象获取节点的日志。
this->get_logger()
获取节点的日志对象之后,才能对节点进行其他设置操作。
日志的接口
set_leve(Level level)
设置日志级别;
设置节点的日志级别之后,只输出当前级别以及更低级别日志。
#include <chrono>
#include "rclcpp/rclcpp.hpp"
using namespace std::literals::chrono_literals;
class ParamLogNode:public rclcpp::Node{
public:
ParamLogNode(std::string name):Node(name){
RCLCPP_INFO(this->get_logger(),"I am %s",name.c_str());
this->declare_parameter("param_log_lelvel",0);
this->get_parameter("param_log_level",log_level_);
this->get_logger().set_level(static_cast[rclcpp::Logger::Level](rclcpp::Logger::Level)(log_level_));
timer_=this->create_wall_timer(500ms,std::bind(&ParamLogNode::_timer_callback,this));
}
private:
void timer_callback(){
_ this->get_parameter("param_log_level",log_level_);
this->get_logger().set_level(static_cast[rclcpp::Logger::Level](rclcpp::Logger::Level)(log_level_));
std::cout<<"============================================================="<<std::endl;
RCLCPP_DEBUG(this->get_logger(),"DEBUG log...");
RCLCPP_INFO(this->get_logger(),"INFO log...");
RCLCPP_WARN(this->get_logger(),"WARN log...");
RCLCPP_ERROR(this->get_logger(),"ERROR log...");
RCLCPP_FATAL(this->get_logger(),"FATAL log...");
}
private:
int log_level_{0};
rclcpp::TimerBase::SharedPtr timer_{};
};
int main(int argc,char** argv){
rclcpp::init(argc,argv);
auto node=std::make_shared<ParamLogNode>("param_log_01");
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}