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?

ealeon
  • 12,074
  • 24
  • 92
  • 173

2 Answers2

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
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
-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.

J Earls
  • 1,792
  • 8
  • 12