文件处理程序的动态文件名

时间:2019-02-14 18:18:52

标签: python-3.x

我正在尝试设置一个记录器,该记录器每次在特定目录中运行该应用程序时都会写入一个新的带有时间戳的日志文件。

例如我想做的是

timestampFilename = time.strftime("runtimelog%b_%d_%Y_%H:%M:%S.txt")
fh = logging.FileHandler(r'C:\my\folder\logs\'+timestampFilename, mode='w')

1 个答案:

答案 0 :(得分:0)

Logging Cookbook开始两周的示例:

import logging
import os
from datetime import datetime

# create logger with 'spam_application'
logger = logging.getLogger('MYAPP')
logger.setLevel(logging.DEBUG)

# create file handler which logs in a specific directory
logdir = '.'
if 'APP_LOG_DIR' in os.environ:
    logdir = os.environ['APP_LOG_DIR']

logfile = datetime.now().strftime("run_%b_%d_%Y_%H_%M_%S.log")

fh = logging.FileHandler(os.path.join(logdir, logfile))
fh.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('[%(asctime)s][%(name)s][%(levelname)s] %(message)s')
fh.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(fh)

logger.debug("my first log line")

可以使用环境变量APP_LOG_DIR配置日志目录,并借助os.path以独立于平台的方式构建路径名。

相关问题