Python 2.7
I am currently using multiple lines of code for logging, as below:
timestr = time.strftime("%Y%m%d_%H%M%S")
print timestr
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='D://my_code_3/logging/'+timestr+'_XFR.log',
filemode='w')
#define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
#set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
#tell the handler to use this format
console.setFormatter(formatter)
#add the handler to the root logger
logging.getLogger('').addHandler(console)
name = raw_input("Please enter your name.")
print 'Hi ', name, 'Please go ahead and transfer files - Press Enter'
print
#####
now = datetime.datetime.now()
logging.debug ('File was transferred by:')
logging.debug(name)
logging.debug('The transfer took palce on:')
logging.info(now.strftime("%Y-%m-%d %H:%M"))
I like to rather use a single line some what similar to:
logging.debug (('File was transferred by:'), name)
But this syntax is wrong. Please help me get this right. /or, please suggest me another method to stream data to log file only / to console and log file both.
many thanks. +
You can use string formatting
logging.debug ('File was transferred by: {}'.format(name))
That's clean and readable
Or logging.debug ('File was transferred by: %s' % name)
You can read more about it Python format string syntax docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With