Repository navigation
add logging API and macros - #138
dirk-thomas wants to merge 11 commits into
Conversation
wjwwood
left a comment
There was a problem hiding this comment.
This is looking good. I like the set of options and the set of combinations of the options.
I have a few high level questions still though:
- Why put this in
rclrather thanrcutils?- Perhaps it was historical, but other than the macros that have a dependency on the
rcl_time_source_t, they are generic C functions and do not have to be inrcl. - I think they would be useful in
rmwand in the rmw implementations. - I would even consider moving the "time source" struct, the system time source, and the steady time source to
rcutilsas well so pretty much all of this code could be moved there.
- Perhaps it was historical, but other than the macros that have a dependency on the
- What about having different severity levels for each named logger?
- I see this as a crucial feature, even at a low level (and in C code), not just in high level C++/Python code.
- You might be planning this, but if you are, I'm curious about when you think you'd implement it and if we should merge this before doing that.
- What about having multiple output handlers, I see this as a core feature, again even at a low level (say console + file)?
- You might be planning this, but if you are, I'm curious about when you think you'd implement it and if we should merge this before doing that.
- What about requiring the caller to pass in a
rcl_time_source_tobject already initialized or a function pointer for "get now" with a generic interface?- I think this would help avoid some race conditions I commented on above.
- Also, @tfoote and I discussed with you at some point about removing the
rcl_time_source_init(enum, ...)function because it won't work with the ROS time source since it will need a Node to be initialized.
- What was the reason for not committing the generated log file (only running the generator code on demand)?
| VERBATIM | ||
| ) | ||
| list(APPEND ${PROJECT_NAME}_sources | ||
| include/rcl/logging_macros.h) |
There was a problem hiding this comment.
Why does this need to be part of the sources?
There was a problem hiding this comment.
Since the file is generated this makes sure the generation happens before the library is being compiled.
| void rcl_logging_initialize(); | ||
|
|
||
| /// The structure identifying the caller location in the source code. | ||
| typedef struct RclLogLocation |
There was a problem hiding this comment.
In the rest of rcl and our other C packages, structs take on the signature rcl_log_location_t.
There was a problem hiding this comment.
I started with names similar as in ROS 1. Updated in 42a02ab
| * \param The format string | ||
| * \param The variable argument list | ||
| */ | ||
| typedef void (* RclLogFunction)( |
There was a problem hiding this comment.
Same thing here, to be consistent it ought to be all_lower_case_t.
| * \param The format string | ||
| * \param The variable argument list | ||
| */ | ||
| typedef void (* RclLogFunction)( |
There was a problem hiding this comment.
Should this be called something like "rcl logging output handler"? I see that it is being returned and taken for the getters and setters of the current output handler, but the name doesn't imply that.
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| /*! \file */ |
There was a problem hiding this comment.
Maybe you should mention here that this file is generated and it should not be modified directly.
Especially since it is generated every build (what changed there btw, I remember discussing with you at some point and it was going to be "run once and commit")?
There was a problem hiding this comment.
I added a comment at the top of the template (same as for all other templates in ROS 2): 8c4d13f
The \file docblock only exists to extract the documentation for the macros.
| static bool __rcl_logging_init_time_source_called = false; \ | ||
| if (RCL_UNLIKELY(!__rcl_logging_init_time_source_called)) { \ | ||
| __rcl_logging_init_time_source_called = true; \ | ||
| if (rcl_time_source_init(time_source_type, &__rcl_logging_time_source)) { \ |
There was a problem hiding this comment.
I believe this is going to be a race condition. I think it's a sever enough one that the above docs should mention it.
This might be avoided by requiring the caller to pass in an already initialized time source, but I'll ask more on that later.
| rcl_time_point_value_t __rcl_logging_now = 0; \ | ||
| bool __rcl_logging_condition = true; \ | ||
| if (RCL_LIKELY(__rcl_logging_time_source.get_now != NULL)) { \ | ||
| if (__rcl_logging_time_source.get_now(__rcl_logging_time_source.data, &__rcl_logging_now)) { \ |
There was a problem hiding this comment.
get_now returns a rcl_ret_t, not a bool, so I think it ought to be compared with RCL_RET_OK:
| void rcl_logging_initialize() | ||
| { | ||
| if (!g_rcl_logging_initialized) { | ||
| g_rcl_logging_initialized = true; |
There was a problem hiding this comment.
I think this is a race condition when threading. Imagine this block of code racing:
rcl_logging_initialize();
if (g_rcl_logging_output_handler == NULL || g_rcl_logging_severity_threshold == 0) {
printf("there was a problem\n");
}Can't these two variables just be statically initialized?
If you're planning to do something more sophisticated in the future (do something that isn't a constexpr according the C compiler) in this function, then I think the only safe way to have this function be thread-safe would be to use a mutex.
There was a problem hiding this comment.
For now the variables could be statically initialized. But I expect in the future additional information to be added here (as in ROS 1) and then it needs an explicit init() function.
There was a problem hiding this comment.
That's what I figured, and that's fine, but I still think it presents a thread safety issue, but I'll take that point up elsewhere.
There was a problem hiding this comment.
I was thinking about this last night, and I think if that you might ought to move this line (assigning true to the global bool) to the end of the if statement block.
The reason I think that is that I think this bool is there to protect logging functions so they don't try to use logging output handler and severity threshold before they are assigned. So, if a logging macro is executed between lines 32 and 33, then they might try to use them anyways even though they are not set yet in this thread.
| return; | ||
| } | ||
|
|
||
| char buffer[1024]; |
There was a problem hiding this comment.
This limitation put on the console logger should be documented (it may be but I missed it). Why not allocate here? Obviously there is a performance hit there, but perhaps you could simply allocate when 1024 is not enough space. *snprintf will calculate the length for you if you pass NULL for the buffer.
If you insist on keeping the limit, you should consider printing a warning that the log message is being truncated, perhaps naively in the case that written >= sizeof(buffer). That would be a false positive in the case that the output string is exactly the size of the buffer, but you could also make the buffer size 1024 but advertise a limit of 1023 or 1000.
There was a problem hiding this comment.
I think we should definitely avoid allocating memory here. For the case where it exceeds this fixed buffer falling back to memory allocation sounds like a good idea. I have implemented it in fa0aa48 but just want to mention that it does imply a performance penalty since the string has to be formatted multiple times (only in the case where the length demands it though).
There was a problem hiding this comment.
That's true, but the only alternative is to always calculate the string length once to start. That actually might not be too bad, since it doesn't actually need to copy memory in that case, but it would need to call strlen and itoa and friends multiple times.
I made a few comments on that commit:
fa0aa48#commitcomment-22256428
That code is tricky, and not made easier due to subtle differences in posix and Windows implementations.
| } else { | ||
| fprintf( | ||
| stream, "[%s] [%s]: %s (%s() at %s:%zu)\n", severity_string, name, buffer, | ||
| location->function_name, location->file_name, location->line_number); |
There was a problem hiding this comment.
Also, it seems a bit silly to avoid allocating memory above, only to allow it here. You could avoid this by using another local, fixed-sized buffer to expand these format strings and then use fwrite to output to the stream.
There was a problem hiding this comment.
I am not sure I understand. You expect fprintf to allocate memory and avoid using it in favor of fwrite?
|
One more thing I forgot to mention. I think the documentation (for the module or for each macro) should touch on thread-safety. In much of the code we write I would be fine with saying "assume non-thread-safe", but for this logging code I can easily imagine people unintentionally using it in a non-thread-safe way. And since it will be so generic and ubiquitous I think we should consider ensuring it is thread-safe. I'm fine having non-thread-safe versions that are faster, but I think those might ought to be opt-in. The last thing you want to be flakey due to a race condition is your logging code 😄. |
Simply because the logging code was started before
As I mentioned I left the feature out since we don't have the necessary data structure available in C at the moment. Once we make a decision to either write our own (I am not a big fan of that approach) or rely on an external library that functionality can be added.
I don't think the "core" API needs to support that. Both of the following approaches are imo suitable:
I think the logging macros can already be added as-is and would be very useful even without the logger specific thresholds and additional output handlers. Because we can finally use them in the code which is otherwise using
The current API is easy for the caller since only a single argument (the time source type) needs to be passed. In order to pass a time source the caller has to keep that instance around (and will likely do so in a way which doesn't support the optimizations of the macros of not needing to creating it until it is required). Therefore I would keep the API as-is until the need arises when the time functions are changed.
Imo committing the generated code always has the drawback that the generator needs to be invoked manually after changing anything in the generation pipeline. Therefore I prefer to generate the file on-the-fly (which doesn't require significant resources and the dependency is already there).
The management API to configure the logging subsystem is not thread safe atm. I added notes to the documentation stating this (add059c). Imo we should delegate the responsibility of making those calls in a thread safe manner to the caller since otherwise that would significantly harm the performance. The default output handler is using |
There are two places which I currently fear there will be a race:
For the first case I think this line might be misleading me: It implied that all macros will call initialize if it hasn't already been initialized. If that is the case then the initialize code is at risk, because it does something like: void rcl_logging_init()
{
if (!g_rcl_logging_is_init) {
g_rcl_logging_is_init = true;
// do one time only init stuff, i.e. critical section
}
}If you run the above code in many threads, something like: int main() {
std::vector<std::thread> threads;
for (size_t i = 0; i < 100; ++i) {
threads.emplace_back([]() {
RCL_LOG_INFO("Hi!") // which according to the doc may call rcl_logging_init()
});
}
}Then you might get more than one of those threads into the critical section. The second case is similar, consider: void run() {
// this will generate one static time source and reuse it in all the threads, AFAIU
ROS_LOG_THROTTLE_SYSTEM_TIME(1.0, "Hi!")
}
int main() {
std::vector<std::thread> threads;
for (size_t i = 0; i < 100; ++i) {
threads.emplace_back(run);
}
}I think you could get in a situation where the above try's to initialize the time source multiple times. A separate question is whether or not the above code should print |
|
I said:
Was worrying me, but looking at the diff again, I don't believe it is actually being called automatically by the other logging macros, as this says: So in that case, I don't think it is a thread-safety problem in the common case. I think it should be sufficient to state that this function needs to be called before logging starts and is not thread safe, which you did note here: |
60cc24a to
5bb18da
Compare
|
Closing in favor of ros2/rcutils#23 |
* check the return value of rcutils_snprintf * use memmove instead of strncpy * use signed int for result of rcutils_snprintf() * remove redundant check
This PR implements a minimal C API for logging. It provides the following features known from ROS 1 (and a couple more):
Logging macros
formatstring andvariable argumentsnameonceskip firstthrottletaking atime source typeas well as adurationin msexpressioncan take an arbitrary expression deciding if a message is logged or notfunctioncan a function pointer which return value decides if a message is logged or notfunction API
rcl_logis the single log function being called from all macros which then invokes the configured output handlerFeatures
The macros don't offer signatures with a filter class argument or streams since both are C++ concepts.
The implementation avoids any complex data structures (like lists and maps) (for now?) and therefore doesn't offer:
CI is currently green on all platforms: