Skip to content

add logging API and macros - #138

Closed
dirk-thomas wants to merge 11 commits into
masterfrom
logging
Closed

dirk-thomas wants to merge 11 commits into
masterfrom
logging

Conversation

@dirk-thomas

Copy link
Copy Markdown
Member

This PR implements a minimal C API for logging. It provides the following features known from ROS 1 (and a couple more):

  • Logging macros

    • all log macros take a format string and variable arguments
    • plain log calls have no further arguments
    • log calls can have an optional name
    • the condition once
    • the condition skip first
    • the condition throttle taking a time source type as well as a duration in ms
    • the condition expression can take an arbitrary expression deciding if a message is logged or not
    • the condition function can a function pointer which return value decides if a message is logged or not
    • all log macros pass the function name, filename, and line number to the output handler
  • function API

    • initialize the logging system
    • get/set output handler, the default writes to stdout/stderr
    • set a global severity threshold (at compile time or at runtime)
    • rcl_log is the single log function being called from all macros which then invokes the configured output handler
  • Features

    • All conditions are being handled within the macro
    • All variable names within macros use "highly" prefixed names to avoid collisions
    • No function call until the message is actually being passed to the output handler
    • Template based generation to avoid repetition and provide consistent signatures as well as documentation
    • Easily compose multiple conditions without having to worry to break the logic

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:

  • more than one output handler
  • logger name specific severity thresholds

CI is currently green on all platforms:

  • Linux Build Status
  • Linux-aarch64 Build Status
  • macOS Build Status
  • Windows Build Status

@dirk-thomas dirk-thomas added the in review Waiting for review (Kanban column) label May 19, 2017
@dirk-thomas dirk-thomas self-assigned this May 19, 2017

@wjwwood wjwwood left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 rcl rather than rcutils?
    • 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 in rcl.
    • I think they would be useful in rmw and in the rmw implementations.
    • I would even consider moving the "time source" struct, the system time source, and the steady time source to rcutils as well so pretty much all of this code could be moved there.
  • 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_t object 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)?

Comment thread rcl/CMakeLists.txt
VERBATIM
)
list(APPEND ${PROJECT_NAME}_sources
include/rcl/logging_macros.h)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this need to be part of the sources?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the file is generated this makes sure the generation happens before the library is being compiled.

Comment thread rcl/include/rcl/logging.h Outdated
void rcl_logging_initialize();

/// The structure identifying the caller location in the source code.
typedef struct RclLogLocation

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the rest of rcl and our other C packages, structs take on the signature rcl_log_location_t.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I started with names similar as in ROS 1. Updated in 42a02ab

Comment thread rcl/include/rcl/logging.h Outdated
* \param The format string
* \param The variable argument list
*/
typedef void (* RclLogFunction)(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same thing here, to be consistent it ought to be all_lower_case_t.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: e072230

Comment thread rcl/include/rcl/logging.h Outdated
* \param The format string
* \param The variable argument list
*/
typedef void (* RclLogFunction)(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: e072230

// See the License for the specific language governing permissions and
// limitations under the License.

/*! \file */

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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")?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)) { \

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread rcl/resource/logging_macros.h.em Outdated
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)) { \

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

get_now returns a rcl_ret_t, not a bool, so I think it ought to be compared with RCL_RET_OK:

https://github.com/ros2/rcl/blob/master/rcl/include/rcl/time.h#L61

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! Fixed: 256dcdf

Comment thread rcl/src/rcl/logging.c Outdated
void rcl_logging_initialize()
{
if (!g_rcl_logging_initialized) {
g_rcl_logging_initialized = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh yeah, absolutely: 51ccce9

Comment thread rcl/src/rcl/logging.c
return;
}

char buffer[1024];

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread rcl/src/rcl/logging.c
} else {
fprintf(
stream, "[%s] [%s]: %s (%s() at %s:%zu)\n", severity_string, name, buffer,
location->function_name, location->file_name, location->line_number);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure I understand. You expect fprintf to allocate memory and avoid using it in favor of fwrite?

@wjwwood

wjwwood commented May 23, 2017

Copy link
Copy Markdown
Member

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 😄.

@dirk-thomas

Copy link
Copy Markdown
Member Author

Why put this in rcl rather than rcutils?

Simply because the logging code was started before rcutils existed. I will move the PR to the new repo.

What about having different severity levels for each named logger?

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.

What about having multiple output handlers, I see this as a core feature, again even at a low level (say console + file)?

I don't think the "core" API needs to support that. Both of the following approaches are imo suitable:

  • Register a composite output handler which can pass the log call to multiple sub handlers. That composite handle would require an container data structure though to manage the sub handlers.
  • Whenever you register an output handler make sure to also invoke the previous one (basically chain them on demand).

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.

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 printf which is not worse (always printing).

What about requiring the caller to pass in a rcl_time_source_t object already initialized or a function pointer for "get now" with a generic interface? 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.

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.

What was the reason for not committing the generated log file (only running the generator code on demand)?

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).

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.

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 printf under the hood which afaik is thread safe (at least on posix?) so I wouldn't expect any threading related problems. Which exact part are you worried about which could make the logging code flaky?

@wjwwood

wjwwood commented May 24, 2017

Copy link
Copy Markdown
Member

Which exact part are you worried about which could make the logging code flaky?

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:

https://github.com/ros2/rcl/pull/138/files#diff-77cf37ad38cc36a6543a165f2fde7ca0R35

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 Hi! 100 times or just once 😄.

@wjwwood

wjwwood commented May 24, 2017

Copy link
Copy Markdown
Member

I said:

All of the macros checking and then calling rcl_logging_initialize() if not already

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:

https://github.com/ros2/rcl/pull/138/files#diff-77cf37ad38cc36a6543a165f2fde7ca0R35

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:

add059c

@dirk-thomas
dirk-thomas force-pushed the logging branch 8 times, most recently from 60cc24a to 5bb18da Compare May 25, 2017 17:57
@dirk-thomas

Copy link
Copy Markdown
Member Author

The latest round of CI also checks long messages (which require dynamic allocation) including double va_list usage:

  • Linux Build Status
  • Linux-aarch64 Build Status
  • macOS Build Status
  • Windows Build Status

@dirk-thomas

Copy link
Copy Markdown
Member Author

Closing in favor of ros2/rcutils#23

@dirk-thomas dirk-thomas closed this Jun 1, 2017
@dirk-thomas
dirk-thomas deleted the logging branch June 1, 2017 18:18
@dirk-thomas dirk-thomas removed the in review Waiting for review (Kanban column) label Jun 1, 2017
ivanpauno pushed a commit that referenced this pull request Jan 2, 2020
* check the return value of rcutils_snprintf

* use memmove instead of strncpy

* use signed int for result of rcutils_snprintf()

* remove redundant check
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants