这是一个守护进程,在树莓派上充当电窑 Controller 。我只想在它实际设置为运行时开始记录,而不是在它只是等待运行时开始记录。这样,我可以通过 RunID 记录每个单独的 kiln 运行情况,而不仅仅是一个通用命名的日志文件。
如果我在 while 和 if 语句之外设置日志代码,它可以正常工作。如果我将其设置在 while 和 if 语句内,则永远不会创建日志文件。我在两个地方都使用了完全相同的代码来检查功能。
当放置在文件开头、导入语句下方时,此方法有效。
#--- Set up logging ---
LogFile = time.strftime(AppDir + '/log/%H_%M_%d_%m_%Y_pilnfired.log')
#LogFile = time.strftime(AppDir + '/log/%(asctime)s.log')
L.basicConfig(filename=LogFile,
#comment to disable
level=L.DEBUG,
format='%(asctime)s %(message)s'
)
如果在此之后不起作用...
while 1:
#ReadTmp = TempRise
ReadTmp = Sensor0.read_temp_c()
ReadITmp = Sensor0.read_internal_temp_c()
# roomTmp = Sensor1.read_temp_c()
# roomITmp = Sensor1.read_internal_temp_c()
while math.isnan(ReadTmp):
#ReadTmp = TempRise
ReadTmp = Sensor0.read_temp_c()
print (' "kilntemp": "' + str(int(ReadTmp)) + '",\n')
L.debug("Write status information to status file %s:" % StatFile)
sfile = open(StatFile, "w+")
sfile.write('{\n' +
' "proc_update_utime": "' + str(int(time.time())) + '",\n'
+ ' "readtemp": "' + str(int(ReadTmp)) + '",\n'
+ ' "run_profile": "none",\n'
+ ' "run_segment": "n/a",\n'
+ ' "ramptemp": "n/a",\n'
+ ' "status": "n/a",\n'
+ ' "targettemp": "n/a"\n'
+ '}\n'
)
sfile.close()
# --- Check for 'Running' firing profile ---
sql = "SELECT * FROM profiles WHERE state=?;"
p = ('Running',)
SQLCur.execute(sql, p)
Data = SQLCur.fetchall()
#--- if Running profile found, then set up to fire, woowo! --
if len(Data) > 0:
RunID = Data[0]['run_id']
Kp = float(Data[0]['p_param'])
Ki = float(Data[0]['i_param'])
Kd = float(Data[0]['d_param'])
L.info("RunID: %d" % (RunID))
StTime = time.strftime('%Y-%m-%d %H:%M:%S')
sql = "UPDATE profiles SET start_time=? WHERE run_id=?;"
p = (StTime, RunID)
try:
SQLCur.execute(sql, p)
SQLConn.commit()
except:
SQLConn.rollback()
LogFile = time.strftime(AppDir + '/log/%H_%M_%d_%m_ %Y_pilnfired.log')
#LogFile = time.strftime(AppDir + '/log/%(asctime)s.log')
L.basicConfig(filename=LogFile,
#comment to disable
level=L.DEBUG,
format='%(asctime)s %(message)s'
)
Do more stuff...
没有错误消息,只是从未创建日志。我知道它实际上正在运行这部分代码,因为我在后面放置了一个打印函数并打印了它。
我可以创建一个替代文件并将所有消息记录到其中,但最好使用日志记录功能。
最佳答案
您是对的,在这种情况下调用 basicConfig()
不起作用。相反,您必须在每个循环中创建一个新的处理程序并将其替换为旧的处理程序。
import logging
# create a formatter
formatter = logging.Formatter('%(asctime)s %(message)s')
# get a logger
logger = logging.getLogger()
for i in range(1, 5):
# remove any old handlers
for old_handler in logger.handlers:
logger.removeHandler(old_handler)
# create a new handler
new_filename = 'log' + str(i)
file_handler = logging.FileHandler(filename=new_filename, mode='a')
file_handler.setFormatter(formatter)
# add the handler and use it
logger.addHandler(file_handler)
logger.warning('some message')
代码基于this回答。
另一方面,使用 logging
而不是 L
会更具可读性,就像坚持其他 PEP8 命名约定一样。
关于python - 无法在 while 循环内调用日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58380110/