Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple arguments to logging.debug

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. +

like image 521
anatta Avatar asked Dec 23 '22 14:12

anatta


1 Answers

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

like image 91
Chen A. Avatar answered Feb 01 '23 14:02

Chen A.