Sebastian Sebastian - 5 months ago 17x
Python Question

How to log to the console in an LLDB data formatter

I've written an LLDB data formatter but I could not get my log output to show in the Xcode lldb console. The data formatter examples create the logger and write to it like so:

def __init__(self, valobj, dict):
logger = lldb.formatters.Logger.Logger()
logger >> "Providing synthetic children for a vector named " + str(valobj.GetName())

I did that and I enabled the lldb formatters log with the command

log enable -g lldb formatters

When I then printed a variable (e.g. with
frame var x
) I did see a lot of debug output, but not mine.


I've figured it out by looking at the Logger source in more detail.

  1. To enable logging at all, you have to set lldb.formatters.Logger._lldb_formatters_debug_level to a value larger than 0. Quoting from the source itself:

    • if you define it to any value greater than 1, the log will be automatically flushed after each write (slower but should make sure most of the stuff makes it to the log even if we crash)
    • if you define it to any value greater than 2, the calling function's details will automatically be logged (even slower, but provides additional details)
  2. By default, lldb.formatters.Logger will print to stdout. If you're debugging with Xcode, you will not see lldb's stdout stream. If you want to log to a file, set lldb.formatters.Logger._lldb_formatters_debug_filename to the desired filename. Attention: You have to make sure the file is writable and you must not set it to a path that requires shell expansion (e.g. ~/logfile.log will not work, Python does not expand the ~).

In summary, my __lldb_init_module looks like this:

def __lldb_init_module(debugger, internal_dict):
    lldb.formatters.Logger._lldb_formatters_debug_level = 2
    lldb.formatters.Logger._lldb_formatters_debug_filename = "/Users/Shared/"

    # followed by debugger.HandleCommand(...)