There's an issue with logging a binary data to stdout via Apache.

After setting up logging I attempt to log string '\x31\x00':

logging.getLogger().info('\x31\x00')

All running smoothly basically use python console - I see expected:

2011-05-01 22:21:27,430 INFO [test_logging:9][test_logging] 1

But when I personally use logging via Apache and mod_wsgi I recieve traceback:

Traceback (most recent call last):   
    File "/usr/local/lib/python2.6/logging/__init__.py", line 789, in emit
        stream.write(fs % msg) TypeError: write() argument 1 must be string without null bytes, not str

Where's the bug? Where must i search into?

My logging configuration:

[loggers]
keys=root

[formatters]
keys=stdoutFormatter

[handlers]
keys=stdoutHandler

[logger_root]
level=NOTSET
handlers=stdoutHandler

[handler_stdoutHandler]
class=StreamHandler
formatter=stdoutFormatter
args=(sys.stdout,)

[formatter_stdoutFormatter]
format=%(asctime)s %(levelname)s [%(module)s:%(lineno)d][%(funcName)s] %(message)s

Apache version 5.2.16

Python version 5.6.4

Mod_wsgi 2.8

You can only use

logging.getLogger().info('%r', binary_bytes)

also it must do the best factor.

There is nothing wrong with Apache/mod_wsgi - it is simply that console output streams aren't said to be employed for binary data.

The mistake is mentioned immediately: stream.write cannot have a string argument that contains null bytes.

Possibly you need to write a function that converts a string that might contain null bytes (or any other unprintable figures) and replace all of them with computer escape sequences. So passing inside a string like '\x31\x00' would increase the risk for string '1\\x00' being printed.

Or, when the string your're logging is binary data, simply convert each character into its \xDD escape code equivalent. Or simply print every character within the string like a simple two-digit hex code, therefore the entore string is really a drenched like a sequence of hex codes.

You've provided a byte-string whenever a character (Unicode) string is anticipated. Remember, in Python 2.x the "string" type can be a byte-string not really a character string. (This follows C, in which the "char" type can be a byte and 'A' is actually 0x41.) If you are using either the u'string' syntax or even the unicode() built-in directly before logging, which will make sure that only character strings are drenched. For the reason that situation, byte-strings that can't be decoded into character strings using ASCII encoding before logging will enable you to get the best at that time rather than from inside the Apache calls.

To really log byte-strings, so it appears you're thinking of doing, you'll first have to scribe them in some way into (Unicode) character strings. base64 is straightforward to complete however the data will have to be decoded again to become human-readable. I authored a hex-dump function which required us a couple of hrs to obtain the same as I needed it.