4
votes

I'm upgrading a python 2.7 code to python 3.6, but every time I'm trying to write something on console using logging I get this error

TypeError: a bytes-like object is required, not 'str'

I've read most of the similiar questions with this but none of them has worked.

# mainTest.py module
from config import logger
log = logger.getLogger(__file__)

def function():
    message = "testing"
    log.info(message)
    # code
# logger.py
import logging
import os
import classpathDir as cf


def getLogger(loggerForFile):
    logger = logging.getLogger(os.path.basename(loggerForFile))
    if not logger.handlers:
        logging.basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                            datefmt='%d/%m/%Y %I:%M:%S %p', filename=cf.ROOT_DIR + "/output/processing.log",
                            filemode='wb', level=logging.DEBUG)
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        # set a format which is simpler for console use
        formatter = logging.Formatter('%(asctime)s %(name)-12s: %(levelname)-8s %(message)s',
                                      datefmt='%d/%m/%Y %I:%M:%S')
        # tell the handler to use this format
        console.setFormatter(formatter)
        # add the handler to the root logger
        logger.addHandler(console)
    return logger


if __name__ == '__main__':
    print("Logging config module")

When I was using this very same code on python2.7 i got this output:

22/05/2019 01:38:11 mainTest.py   : INFO     testing

On python 3.6 with the same code I got this error:

22/05/2019 03:17:59 mainRF.py   : INFO     testing
--- Logging error ---
Traceback (most recent call last):
  File "/usr/lib/python3.6/logging/__init__.py", line 996, in emit
    stream.write(msg)
TypeError: a bytes-like object is required, not 'str'
Call stack:
  File "mainTest.py", line 126, in <module>
    run_combinations()
  File "mainTest.py", line 20, in run_combinations
    log.info(message)
Message: 'testing'
Arguments: ()
1
Your code just executes fine on my setup.. Python 3.7.3 x64..Anvesh Yalamarthy
Can you put the full stack trace in your question.Tech at The Sparks Foundation
Done. Added the full stack traceGabriel Michelassi
I'm guessing that the placeholder "some code to set a format which is simpler for console use" is installing a formatter that is not returning the correct type.Mark A
Just updated the question with the missing codeGabriel Michelassi

1 Answers

1
votes

When setting logging basic config I changed python filemode='wb' to python filemode='w' and it worked properly.