13

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.

3
  • Adding a u to a string in Python 3 doesn't do anything. Strings are unicode per default in Python 3 anyway. Commented Jan 28, 2014 at 10:13
  • How do you look at the output .log file when you see your strange character? Have you looked at it in a hex dump of that .log file? (Maybe it's just the log file viewer who is not displaying the utf 8 correctly.) Commented Jan 28, 2014 at 10:15
  • @Alfe, I'm looking at the output file with Pycharm IDE: Settings: File Encodings -> IDE Encoding -> 'UTF-8', 'Autodetect UTF' is checked; Proyect Encoding -> <System Default> Commented Jan 28, 2014 at 10:23

2 Answers 2

24

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @JanneKarila, that works fine. But now, I need to read how it works in Advanced Tutorial; I don't like to use things that I don't know how to use. ;-)
Thank you. I didn't know the FileHandler has to be in array. Here, have my ↑.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.