How to encode log file?

Question:

My code:

logging.warning('FASE VALIDACIÓN TITULOS DE COLUMNAS DE DATOS NO SUPERADA. compruebe los nombres de los títulos de las columnas en datos.csv)')

Output in .log file:

WARNING:root:FASE VALIDACI�N TITULOS DE COLUMNAS DE DATOS NO SUPERADA. compruebe los nombres de los t�tulos de las columnas en datos.csv)

Then I tried this:

logging.basicConfig(filename=nombreFicheroLog, encoding="utf-8", level=logging.DEBUG)

But it does not work. Then I tried this one:

logging.warning(u'FASE VALIDACIÓN TITULOS DE COLUMNAS DE DATOS NO SUPERADA. compruebe los nombres de los títulos de las columnas en datos.csv)')

But the output is the same.

How I can encode the .log file to support UTF-8?

P.S. I’m using Python3.

Asked By: Trimax

||

Answers:

basicConfig does not take an encoding argument, but in Python 3.3 you can do this instead:

logging.basicConfig(handlers=[logging.FileHandler(nombreFicheroLog, 'w', 'utf-8')], 
                    level=logging.DEBUG)

For older Pythons, see this question.

Answered By: Janne Karila

Since Python3.9 you can set encoding in logging.basicConfig:
https://docs.python.org/3.9/library/logging.html#logging.basicConfig

For previous versions you also can configure a stream with ‘utf-8’ encoding, without explicitly using handler:

logging.basicConfig(stream=open(nombreFicheroLog, 'w', encoding='utf-8', level=logging.DEBUG)

source: https://github.com/python/cpython/issues/81292 (https://bugs.python.org/issue37111)

Answered By: nikioa