简体   繁体   English

Python-将日志写入文件

[英]Python - Writing a log to a file

I currently have logging setup for console. 我目前有控制台的日志记录设置。

Im invoking my config using : 我使用以下命令调用我的配置:

import logging
import logging.config

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

My config is :: 我的配置是::

[loggers]
keys=root,osPatch

[handlers]
keys=consoleHandler

[formatters]
keys=osPatch

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_osPatch]
level=DEBUG
handlers=consoleHandler
qualname=osPatch
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=osPatch
args=(sys.stdout,)

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

This gives me console level logging perfectly fine. 这使我可以很好地进行控制台级别的日志记录。

Now I want the same logs to be written to a file. 现在,我希望将相同的日志写入文件。

What im trying to do is edit my config file and use a fileHandler . 我想做的是编辑我的配置文件并使用fileHandler

So Im editing my config file to : 因此,我将配置文件编辑为:

[loggers]
keys=root,osPatch

[handlers]
keys=consoleHandler,FileHandler

[handler_FileHandler]
filename=example.log
level=DEBUG
formatter=osPatch

This gives me an ERROR : 这给我一个错误:

Traceback (most recent call last):
  File "apply_errata.py", line 1, in <module>
    import satellite_utils
  File "/root/config-3.1.25/automated-os-patching/satellite_utils.py", line 3, in <module>
    import system_utils
  File "/root/config-3.1.25/automated-os-patching/system_utils.py", line 4, in <module>
    import processing_utils
  File "/root/config-3.1.25/automated-os-patching/processing_utils.py", line 7, in <module>
    logging.config.fileConfig('logging.conf')
  File "/usr/lib64/python3.4/logging/config.py", line 85, in fileConfig
    _install_loggers(cp, handlers, disable_existing_loggers)
  File "/usr/lib64/python3.4/logging/config.py", line 253, in _install_loggers
    logger.addHandler(handlers[hand])
KeyError: 'FileHandler'

What am I doing wrong here ? 我在这里做错了什么?

Not sure how your full config file looks, but that traceback in my experience indicate that the handler key isn't properly declared in the handler section. 不确定完整配置文件的外观,但是根据我的经验,该追溯表明处理程序密钥未在处理程序部分中正确声明。

For reference, this is a tried and working version of the config file I think you aim to create: 作为参考,这是我认为您打算创建的配置文件的试用版。

[loggers]
keys=root,osPatch

[handlers]
keys=consoleHandler,FileHandler

[formatters]
keys=osPatch

[logger_root]
level=DEBUG
handlers=consoleHandler,FileHandler

[logger_osPatch]
level=DEBUG
handlers=consoleHandler,FileHandler
qualname=osPatch
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=osPatch
args=(sys.stdout,)

[handler_FileHandler]
class=FileHandler
level=DEBUG
formatter=osPatch
args=('example.log',)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM