1

While writing a logging function to duplicate the print statements output to a logging file I came up with following idea.

It basically overrides the print function, strips all of the escape sequences out of it and prints the string on screen. For 99% it works flawlessly. However if the original print statement contains an end='' parameter it doesn't seem to pass this to the logging output. Is there a way to fix this ?

if logProgram == True:
    logName_program = str(idCode)+"-program.log"
    logger_program = logging.getLogger('programlog')
    logger_program.setLevel(level=logging.DEBUG)
    logger_program.addHandler(logging.FileHandler(logName_program))

    def print(*args, **kwargs):
        output = " ".join(map(str, args))
        output = remove_ansi_escape_codes(output)
        logger_program.debug(output)
        builtins.print(*args, **kwargs)

Edit (answer below, because the question is closed) :

if logProgram == True:
    logName_program = str(idCode)+"-program.log"
    logger_program = logging.getLogger('programlog')
    logger_program.setLevel(level=logging.DEBUG)
    fh = logging.FileHandler(logName_program)
    logger_program.addHandler(fh)

    def print(*args, **kwargs):
        output = " ".join(map(str, args))
        output = remove_ansi_escape_codes(output)

        if 'end' in kwargs and kwargs['end'] in ['']:
            fh.terminator = ''
        else:
            fh.terminator = '\n'
    
        logger_program.debug(output)

        builtins.print(*args, **kwargs)
HermDP
  • 205
  • 1
  • 6
  • 1
    Sadly, *not* a duplicate of [Log a string without ending newline](https://stackoverflow.com/q/24360917/364696), where one newline is okay, but not two, and they can just `rstrip` it from the string to be logged (in this case, there is no existing newline, and no newline is desired). – ShadowRanger May 11 '23 at 20:33

0 Answers0