0
import logging
import sys

log_fmt = 'brbuild: %(message)s'
# Initilaize log here
# TODO may need to flush
logging.basicConfig(filename="logtest",
                    level=logging.DEBUG,
                    format=log_fmt,
                    datefmt='%H:%M:%S',
                    filemode='a')

# capture stdout to log
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
log_fmt = logging.Formatter(log_fmt)
ch.setFormatter(log_fmt)
logging.getLogger("logtest").addHandler(ch)

logging.info("using logging")
print "using stdout"

logtest

brbuild: using logging

how can i get "using stdout" to be written in the log as well?

4
  • You have to log it. logging.info("using stdout") Commented Sep 11, 2016 at 18:57
  • @agconti I want to be able to send stdout out the log.... i.e. whatever i am using print it goes to the log. Commented Sep 11, 2016 at 19:06
  • I thought Streamhandler does that but it doesnt seem to be working.. Commented Sep 11, 2016 at 19:07
  • @valentjedi yes the second answer works! Commented Sep 11, 2016 at 19:20

2 Answers 2

0

That's a kind of a hack but you could redefine print in the current module, and others module could perform a from foo import print to be able to use it.

For simplicity's sake, I haven't used file handles in that example, but stdout/stderr. If you use files, you can still add a sys.stdout.write(msg+os.linesep) statement to your new print function.

my new print may not be as powerful as the original print but it supports multiple arguments as well.

import logging,sys

def print(*args):
    logger.info(" ".join([str(x) for x in args]))

if __name__ == '__main__':
    logger = logging.getLogger('foo')
    logger.addHandler(logging.StreamHandler(sys.stdout))
    logger.addHandler(logging.StreamHandler(sys.stderr))
    logger.setLevel(logging.INFO)
    a=12
    logger.info('1. This should appear in both stdout and stderr.')
    print("logging works!",a)

(you have to use it with parentheses). Result:

1. This should appear in both stdout and stderr.
1. This should appear in both stdout and stderr.
logging works! 12
logging works! 12
Sign up to request clarification or add additional context in comments.

Comments

-1

If your intention is to redirect the print output (i.e. redirect sys.stdout) to logger, or to both the logger and the standard output, you will need to create a class that mimics a file-like object to do that and assign an instance of that file-like object class to sys.stdout.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.