bluenote10
bluenote10

Reputation: 26710

Does Python logging write to stdout or stderr by default?

The logging docs don't mention what the default logger obtained from basicConfig writes to: stdout or stderr.

What is the default behavior?

Upvotes: 21

Views: 7851

Answers (2)

snakecharmerb
snakecharmerb

Reputation: 55799

If no filename argument is passed to logging.basicconfig it will configure a StreamHandler. If a stream argument is passed to logging.basicconfig it will pass this on to StreamHandler otherwise StreamHandler defaults to using sys.stderr as can be seen from the StreamHandler docs

class logging.StreamHandler(stream=None)

Returns a new instance of the StreamHandler class. If stream is specified, the instance will use it for logging output; otherwise, sys.stderr will be used.

and the source code:

class StreamHandler(Handler):
    """
    A handler class which writes logging records, appropriately formatted,
    to a stream. Note that this class does not close the stream, as
    sys.stdout or sys.stderr may be used.
    """

    def __init__(self, stream=None):
        """
        Initialize the handler.
        If stream is not specified, sys.stderr is used.
        """
        Handler.__init__(self)
        if stream is None:
            stream = sys.stderr
        self.stream = stream

Upvotes: 13

bluenote10
bluenote10

Reputation: 26710

Apparently the default is stderr.

A quick check: Using a minimal example

import logging
logger = logging.getLogger(__name__)

logging.basicConfig(level=logging.INFO)
logger.info("test")

and running it with python test.py 1> /tmp/log_stdout 2> /tmp/log_stderr results in an empty stdout file, but a non-empty stderr file.

Upvotes: 11

Related Questions