Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python logging: sending StreamHandler to file from command line

Let's say I have a script like the following, and I can't edit it:

import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

handler = logging.StreamHandler()

logger.addHandler(handler)

logger.debug('debug log')
logger.info('info log')
logger.warning('warning log')
logger.error('error log')

later I call this script with:

python log_example.py > file.log

But it isn't populating the file.log file, but outputting the logs in console.

Q: Is there a way to, despite configuring logging handler to StreamHandler, still output the logs into a file from command line?

like image 789
eLRuLL Avatar asked Jan 13 '17 01:01

eLRuLL


People also ask

What is StreamHandler in python logging?

The StreamHandler class, located in the core logging package, sends logging output to streams such as sys. stdout, sys. stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods).

How do you log an exception in Python?

To log an exception in Python we can use logging module and through that we can log the error. Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger.


1 Answers

Try the &> syntax, as in Pijnappel's answer to this question. This redirects all output (not just stdout) to the file.

python log_example.py &> file.log
like image 137
user3558515 Avatar answered Oct 19 '22 00:10

user3558515