logging.debug 的多个参数

ana*_*tta 3 string logging python-2.7

蟒蛇 2.7

我目前使用多行代码进行日志记录,如下所示:

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"))
Run Code Online (Sandbox Code Playgroud)

我更喜欢使用类似于以下内容的单行:

logging.debug (('File was transferred by:'), name)
Run Code Online (Sandbox Code Playgroud)

但是这种语法是错误的。请帮我解决这个问题。/ 或,请建议我另一种方法将数据仅流式传输到日志文件 / 到控制台和日志文件。

非常感谢。+

Che*_* A. 6

您可以使用字符串格式

logging.debug ('File was transferred by: {}'.format(name))
Run Code Online (Sandbox Code Playgroud)

这是干净和可读的

或者 logging.debug ('File was transferred by: %s' % name)

您可以阅读有关它的更多信息Python 格式字符串语法文档

  • -1。即使调试级别关闭,此方法也将执行格式化。请根据此使用格式字符串和位置参数 -> https://docs.python.org/3/library/logging.html#logging.Logger.debug (2认同)