Convert unicode data to utf-8 before calling syslog.syslog()

Without this patch no conversion was taking place and message containing
special characters were raising TypeError exceptions. Just like the following
example:

>>> import syslog
>>> syslog.syslog(syslog.LOG_DEBUG, u"kaboom")
>>> syslog.syslog(syslog.LOG_DEBUG, u"François Deppierraz")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: [priority,] message string
>>>

Change-Id: I7557e016e8b9894033953bee689c79484c4a11f3
Closes-Bug: #1483842
This commit is contained in:
Francois Deppierraz 2016-05-27 15:06:00 +02:00
parent ea4b9d0105
commit 93dd44f857
2 changed files with 19 additions and 3 deletions

View File

@ -19,6 +19,7 @@ try:
import syslog
except ImportError:
syslog = None
from oslo_utils import encodeutils
NullHandler = logging.NullHandler
@ -52,9 +53,11 @@ if syslog is not None:
syslog.openlog(binary_name, 0, facility)
def emit(self, record):
syslog.syslog(self.severity_map.get(record.levelname,
syslog.LOG_DEBUG),
self.format(record))
priority = self.severity_map.get(record.levelname,
syslog.LOG_DEBUG)
message = encodeutils.safe_encode(self.format(record))
syslog.syslog(priority, message)
class ColorHandler(logging.StreamHandler):

View File

@ -1,3 +1,5 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
@ -259,6 +261,17 @@ class OSSysLogHandlerTestCase(BaseTestCase):
log._find_facility,
"fougere")
def test_syslog(self):
msg_unicode = u"Benoît Knecht & François Deppierraz login failure"
msg_utf8 = msg_unicode.encode('utf-8')
handler = handlers.OSSysLogHandler()
syslog.syslog = mock.Mock()
handler.emit(
logging.LogRecord("name", logging.INFO, "path", 123,
msg_unicode, None, None))
syslog.syslog.assert_called_once_with(syslog.LOG_INFO, msg_utf8)
class LogLevelTestCase(BaseTestCase):
def setUp(self):