如何使用当前日期创建日志文件logging.handlers.TimeDrotingFileHand

2024-04-20 15:52:15 发布

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

我每小时运行一次任务列表,但我希望获得按当前日期命名的日志文件。在

def get_mylogger():
    # get logger
    fmt = '%(asctime)-15s %(levelname)-4s %(message)s'
    datefmt = '%Y-%m-%d %H:%M:%S'

    mylogger = logging.getLogger()
    mylogger.setLevel(logging.INFO)

    # log_path = "/opt/spark/logs/pyspark/"
    log_path = "H:\upupw\www\spark\logs\pyspark"
    if not os.path.exists(log_path):
        os.makedirs(log_path)
    log_file_name = 'spark.log'
    log_name = os.path.join(log_path, log_file_name)

    # TimedRotatingFileHandler
    timer = TimedRotatingFileHandler(log_name, when='D')

    formatter = logging.Formatter(fmt, datefmt=datefmt)
    timer.setFormatter(formatter)
    mylogger.addHandler(timer)

    return mylogger

如果我创建第一个日志文件'火花.log'在'10:00:00'中,但它在明天'10:00:00'之前不会创建新文件。我想要的是明天在0创建一个新文件!在


Tags: 文件pathnameloggetosloggingspark
1条回答
网友
1楼 · 发布于 2024-04-20 15:52:15

根据logging documentation for TimedRotatingFileHandler,您可能希望在TimedRotatingFileHandler函数调用中使用附加参数atTime,如下所示:

timer = TimedRotatingFileHandler(log_name, when='D', atTime=datetime.time(0, 0, 0))

如文件所述:

If atTime is not None, it must be a datetime.time instance which specifies the time of day when rollover occurs, for the cases where rollover is set to happen “at midnight” or “on a particular weekday”. Note that in these cases, the atTime value is effectively used to compute the initial rollover, and subsequent rollovers would be calculated via the normal interval calculation.

…您需要提供滚动时间作为datetime.time()的实例。这是通过将所需的滚动时间作为参数传递给datetime.time class来完成的。将小时作为第一个参数,分钟作为第二个参数,秒作为第三个参数。上面的示例将滚动时间设置为00:00:00。在

注意:一定要

^{pr2}$

在你的代码开头。在

相关问题 更多 >