2017-07-24 116 views
0

我一直在学习关于日志记录,并得到帮助在这里设置记录器W /外部配置文件。没有日志文件创建

我已经根据设置的例子,但只看到控制台上,而不是在一个长的文件(未创建。

能否请你看我在做什么错误消息?

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 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

处理程序在配置文件中设置为consoleHandler,该文件写入'sys.stdout'。更改为fileHandler。 – Dan

+0

@丹我不知道我遵循你的评论,因为我的fileHandler需要一个arg文件名输出到。 –

+1

你的'[handlers]''keys'只包含'consoleHandler' - 你的fileHandler永远不会被初始化。 – zwer

回答

2

好的,让我们把它作为避免评论限制的答案。

你的配置的主要问题是你根本没有初始化你的fileHandler。如果你想使用它,请确保你把它添加到[handlers]部分,例如:

[handlers] 
keys=fileHandler

至于你的其他错误,因为在你的[handler_fileHandler]你定义一个动态参数logfilename的文件的名称,以便您需要提供它,当你在Python中加载你的日志记录配置,例如:

logging.config.fileConfig(config_file, defaults={"logfilename": "your_log_filename.log"}) 

这应该做的伎俩。

UPDATE - 只要你提供一个适当的文件路径,则表示应该工作,但你仍然需要修改配置多一点点,使您的所有记录器的文件记录器。因此,改变你的配置到:

[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...") 

调整为您的本地路径它应该按预期工作。我只是在我身边进行测试,并给出了正确的结果。

+0

感谢您的解释。当我的解决方案的第二部分,我得到以下内容:更新行'logging.config.fileConfig(config_file,defaults = {“logfilename”:“C:\\ PycharmProjects \\ scrap \\ test.log”})'错误:'IOError:[Errno 22]无效模式('a')或文件名:'我用'/','\\\'和abs路径尝试过,但是我一直得到相同的错误。 –

+0

@Simply_me - 尝试将其定义为:'defaults = {“logfilename”:r“C:\ PycharmProjects \ scrap \ test.log”}'并确保该文件夹存在('logging'模块不会创建路径) 。 – zwer

+0

我试过了,但是我得到了同样的错误。 –