I use logging library in python via conf file setting from this link https://realpython.com/python-logging/ and I write this codes:
log.conf.conf :
[loggers]
keys=root, sampleLogger
[handlers]
keys= consoleHandler, fileHandler
[formatters]
keys=fileFormatter, consoleFormatter
[logger_root]
level=DEBUG
handlers=fileHandler,consoleHandler
[logger_sampleLogger]
level=DEBUG
handlers=consoleHandler
qualname=sampleLogger
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=consoleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=handlers.TimedRotatingFileHandler
interval=midnight
backupCount=5
formatter=fileFormatter
level=DEBUG
args=('../logs/log.log',)
[formatter_fileFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
[formatter_consoleFormatter]
format=%(message)s
main.py:
logging.config.fileConfig(fname='../configs/log_conf.conf',
disable_existing_loggers=False)
logger = logging.getLogger('main')
logger.info('Hello')
logger.info('سلام')
Logging string that contains English chars likes "Hello" works without any problem. But string "سلام" that contains Persian/Arabic chars raise exception:
--- Logging error ---
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 1028, in emit
stream.write(msg + self.terminator)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 40-43: character maps to <undefined>
Call stack:
File "D:/Alireza/Code/addresstomaplocation/main/main.py", line 11, in <module>
logger.info('سلام')
Message: 'سلام'
Arguments: ()
So I tried "utf-8" decoding and this way working but clearly logs file isn't readable for human:
logger.info('سلام'.encode('utf-8'))
outputs in log file:
2020-09-16 18:55:00,949 - main - INFO - b'\xd8\xb3\xd9\x84\xd8\xa7\xd9\x85'
My question is "There is any way for writing in logs file with Persian chars without encoding for human readability?"