logging.config, attributeerror: type object 'filehandler' has no attribute 'split'

  • Last Update :
  • Techknowledgy :

Code:

import logging
import logging.config

verbose_formatter_conf = {
   "format": "%(asctime)-15s %(name)s %(levelname)-9s %(message)s",
}

formatters_dict = {
   "verbose_formatter": verbose_formatter_conf,
}

logfile_handler_conf = {
   "class": logging.FileHandler,
   "level": logging.DEBUG,
   "formatter": "verbose_formatter",
   "filename": "logfile.txt",
   "mode": "w",
   "encoding": "utf-8",
}

handlers_dict = {
   "logfile_handler": logfile_handler_conf,
}

verbose_file_logger_conf = {
   "propagate": True,
   "handlers": ["logfile_handler"]
}

loggers_dict = {
   "verbose_file_logger": verbose_file_logger_conf
}

final_conf = {
   "version": 1,
   "formatters": formatters_dict,
   "handlers": handlers_dict,
   "loggers": loggers_dict,
   "incremental": False,
}

logging.config.dictConfig(final_conf)
logger = logging.getLogger(__name__)

logger.debug("hello")

The error it throws is:

Traceback (most recent call last):
File "C:\Program Files\Python37\lib\logging\config.py", line 555, in configure
handler = self.configure_handler(handlers[name])
File "C:\Program Files\Python37\lib\logging\config.py", line 705, in configure_handler
klass = self.resolve(cname)
File "C:\Program Files\Python37\lib\logging\config.py", line 372, in resolve
name = s.split('.')
AttributeError: type object 'FileHandler' has no attribute 'split'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "c:\Users\Tejul\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\ptvsd_launcher.py", line 43, in <module>
   main(ptvsdArgs)
   File "c:\Users\Tejul\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\lib\python\ptvsd\__main__.py", line 434, in main
   run()
   File "c:\Users\Tejul\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\lib\python\ptvsd\__main__.py", line 312, in run_file
   runpy.run_path(target, run_name='__main__')
   File "C:\Program Files\Python37\lib\runpy.py", line 263, in run_path
   pkg_name=pkg_name, script_name=fname)
   File "C:\Program Files\Python37\lib\runpy.py", line 96, in _run_module_code
   mod_name, mod_spec, pkg_name, script_name)
   File "C:\Program Files\Python37\lib\runpy.py", line 85, in _run_code
   exec(code, run_globals)
   File "g:\Sven\Python\pygtris\logger_conf.py", line 42, in <module>
      logging.config.dictConfig(final_conf)
      File "C:\Program Files\Python37\lib\logging\config.py", line 792, in dictConfig
      dictConfigClass(config).configure()
      File "C:\Program Files\Python37\lib\logging\config.py", line 563, in configure
      '%r' % name) from e
      ValueError: Unable to configure handler 'logfile_handler'

Suggestion : 2

The error seems to be that the "class" anycodings_python value in the logfile_handler_conf anycodings_python dictionary is supposed to be a string, anycodings_python "logging.FileHandler", rather than the anycodings_python FileHandler class itself.,QueryDSL Predicate for use with JPARepository where field is a JSON String converted using an AttributeConverter to a List&lt;Object&gt;,Anaconda Navigator won't start : (Navigator Error) expected str, bytes or os.PathLike object, not NoneType,How to add an item to list in setter and notify one by one with provider in Flutter?

Code:

import logging
import logging.config

verbose_formatter_conf = {
   "format": "%(asctime)-15s %(name)s %(levelname)-9s %(message)s",
}

formatters_dict = {
   "verbose_formatter": verbose_formatter_conf,
}

logfile_handler_conf = {
   "class": logging.FileHandler,
   "level": logging.DEBUG,
   "formatter": "verbose_formatter",
   "filename": "logfile.txt",
   "mode": "w",
   "encoding": "utf-8",
}

handlers_dict = {
   "logfile_handler": logfile_handler_conf,
}

verbose_file_logger_conf = {
   "propagate": True,
   "handlers": ["logfile_handler"]
}

loggers_dict = {
   "verbose_file_logger": verbose_file_logger_conf
}

final_conf = {
   "version": 1,
   "formatters": formatters_dict,
   "handlers": handlers_dict,
   "loggers": loggers_dict,
   "incremental": False,
}

logging.config.dictConfig(final_conf)
logger = logging.getLogger(__name__)

logger.debug("hello")

The error it throws is:

