开发者

Django Logging i18n ugettext_lazy Variables

I'm having trouble logging the output of an internationalized django variable.

My application code used the 'message' vaiable OK and it displays in English and German (the two languages I am working with)

My problem is when I try to make a log of the said 'message' variable output. I want to log in English and/or German (depending on what the end user is seeing)

I'm using string_concat and it says:

the lazy translations in result will only be converted to strings when result itself is used in a string (usually at template rendering time).

Here is a code sample:

from django.utils.translation import ugettext_lazy as _
from django.utils.translation import string_concat

message = _('Profile Updated OK')

# Build a log message
fmt_msg = _(message)
log_message = 'Message Sent: '
log_message = string_concat(log_message, fmt_msg)

logger.info(log_message)

The log entry is not translated:

Message Sent: <django.utils.functional.__proxy__ object at 0x9c3c4ac>

Can anyone suggest ho开发者_高级运维w I can have the proxy object to be translated when used with logging?

It's translating OK in my regular Django code just the logging.info() issue.

Cheers!


From the docs:

The result of a ugettext_lazy() call can be used wherever you would use a unicode string (an object with type unicode) in Python. If you try to use it where a bytestring (a str object) is expected, things will not work as expected, since a ugettext_lazy() object doesn't know how to convert itself to a bytestring.

Also, don't call _() twice.

logger.info(u'Message Sent: %s' % message)


You have to force Unicode strings, as documented in http://www.djangobook.com/en/2.0/chapter19/

u"Hello %s" % ugettext_lazy("people")

And do not call the function twice ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