使用模块设置日志记录的pythonic方法

时间:2018-03-20 13:47:17

标签: python logging

我写了一个简单的bot.py来定义一个记录器。记录器工作正常。

但后来我需要继续保存bot.py脚本,所以我写了一个keepalive.py,每小时调用一次,并使用套接字来识别bot.py何时死亡,然后重新启动它。

但我没有看到在keepalive.pybot.py之间设置和共享记录器的正确/ pythonic方式。

我尝试将记录器实例从bot.py调用时将其传递给keepalive.py,否则创建它(如果直接运行bot.py),但它需要我将记录器作为参数传递给我调用的所有函数(例如,demo()函数)。这很糟糕。

设置记录器的最佳方法是什么,然后在其他地方使用它而不需要做太多的传递等等?

bot.py

import logging

def demo():
    #this won't work unless I pass in the logger as a parameter
    #logger.info("demonstrate the Inner demo() called from Inner main works")
    pass

def main(logger=None):
    if logger is None:
        # Enable logging
        logging.basicConfig(
            filename='log_experiment.txt',
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.INFO)
        logger = logging.getLogger(__name__)
        logger.info("I created logger instance inside Inner Main()")
    else:
        logger.info("I am using the logger passed to Inner main() as a parameter")

    demo()

if __name__ == "__main__":
    main()

keepalive.py

import logging
import socket
import sys


# Enable logging
logging.basicConfig(
    filename='log_experiment.txt',
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("I created logger instance inside keepalive")

lock_socket = None  # we want to keep the socket open until the very end of
                    # our script so we use a global variable to avoid going
                    # out of scope and being garbage-collected



def is_lock_free():
    global lock_socket
    lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    try:
        lock_id = "straits.keepalive"   # this should be unique. using your username as a prefix is a convention
        lock_socket.bind('\0' + lock_id)
        logging.debug("Acquired lock %r" % (lock_id,))
        return True
    except socket.error:
        # socket already locked, task must already be running
        logging.info("Failed to acquire lock %r" % (lock_id,))
        return False

if not is_lock_free():
    print("alive")
    sys.exit()

print("**RESTART REQUIRED")
# then, either include the rest of your script below,
# or import it, if it's in a separate file:
import inner as bot

bot.main(logger)

0 个答案:

没有答案
相关问题