Traceback (most recent call last):
File "C:\Program Files\Python37\lib\logging\config.py", line 555, in configure
handler = self.configure_handler(handlers[name])
File "C:\Program Files\Python37\lib\logging\config.py", line 705, in configure_handler
klass = self.resolve(cname)
File "C:\Program Files\Python37\lib\logging\config.py", line 372, in resolve
name = s.split('.')
AttributeError: type object 'FileHandler' has no attribute 'split'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "c:\Users\Tejul\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\ptvsd_launcher.py", line 43, in <module>
   main(ptvsdArgs)
   File "c:\Users\Tejul\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\lib\python\ptvsd\__main__.py", line 434, in main
   run()
   File "c:\Users\Tejul\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\lib\python\ptvsd\__main__.py", line 312, in run_file
   runpy.run_path(target, run_name='__main__')
   File "C:\Program Files\Python37\lib\runpy.py", line 263, in run_path
   pkg_name=pkg_name, script_name=fname)
   File "C:\Program Files\Python37\lib\runpy.py", line 96, in _run_module_code
   mod_name, mod_spec, pkg_name, script_name)
   File "C:\Program Files\Python37\lib\runpy.py", line 85, in _run_code
   exec(code, run_globals)
   File "g:\Sven\Python\pygtris\logger_conf.py", line 42, in <module>
      logging.config.dictConfig(final_conf)
      File "C:\Program Files\Python37\lib\logging\config.py", line 792, in dictConfig
      dictConfigClass(config).configure()
      File "C:\Program Files\Python37\lib\logging\config.py", line 563, in configure
      '%r' % name) from e
      ValueError: Unable to configure handler 'logfile_handler'

Suggestion : 3

If an error is encountered during configuration, this function will raise a ValueError, TypeError, AttributeError or ImportError with a suitably descriptive message. The following is a (possibly incomplete) list of conditions which will raise an error:,If the specified value is True, the configuration is processed as described in the section on Incremental Configuration.,The configuring dict is searched for the following optional keys which correspond to the arguments passed to create a Formatter object:,formatters - the corresponding value will be a dict in which each key is a formatter id and each value is a dict describing how to configure the corresponding Formatter instance.

def dictConfig(config):
   dictConfigClass(config).configure()
handlers:
   console:
   class: logging.StreamHandler
formatter: brief
level: INFO
filters: [allow_foo]
stream: ext: //sys.stdout
   file:
   class: logging.handlers.RotatingFileHandler
formatter: precise
filename: logconfig.log
maxBytes: 1024
backupCount: 3
formatters:
   brief:
   # configuration
for formatter with id 'brief'
goes here
precise:
   # configuration
for formatter with id 'precise'
goes here
handlers:
   h1: #This is an id
# configuration of handler with id 'h1'
goes here
formatter: brief
h2: #This is another id
# configuration of handler with id 'h2'
goes here
formatter: precise
loggers:
   foo.bar.baz:
   # other configuration
for logger 'foo.bar.baz'
handlers: [h1, h2]
formatters:
   brief:
   format: '%(message)s'
default:
format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
datefmt: '%Y-%m-%d %H:%M:%S'
custom:
   (): my.package.customFormatterFactory
bar: baz
spam: 99.9
answer: 42
{
   'format': '%(message)s'
}
{
   'format': '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
   'datefmt': '%Y-%m-%d %H:%M:%S'
}

Suggestion : 4

logging.StreamHandler()

def get_logger(cls, logger_name, create_file = False):

   # create logger
for prd_ci
log = logging.getLogger(logger_name)
log.setLevel(level = logging.INFO)

# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

if create_file:
   # create file handler
for logger.
fh = logging.FileHandler('SPOT.log')
fh.setLevel(level = logging.DEBUG)
fh.setFormatter(formatter)
# reate console handler
for logger.
ch = logging.StreamHandler()
ch.setLevel(level = logging.DEBUG)
ch.setFormatter(formatter)

# add handlers to logger.
if create_file:
   log.addHandler(fh)

log.addHandler(ch)
return log
def log_config(log_dir = None, log_file = None, prefix = None, rank = 0):
   reload(logging)
head = '%(asctime)-15s Node[' + str(rank) + '] %(message)s'
if log_dir:
   logging.basicConfig(level = logging.DEBUG, format = head)
if not os.path.exists(log_dir):
   os.makedirs(log_dir)
if not log_file:
   log_file = (prefix
      if prefix
      else '') + datetime.now().strftime('_%Y_%m_%d-%H_%M.log')
log_file = log_file.replace('/', '-')
else:
   log_file = log_file
