我一直在学习日志记录,并且早些时候在设置带外部配置文件的记录器时获得了帮助。
我已根据示例进行设置,但是这些消息仅在控制台上显示,而不是在长文件中显示(未创建。
你能看到我做错了吗?
utilityLogger:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
My app
'''
# ~~~~~ LOGGING SETUP ~~~~~ #
# set up the first logger for the app
import os
import testLogging as vlog
# path to the current script's dir
scriptdir = os.path.dirname(os.path.realpath(__file__))
LOG_CONFIG = '../config/logging.conf'
print scriptdir
def logpath():
'''
Return the path to the main log file; needed by the logging.yml
use this for dynamic output log file paths & names
'''
global scriptdir
return (vlog.logpath(scriptdir = scriptdir, logfile = 'log.txt'))
logger = vlog.log_setup(config_file=LOG_CONFIG, logger_name="app")
logger.debug("App is starting...")
testLogging:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Functions to set up the app logger
'''
import logging
import logging.config
import os
LOG_CONFIG = '../config/logging.conf'
def logpath(scriptdir, logfile):
'''
Return the path to the main log file; needed by the logging.yml
use this for dynamic output log file paths & names
'''
log_file = os.path.join(scriptdir, logfile)
print log_file
print scriptdir
print logfile
return(logging.FileHandler(log_file))
def log_setup(config_file, logger_name):
'''
Set up the logger for the script
config = path to YAML config file
'''
# Config file relative to this file
logging.config.fileConfig(config_file)
return(logging.getLogger(logger_name))
logging.conf文件:
[loggers]
keys=root
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
qualname=app
[logger_app]
level=DEBUG
handlers=consoleHandler
qualname=app
propagate=true
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=('%(logfilename)s',)
[main]
()=__main__.logpath
level=DEBUG
formatter=simpleFormatter
[formatter_fileFormatter]
format=%(asctime)s (%(name)s:%(funcName)s:%(lineno)d:%(levelname)s) %
(message)s # %(module)s:
datefmt="%Y-%m-%d %H:%M:%S"
[formatter_simpleFormatter]
format=%(asctime)s (%(name)s:%(funcName)s:%(lineno)d:%(levelname)s) %(message)s # %(module)s:
datefmt="%Y-%m-%d %H:%M:%S"
更新,问题已经标记为已回答,我很感谢@zwer的帮助!
最后一个目标,要理解,是否有更多pythonic方式将记录器实例化为Class(但我希望能够登录main)。有了明确的答案,我将以下内容放在一起,但我不确定它是主要和类日志记录的最佳解决方案。
class TestLog(object):
def __init__(self, logger):
self.logger = logger
self.__sub_test = 0
def add_test(self):
self.logger.debug('addition')
a = 1 + 1
self.logger.debug('result {}'.format(a, 1))
def sub_test(self):
self.logger.debug('subtraction')
b = 5 -2
self.logger.debug('result {}'.format(b, 1))
def main():
logger = vlog.log_setup(config_file=LOG_CONFIG, logger_name="app",
log_file=LOG_PATH)
logger.debug("App is starting...")
test1 = TestLog(logger)
print test1.add_test()
print test1.sub_test()
if __name__ == "__main__":
sys.exit(main())
答案 0 :(得分:2)
好吧,让我们把它打包成答案,以避免评论限制。
您的配置的主要问题是您根本没有初始化您的fileHandler。如果您想使用它,请务必将其添加到[handlers]
部分,例如:
[handlers] keys=fileHandler
至于你的其他错误,因为你在[handler_fileHandler]
中为文件名定义了一个动态参数logfilename
,所以你需要在用Python加载日志配置时提供它,例如:
logging.config.fileConfig(config_file, defaults={"logfilename": "your_log_filename.log"})
这应该可以解决问题。
更新 - 只要您提供了正确的文件路径,说明应该可以使用,但您仍需要稍微修改配置以在所有记录器中启用文件记录器。因此,请将配置更改为:
[loggers] keys=root [handlers] keys=consoleHandler,fileHandler [formatters] keys=simpleFormatter,fileFormatter [logger_root] level=DEBUG handlers=consoleHandler,fileHandler qualname=app [logger_app] level=DEBUG handlers=consoleHandler,fileHandler qualname=app propagate=true [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [handler_fileHandler] class=FileHandler level=DEBUG formatter=fileFormatter args=('%(logfilename)s',) [main] ()=__main__.logpath level=DEBUG formatter=simpleFormatter [formatter_fileFormatter] format=%(asctime)s (%(name)s:%(funcName)s:%(lineno)d:%(levelname)s) %(message)s # %(module)s: datefmt="%Y-%m-%d %H:%M:%S" [formatter_simpleFormatter] format=%(asctime)s (%(name)s:%(funcName)s:%(lineno)d:%(levelname)s) %(message)s # %(module)s: datefmt="%Y-%m-%d %H:%M:%S"
另外,为了使其更灵活,请将testLogging.log_setup()
更改为:
def log_setup(config_file, logger_name, log_file):
# Config file relative to this file
logging.config.fileConfig(config_file, defaults={"logfilename": log_file})
return logging.getLogger(logger_name)
最后,当你进行设置时,只需将其调用为:
LOG_CONFIG = '../config/logging.conf'
LOG_PATH = r"C:\PycharmProjects\scrap\test.log" # make sure it exists and is accessible!
logger = vlog.log_setup(config_file=LOG_CONFIG, logger_name="app", log_file=LOG_PATH)
logger.debug("App is starting...")
根据您的本地路径进行调整,它应该按预期工作。我只是测试了它,它给出了正确的结果。