0

我第一次使用 Python 'logging' 模块,目前,我正在尝试使用“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

请建议。谢谢你。

4

1 回答 1

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")
于 2019-03-25T09:18:35.660 回答