【问题标题】:Python Logger Invalid Argument for FileHandlerFileHandler 的 Python 记录器参数无效
【发布时间】:2021-12-16 04:28:24
【问题描述】:

您好,当我在 python 中编写以下代码时

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('ThingsSpeakRESTAPI.log')
fh.setLevel(logging.DEBUG)

日志文件以 ThingsSpeakRESTAPI.log 的名称创建

但如果我这样做:

filename = datetime.datetime.now().isoformat()+"LOG.log"
print(filename)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler(filename)
fh.setLevel(logging.DEBUG)

然后我得到以下错误

OSError: [Errno 22] Invalid argument

两者都在 str 那么为什么不使用字符串值的变量,而是本身的字符串值呢??

【问题讨论】:

  • 如果我复制您的代码并打印出来,它会显示:filename = datetime.datetime.now().isoformat()+"LOG.log" print(filename) 结果:2021-11-01T14:02:31.610468LOG.log 文件名不能包含字符 :

标签: python python-3.x windows rest logging


【解决方案1】:

文件名不能包含: 字符。

你可以这样做:

filename = datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.%f")+"LOG.log"

在这里您可以自己格式化字符串,并确保文件名不包含非法字符。

结果:

2021-11-01_14.10.46.091188LOG.log

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2016-02-27
    • 2017-12-05
    相关资源
    最近更新 更多