如何在python logging.basicConfig中使用TimedRotatingFileHandler作为文件名?

时间:2019-03-25 09:04:16

标签: python-3.6 python-logging

我第一次使用Python的“日志记录”模块,目前正在尝试使用“ logging.basicConfig()”生成一些示例日志文件。我的主要目的是生成名称为“ dd-mm-YY_.log”的日期的示例日志文件。经过一些初步的研究,我发现我们可以使用“ TimedRotatingFileHandler”来完成这项工作。以下是Stackoverflow帖子之一中的示例代码

from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile',  when='midnight')
fh.suffix = '%Y_%m_%d.log'

但是我无法从TimedRotatingFileHandler()函数中的“ logging.basicConfig”中确定如何使用“格式”和“级别”。

下面是我编写的整个python代码:

import logging
from logging.handlers import TimedRotatingFileHandler
log = logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', filename='log.txt', level=logging.INFO)
try:
    var = TimedRotatingFileHandler(log, when='midnight')
    var.suffix = '%y_%m_$d.log'
except Exception as e:
    print("expected str")
    logging.exception(e)

print(" ")
print("This is a Logging demo")
print(" ")
logging.info("new request came")
print(" ")
try:
    x = int(input("Enter the first number: "))
    y = int(input("Enter the second number: "))
    print(x / y)
except ZeroDivisionError as msg:
    print("cannot divide with zero")
    logging.exception(msg)
    print(" ")
except ValueError as msg:
    print("enter only integer value")
    logging.exception(msg)
    print(" ")
logging.info("executed successfully")

在上面的代码中,一切正常,直到我希望在程序中引入“ TimedRotatingFileHandler”。

以下是我在log.txt中收到的错误

2019-03-25 14:14:00,528:ERROR:expected str, bytes or os.PathLike object, not NoneType
Traceback (most recent call last):
  File "/Users/amitesh/PycharmProjects/Automation/Databases/DB_Conn.py", line 17, in <module>
    var = TimedRotatingFileHandler(log, when='midnight')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/handlers.py", line 202, in __init__
    BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/handlers.py", line 57, in __init__
    logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 1019, in __init__
    filename = os.fspath(filename)
TypeError: expected str, bytes or os.PathLike object, not NoneType
2019-03-25 14:14:00,530:INFO:new request came

从上述错误中可以很明显地看出,我无法正确地放置逻辑。

新日志结构

executed successfully
new request came
executed successfully
new request came
invalid literal for int() with base 10: ''
Traceback (most recent call last):
  File "/Users/amitesh/PycharmProjects/Automation/Databases/DB_Conn.py", line 61, in <module>
    y = int(input("Enter the second number: "))
ValueError: invalid literal for int() with base 10: ''
executed successfully
new request came
new request came
division by zero
Traceback (most recent call last):
  File "/Users/amitesh/PycharmProjects/Automation/Databases/DB_Conn.py", line 62, in <module>
    print(x / y)
ZeroDivisionError: division by zero
executed successfully
new request came
invalid literal for int() with base 10: 'er'
Traceback (most recent call last):
  File "/Users/amitesh/PycharmProjects/Automation/Databases/DB_Conn.py", line 61, in <module>
    y = int(input("Enter the second number: "))
ValueError: invalid literal for int() with base 10: 'er'
executed successfully
new request came
executed successfully
new request came

建议。 谢谢。

1 个答案:

答案 0 :(得分:0)

好的,我找到了答案,下面是修改后的代码:

import logging
from logging.handlers import TimedRotatingFileHandler
LOGGING_MSG_FORMAT = '%(name)-14s > [%(levelname)s] [%(asctime)s] : %(message)s'
LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'

logging.basicConfig(level=logging.DEBUG, format=LOGGING_MSG_FORMAT, datefmt=LOGGING_DATE_FORMAT)
root_logger = logging.getLogger('')
logger = logging.handlers.TimedRotatingFileHandler('amitesh.log', 'midnight', 1)
root_logger.addHandler(logger)
while True:
    print(" ")
    print("This is a Logging demo")
    print(" ")
    logging.info("new request came")
    print(" ")
    try:
        x = int(input("Enter the first number: "))
        y = int(input("Enter the second number: "))
        print(x / y)
    except ZeroDivisionError as msg:
        print("cannot divide with zero")
        logging.exception(msg)
        print(" ")
    except ValueError as msg:
        print("enter only integer value")
        logging.exception(msg)
        print(" ")
    logging.info("executed successfully")