2017-07-24 53 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

我試過了,但是我得到了同樣的錯誤。 –