[英]I don't understand how python logging module reads its execution code
This below is my code下面是我的代码
logging.basicConfig(filename='logging2 text', level=logging.INFO,
format='%(levelname)s:%(message)s')
class Employee:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
@property
def fullname(self):
return('{} {}'.format(self.firstname, self.lastname))
@property
def email(self):
return('{}@gmail.com'.format(self.fullname))
logging.info('Employee info:\nFullname: {}\nEmail: {}'.format(self.fullname, self.email))
emp1 = Employee('Joe', 'Mama')
When I run the program, it creates the file 'logging2 test' but it records no logs, only a blank file although i've already tell the program to record the logs on line 19, logging.info('Employee info:\nFullname: {}\nEmail: {}'.format(self.fullname, self.email))
really could use some explanation.当我运行程序时,它会创建文件“logging2 test”,但它不记录日志,只记录一个空白文件,尽管我已经告诉程序在第 19 行记录日志,
logging.info('Employee info:\nFullname: {}\nEmail: {}'.format(self.fullname, self.email))
确实可以使用一些解释。 Thanks谢谢
There are two issues.有两个问题。 You log after
return
and hence the log line is never reached.您在
return
后登录,因此永远不会到达日志行。
But your code also contains an infinite recursion.但是您的代码还包含无限递归。 This happens because it calls
self.email
inside of the email
property in the logging
line.发生这种情况是因为它在
logging
行的email
属性内调用self.email
。
To break out of this, you need to know what the email address is at the time of the log.要打破这种情况,您需要知道日志时的 email 地址是什么。
@property
def email(self):
email = '{}@gmail.com'.format(self.fullname)
logging.info('Employee info:\nFullname: {}\nEmail: {}'.format(self.fullname, email))
return(email)
This sets email
to a variable inside the of the function and uses that in both the log and the return statements.这
email
设置为 function 内部的变量,并在日志和返回语句中使用该变量。
Then when you access the email property, the log line will show as expected.然后,当您访问 email 属性时,日志行将按预期显示。
print(empl.email)
Logs the following:记录以下内容:
INFO:Employee info:
Fullname: Joe Mama
Email: Joe Mama@gmail.com
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.