Python3-了解fileConfig的工作方式

时间:2019-06-21 15:16:10

标签: python-3.x

我正在尝试用Python登录,下面是我的目录结构。

.
├── __pycache__
│   ├── constants.cpython-37.pyc
│   ├── logging_formatter.cpython-37.pyc
│   └── test_logging.cpython-37-PYTEST.pyc
├── employee
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-37.pyc
│   │   └── employee.cpython-37.pyc
│   └── employee.py
├── logging.conf
└── start_logging.py

3 directories, 9 files

我的logging.conf文件如下:

[loggers]
keys=mainlogger, Employee.employee

[handlers]
keys=employeeHandler, rootHandler

[formatters]
keys=employee_formatter, root_formatter

[logger_mainlogger]
level=DEBUG
handlers=rootHandler

[logger_Employee.employee]
level=INFO
handlers=employeeHandler
propagate=0

[handler_employeeHandler]
class=FileHandler
level=INFO
formatter=employee_formatter
args=('employee.log',)

[handler_rootHandler]
class=StreamHandler
level=DEBUG
formatter=root_formatter

[formatter_employee_formatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

[formatter_root_formatter]
format=%(name)s - %(levelname)s - %(message)s

我的Employee.employee类:

import logging

logger = logging.getLogger(__name__)
logger.propagate = False
handler = logging.FileHandler(filename='employee.log')
format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(format)
logger.addHandler(handler)

class Employee:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

        logger.info(f"Created new employee with {firstname} and {lastname}")

这是我的主要功能:

import logging
import logging.config


logging.config.fileConfig('logging.conf')
logger = logging.getLogger('mainlogger')


from employee import employee


def add(x, y):
    return x + y

def multiply(x, y):
    return x * y


if __name__ == '__main__':
    x = 10
    y = 20
    logger.debug(f"The result of adding numbers {x} and {y} are {add(x, y)}")

    logger.debug(f"The result of multiplying numbers {x} and {y} are {multiply(x, y)}")

    employee.Employee("Subhayan", "Bhattacharya")

    employee.Employee("Shaayan", "Bhattacharya")

当我运行start_logging.py文件时,出现了这个奇怪的错误。

Traceback (most recent call last):
  File "start_logging.py", line 5, in <module>
    logging.config.fileConfig('logging.conf')
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 80, in fileConfig
    _install_loggers(cp, handlers, disable_existing_loggers)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 189, in _install_loggers
    llist.remove("root")
ValueError: list.remove(x): x not in list

有人可以告诉我这里出了什么问题吗?我不太了解Python日志记录。

0 个答案:

没有答案