运行Python脚本作为upstart服务显示不同的时间输出

2024-06-17 08:41:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,它本质上是一个小型的socket服务器,它为我执行一些简单的网络任务,我开始将它作为一个新启动的服务来运行,以跟踪它并管理它是否在运行。为了记录信息,我使用Python内置的日志模块。当作为一个新启动服务运行时,我注意到一个小问题:所有的时间调用都是在GMT中发出的。当它单独运行时(无论是./scriptname.py还是{}),它都使用本地时间,而Python知道本地时间。系统时间设置正确,我只在作为一个新启动服务运行时看到这种行为。有人知道为什么会这样吗?我该怎么解决?在

编辑:相关代码:我有一个helper类,方便地称为helper,它包含一些常用函数(我知道需要更好地组织它,但它很快就被组合在一起)。最值得注意的是我用来设置我的记录器的函数:

class helper:
    log_format = '%(asctime)-25s %(name)-25s %(levelname)-12s %(message)s'

    @staticmethod
    def createLogger(name):
        rotatingFile = logging.handlers.RotatingFileHandler('/var/log/myLog.log', maxBytes=1048576, backupCount=5)
        rotatingFile.setLevel(logging.DEBUG)
        formatter = logging.Formatter(helper.log_format)
        formatter.time = localtime()
        rotatingFile.setFormatter(formatter)
        log = logging.getLogger(name)
        log.setLevel(logging.DEBUG)
        logging.basicConfig(format=helper.log_format, level=logging.DEBUG)
        if not log.handlers:
            log.addHandler(rotatingFile)
        return log

在我的一个班级里,它被这样使用:

^{pr2}$

所有python内部日志工具的使用都非常简单。在我开始注意到这个问题之后,但在我意识到它只在作为服务运行时发生之前,我添加了formatter.time = localtime()。没用。在

以下是我从教程中获得的(非常基本的)新贵配置:

description "Blah blah"
author  "My Name <My Email>"

start on runlevel [234]
stop on runlevel [0156]

exec /path/to/script.py

respawn

Tags: 函数namepydebughelperlogformattime
2条回答

在upstart下检查脚本的环境。localtime()TZ/TZDIR//etc/localtime获取时区信息,“GMT”是硬编码的默认值(请参见glibc源中的time/tzset.c)。环境可能被chrooted或其他限制,并且您的TZ规范可能不起作用。在

作为快速检查,您可以使用strace -o <outfile> -ff start <jobname>来查看python在启动时是否读取了正确的时区文件。在

所以,我想我终于发现了这个问题。我需要设置TZ env var,但我之前没有这样做。将env TZ=/usr/share/zoneinfo/US/Central添加到我的upstart配置中可以纠正它。谢谢大家的帮助!在

相关问题 更多 >