Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging: unicode symbols is unicode-escaped [duplicate]

Tags:

python

I want to log requests responses to file, but when i use getLogger().warning(string), following string is being unicode-escaped Example:

r = requests.post(...)
result = json.loads(r.text)  # Now result == '{"error": "Ошибка 1"}'
getLogger().warning(json.dumps(result))

This code will write to log file unicode-escaped string, where "Ошибка" will be written like "\u0417\u0430\u043a\u0430\u0437..." But i want to see these characters as is.

like image 529
Pavel Shishmarev Avatar asked Sep 10 '25 23:09

Pavel Shishmarev


1 Answers

Your issue is that json.dumps is converting the Unicode to ASCII by escaping it. This can be avoided by adding an extra parameter, ensure_ascii=False, to the .dumps function:

r = requests.post(...)
result = json.loads(r.text)  # Now result == {"error": "Ошибка 1"}
getLogger().warning(json.dumps(result, ensure_ascii=False))

You can check the documentation for other arguments to the json.dumps function.

like image 143
Anuvab Mohanty Avatar answered Sep 12 '25 13:09

Anuvab Mohanty