log_file_full_name = os.path.join(log_dir, log_file)
handler = logging.FileHandler(log_file_full_name, mode = 'w')
formatter = logging.Formatter(head)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
logging.info('start with arguments %s', args)
else:
   logging.basicConfig(level = logging.DEBUG, format = head)
logging.info('start with arguments %s', args)
def getLogger(fname = None):
   format = '%(asctime)s:%(process)d:%(threadName)s:%(levelname)s:%(name)s:%(pathname)s %(lineno)d:%(message)s'
formatter = MyFormatter(format)

logger = logging.getLogger('sdx')

if fname:
   fh = logging.FileHandler(fname)
fh.setFormatter(formatter)
logger.addHandler(fh)

ch = logging.StreamHandler(stream = sys.stdout)
ch.setFormatter(formatter)
logger.addHandler(ch)

return logger
def get_logger(cls, logger_name, create_file = False):

   # create logger
for prd_ci
log = logging.getLogger(logger_name)
log.setLevel(level = logging.INFO)

# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

if create_file:
   # create file handler
for logger.
fh = logging.FileHandler('oa.log')
fh.setLevel(level = logging.DEBUG)
fh.setFormatter(formatter)
# reate console handler
for logger.
ch = logging.StreamHandler()
ch.setLevel(level = logging.DEBUG)
ch.setFormatter(formatter)

# add handlers to logger.
if create_file:
   log.addHandler(fh)

log.addHandler(ch)
return log
def create_file_logger(root, name, file_name = "log.txt", timestamp_format = "", debug = False):
   file_api = FileAPI(root)
timestamp = ""
if timestamp_format:
   timestamp = datetime.now().strftime(timestamp_format)
else:
   timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

folder = name + "_" + timestamp
# prepare folder and file
with file_api.open_with_mkdir(folder + "/" + file_name) as f:
   f.write("".encode("utf-8"))

log_root = os.path.join(root, folder)
logger = create_logger(name, debug)
fh = FileHandler(os.path.join(log_root, file_name), encoding = "utf-8")
fh.setLevel(_bool_2_level(debug))
logger.addHandler(fh)

# add close method to release resource
logger.close = types.MethodType(__close, logger)
return logger, log_root
def setup_logging(log_loc):
   if os.path.exists(log_loc):
   shutil.move(log_loc, log_loc + "_" + str(int(os.path.getctime(log_loc))))
os.makedirs(log_loc)

log_file = '{}/benchmark.log'.format(log_loc)
LOGGER = logging.getLogger('benchmark')
LOGGER.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(levelname)s:%(name)s %(message)s')
file_handler = logging.FileHandler(log_file)
console_handler = logging.StreamHandler()
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)

LOGGER.addHandler(file_handler)
LOGGER.addHandler(console_handler)
return LOGGER

Suggestion : 5

With the logger object configured, the following methods create log messages:,The standard library includes quite a few handler types; this tutorial uses only StreamHandler and FileHandler in its examples.,The most widely used methods on logger objects fall into two categories: configuration and message sending.,The following Python module creates a logger, handler, and formatter nearly identical to those in the example listed above, with the only difference being the names of the objects:

import logging
LOG_FILENAME = 'example.log'
logging.basicConfig(filename = LOG_FILENAME, level = logging.DEBUG)

logging.debug('This message should go to the log file')
DEBUG: root: This message should go to the log file
import glob
import logging
import logging.handlers

LOG_FILENAME = 'logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
   LOG_FILENAME, maxBytes = 20, backupCount = 5)

my_logger.addHandler(handler)

# Log some messages
for i in range(20):
   my_logger.debug('i = %d' % i)

# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)

for filename in logfiles:
   print filename
logging_rotatingfile_example.out
logging_rotatingfile_example.out .1
logging_rotatingfile_example.out .2
logging_rotatingfile_example.out .3
logging_rotatingfile_example.out .4
logging_rotatingfile_example.out .5
import logging
import sys

LEVELS = {
   'debug': logging.DEBUG,
   'info': logging.INFO,
   'warning': logging.WARNING,
   'error': logging.ERROR,
   'critical': logging.CRITICAL
}

if len(sys.argv) > 1:
   level_name = sys.argv[1]
level = LEVELS.get(level_name, logging.NOTSET)
logging.basicConfig(level = level)

logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical error message')
$ python logging_level_example.py debug
DEBUG: root: This is a debug message
INFO: root: This is an info message
WARNING: root: This is a warning message
ERROR: root: This is an error message
CRITICAL: root: This is a critical error message

