Anonymous
Anonymous

Reputation: 4632

Python logging special characters to file throws exception

I have a logger which logs to file but occasionally when it encounters TM characters it throws an exception and the entry is not logged.

logging.basicConfig(filename='C:/Users/Administrator/Desktop/logs/log.log',
    level=logging.INFO, 
    format='%(asctime)s - %(message)s') 

What's wrong with it?

Edit:

Those are time and message obviously. The message is being received from google chrome via websocket as a stringified object {log: log} which is then parsed using data=json.loads(obj). Then data["log"] string goes into message.

Upvotes: 1

Views: 3266

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308138

Instead of allowing logger to open the file, open it yourself and specify an encoding that can handle the character.

logfile = open('C:/Users/Administrator/Desktop/logs/log.log', 'a', encoding='utf-8')
logging.basicConfig(stream=logfile,
    level=logging.INFO, 
    format='%(asctime)s - %(message)s')

Upvotes: 4

Related Questions