0

I would like the logger to print the linenumber where the subprocess.run method is called, the example below prints the linenumber where the wrapfunction is defined

#!/usr/bin/env python3
import logging, sys, functools, subprocess    

logging.basicConfig(stream=sys.stdout, level=logging.INFO,style='{',format='⬬ {lineno:4d} ⬤ {pathname} ⬮\n{msg}')    

def wrap_function(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        logging.info((args,kwargs))  # lineno=9
        return func(*args ,**kwargs)
    return wrapper    

subprocess.run = wrap_function(subprocess.run)    

subprocess.run('ls',timeout=10,shell=True)  # lineno=15

Of course I get the line number where logging.info is called:

# current output:
#⬬    9 ⬤ ./PycharmProjects/02.py ⬮
#(('ls',), {'timeout': 10, 'shell': True})

Is there a way to define the msg argument to logging.info without calling logging.info? This is the output I would like to have:

# output I would like to have:
#⬬   15 ⬤ ./PycharmProjects/02.py ⬮
#(('ls',), {'timeout': 10, 'shell': True})
v217
  • 765
  • 1
  • 6
  • 17
  • 1
    Where would you want to define `msg`? It might be a problem for `functools.partial` – Patrick Haugh Feb 01 '18 at 15:31
  • @PatrickHaugh msg=(args,kwargs) (args,kwargs) has a string representation. lineno should be the last line in the code example line number: 20 – v217 Feb 01 '18 at 15:41
  • 1
    See if the answers in [this question](https://stackoverflow.com/questions/32443808/best-way-to-override-lineno-in-python-logger) help. The accepted one sounds like it may only work for python2 though – Patrick Haugh Feb 01 '18 at 15:48
  • @PatrickHaugh This looks like a way too complicated solution, anyway I will try to simplify it, if possible. I think something like clojures transducers would solve my problem. I was really hoping for a simple elegant solution! – v217 Feb 01 '18 at 15:56

0 Answers0