【问题标题】:Can't call logging inside while loop无法在while循环中调用日志记录
【发布时间】:2020-02-11 06:36:09
【问题描述】:

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

如果我在 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 应该不在while 循环中。在基本配置到位之前,没有配置日志记录吗?通常,人们将日志记录配置为他们主模块中的第一步......

标签: python python-3.x


【解决方案1】:

你是对的,在这种情况下调用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 命名约定一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 2017-11-24
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多