$ python logging_level_example.py info
INFO: root: This is an info message
WARNING: root: This is a warning message
ERROR: root: This is an error message
CRITICAL: root: This is a critical error message

Suggestion : 6

I am trying to configure my logging using the dictConfig() method. I think I understood the Dictionary Schema Details, but my code still throws an error.,错误似乎是logfile_handler_conf字典中的“类”值应该是字符串“ logging.FileHandler”,而不是FileHandler类本身。

码:

import logging
import logging.config

verbose_formatter_conf = {
   "format": "%(asctime)-15s %(name)s %(levelname)-9s %(message)s",
}

formatters_dict = {
   "verbose_formatter": verbose_formatter_conf,
}

logfile_handler_conf = {
   "class": logging.FileHandler,
   "level": logging.DEBUG,
   "formatter": "verbose_formatter",
   "filename": "logfile.txt",
   "mode": "w",
   "encoding": "utf-8",
}

handlers_dict = {
   "logfile_handler": logfile_handler_conf,
}

verbose_file_logger_conf = {
   "propagate": True,
   "handlers": ["logfile_handler"]
}

loggers_dict = {
   "verbose_file_logger": verbose_file_logger_conf
}

final_conf = {
   "version": 1,
   "formatters": formatters_dict,
   "handlers": handlers_dict,
   "loggers": loggers_dict,
   "incremental": False,
}

logging.config.dictConfig(final_conf)
logger = logging.getLogger(__name__)

logger.debug("hello")

它引发的错误是:

Traceback (most recent call last):
File "C:\Program Files\Python37\lib\logging\config.py", line 555, in configure
handler = self.configure_handler(handlers[name])
File "C:\Program Files\Python37\lib\logging\config.py", line 705, in configure_handler
klass = self.resolve(cname)
File "C:\Program Files\Python37\lib\logging\config.py", line 372, in resolve
name = s.split('.')
AttributeError: type object 'FileHandler' has no attribute 'split'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "c:\Users\Tejul\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\ptvsd_launcher.py", line 43, in <module>
   main(ptvsdArgs)
   File "c:\Users\Tejul\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\lib\python\ptvsd\__main__.py", line 434, in main
   run()
   File "c:\Users\Tejul\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\lib\python\ptvsd\__main__.py", line 312, in run_file
   runpy.run_path(target, run_name='__main__')
   File "C:\Program Files\Python37\lib\runpy.py", line 263, in run_path
   pkg_name=pkg_name, script_name=fname)
   File "C:\Program Files\Python37\lib\runpy.py", line 96, in _run_module_code
   mod_name, mod_spec, pkg_name, script_name)
   File "C:\Program Files\Python37\lib\runpy.py", line 85, in _run_code
   exec(code, run_globals)
   File "g:\Sven\Python\pygtris\logger_conf.py", line 42, in <module>
      logging.config.dictConfig(final_conf)
      File "C:\Program Files\Python37\lib\logging\config.py", line 792, in dictConfig
      dictConfigClass(config).configure()
      File "C:\Program Files\Python37\lib\logging\config.py", line 563, in configure
      '%r' % name) from e
      ValueError: Unable to configure handler 'logfile_handler'

Suggestion : 7

Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers in the application. It is sufficient to configure handlers for a top-level logger and create child loggers as needed. , Levels are used for identifying the severity of an event. There are six logging levels: , In the configuration file, we have defined various formatters, handlers, and loggers. The propagate option prevents from propagating log messages to the parent loggers; in our case, to the root logger. Otherwise, the messages would be duplicated. , Python logging module defines functions and classes which implement a flexible event logging system for applications and libraries.

1._
#!/usr/bin/python

import logging

logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

The example calls five methods of the logging module. The messages are written to the console.

$ simple.py
WARNING: root: This is a warning message
ERROR: root: This is an error message
CRITICAL: root: This is a critical message
3._
#!/usr/bin/python

import logging

logger = logging.getLogger('dev')
logger.setLevel(logging.DEBUG)

logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

The getLogger returns a logger with the specified name. If name is None, it returns the root logger. The name can be a dot separated string defining logging hierarchy; for instance 'a', 'a.b', or 'a.b.c'. Note that there is an implicit root name, which is not shown.

$ set_level.py
This is a warning message
This is an error message
This is a critical message
6._
#!/usr/bin/python

import logging

main_logger = logging.getLogger('main')
main_logger.setLevel(5)

dev_logger = logging.getLogger('main.dev')

print(main_logger.getEffectiveLevel())
print(dev_logger.getEffectiveLevel())