-1

How can I make print() to always print a leading string every time it is used. I need it to keep track of the things that are printed to the console based on execution ID every time print() is used.

For example, if I have: execution_id = "123abc"

and I do: print("My Name")

I want the output in the logs to be:

123abc - My Name

Any ideas?

We thought about using the python logger, but we are looking for a solution focused on using print(). Maybe by modifying the print() function. So that by default everything that is printed has a leading sting.

miguel
  • 1
  • 2

2 Answers2

1

You could use the in-built logging module with a formatter. See here: https://docs.python.org/3/library/logging.html#formatter-objects

%(funcName)s is probably what you are looking for

fralk
  • 31
  • 5
  • Thank you for the suggestion. We thought about it indeed. However, we are using the logger already for some other purpose and we specifically want to use print() for these logs. – miguel Aug 08 '23 at 07:28
  • For whoever is interested in using the `logging.Formatter` class. In this page it is explained how to use it: In this page it is explained how to https://stackoverflow.com/questions/57204920/how-to-properly-format-the-python-logging-formatter – miguel Aug 08 '23 at 07:29
0

I found these two alternatives to create a modified version of the print() function. However, that means that the new print function is usable only within the module being executed.

  1. Using decorators
def my_decorator(func):
    def wrapped_func(*args, **kwargs):
        return func("123abc -", *args, **kwargs)
    return wrapped_func

my_print = my_decorator(print)
my_print("My message")
Output: 123abc - My message
  1. Using the bultins
import builtins
def my_print(*args):
    builtins.print("123abc -", *args)

my_print("My message")
Output: 123abc - My message

Update: To modify the print() function saved in the builtins package to have its effects anytime and anywhere print is used (so that the modification only needs to be performed once in the whole script) you can use the code below. I found it in this thread: https://stackoverflow.com/a/13871861/21905824

def modify_print_builtin():
    try:
        import __builtin__ as builtins # Python 2
    except ImportError:
        import builtins # Python 3

    _print = print # keep a local copy of the original print
    builtins.print = lambda *args, **kwargs: _print("123abc -", *args, **kwargs)

modify_print_builtin()
print("My message")
miguel
  • 1
  • 2