无法在while循环中调用日志记录

时间:2019-10-14 15:46:50

标签: python python-3.x

这是一个守护程序,可充当树莓派上的电窑控制器。我只想在实际设置为运行时开始记录日志,而不是仅在等待运行时开始记录日志。这样,我可以通过RunID记录运行的每个窑炉,而不仅仅是拥有一个通用名称的日志文件。

如果我在while和if语句之外设置了日志代码,则可以正常工作。如果我在while和if语句中设置它,则永远不会创建日志文件。我在两个地方使用完全相同的代码来检查功能。

将其放置在文件的开头(紧随import语句下方)时有效。

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

没有错误消息,只是从未创建过日志。我知道它实际上正在这部分代码中运行,因为我紧随其后放置了打印功能并进行了打印。

我可以创建一个备用文件并将所有消息记录到该文件中,但是使用日志记录功能会很好。

1 个答案:

答案 0 :(得分:0)

您是正确的,在此情况下,无法调用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命名约定一样。

相关问题