Trying to get file, function, line number



  • I'm trying to get file, function and line number to display in a message. I found a technique here (https://forum.micropython.org/viewtopic.php?t=7811), and tried to adapt it. It seemed to be working for a bit, but then somehow it stopped. The idea was to force an exception, which should dump a stack trace, then rummage through that. But for some reason, it is only showing the current function:

    Traceback (most recent call last):
      File "lib/logging.py", line 46, in log
    ValueError: foo
    'Traceback (most recent call last):\n  File "lib/logging.py", line 46, in log\nValueError: foo\n'
    line= Traceback (most recent call last):
    line=   File "lib/logging.py", line 46, in log
    INFO:Traceback (most recent call last)::ShowError (2000-1-1 0:0:14): error='WiFi connected'
    

    Here's my code (borrowed in part from https://github.com/m5stack/M5Stack_MicroPython/blob/master/MicroPython_BUILD/components/micropython/esp32/modules/logging.py). Note that I also tried the seek(0) readline() thing from the example I'm copying, but it doesn't matter. In fact, just throwing a straight sys.print_exception(err) and letting it print out still doesn't show the stack.

        def log(self, level, msg, *args):
            if level >= (self.level or _level):
                redirect = io.StringIO()
                try:
                  raise ValueError('foo')
                except ValueError as err:
                  sys.print_exception(err, redirect)
                print('%r' % redirect.getvalue())
                caller = 'unknown'
                for new_line in redirect.getvalue().splitlines():
                  print('line=',new_line)
                  if 'logging.py' in new_line:
                    break
                  caller = new_line
                if caller != 'unknown':
                  caller = caller_re.sub('[\\1:\\2](\\3)', caller)
                _stream.write("%s:%s:" % (self._level_str(level), caller))
                if not args:
                    print(msg, file=_stream)
                else:
                    print(msg % args, file=_stream)
    

    I know from other code that I have that sys.print_exception(err) normally prints the stack, so I'm a bit flummoxed!

    Any ideas where the stack trace went?