2017-07-24 141 views
0

我一直在閱讀日誌模塊在python和幾個博客如何設置它,但是,沒有博客給出了更復雜的設置方案。另一個Python日誌記錄設置

我想:

  1. 使用外部配置文件(見下文)。
  2. 有外部的模塊來處理日誌設置(創建日誌文件瓦特/ mylogfile+datetime(見下文)。
  3. 最後,實例化一個記錄器類中的多個方法來輸出文件記錄。

權現在,無可否認,我有一些設置混亂,並希望有一些指示清理這個混亂:-)。

我相信外部配置文件加載正常,但沒有創建日誌文件。

例主要:

#!/bin/env python 

import os 
import sys 
import logging.config 
from datetime import datetime 

datetime.now().strftime('mylogfile_%H%M%d%m%Y.log') 

LOG_CONFIG = '../config/logging.conf' 
#logging.config.fileConfig(LOG_CONFIG) 
#logger = logging.getLogger(datetime.now().strftime('mylogfile_%H%M%d%m%Y.log')) 

    def setup_logger(): 
     logging.config.fileConfig(LOG_CONFIG) 
     datetime.now().strftime('mylogfile_%H%M%d%m%Y.log') 
     logger = logging.getLogger(datetime.now().strftime('mylogfile_%H%M%d%m%Y.log')) 

class TestLog(object): 
def __init__(self): 
    self.logger = logging.getLogger(__name__) 
    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(): 
    # 'application' code 
    logger.debug('debug message') 
    logger.info('info message') 
    logger.warn('warn message') 
    logger.error('error message') 
    logger.critical('critical message') 
    #setup_logger() 
    test1 = TestLog() 
    print test1.add_test() 
    print test1.sub_test() 

if __name__ == "__main__": 
    sys.exit(main()) 

的conf文件:

[loggers] 
keys=root 

[handlers] 
keys=consoleHandler 

[formatters] 
keys=simpleFormatter 

[logger_root] 
level=DEBUG 
handlers=consoleHandler 

[logger_sLogger] 
level=DEBUG 
handlers=consoleHandler 
qualname=sLogger 
propagate=0 

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

[handler_fileHandler] 
class=FileHandler 
level=DEBUG 
formatter=fileFormatter 
args=('%(logfilename)s',) 

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

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

更新基於user5359531的回覆,我已經修改了腳本,下面的那些,但與文件處理程序問題未創建文件並且消息未附加到文件。

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" 

回答

2

我做了類似的事情,這是我如何把它設置

外部配置文件YAML格式:

logging.yml

version: 1 
formatters: 
    default: # default debug logger 
    format: '[%(asctime)s] (%(name)s:%(funcName)s:%(lineno)d:%(levelname)s) %(message)s' # %(module)s: 
    datefmt: "%Y-%m-%d %H:%M:%S" 
    info: # basic info logging, for easier reading 
    format: '[%(levelname)-8s] %(message)s' 
    datefmt: "%Y-%m-%d %H:%M:%S" 
    console: 
    format: '[%(asctime)s] (%(name)s:%(funcName)s:%(lineno)d:%(levelname)s) %(message)s' 
    datefmt: "%Y-%m-%d %H:%M:%S" 

handlers: 
    console: 
    class: logging.StreamHandler 
    level: DEBUG 
    formatter: console 
    stream: ext://sys.stdout 
    main: 
    () : __main__.logpath # output file path 
    level: DEBUG 
    formatter: default 

loggers: 
    app: 
    level: DEBUG 
    handlers: [console, main] 
    propagate: true 
    parse: 
    level: DEBUG 
    handlers: [console, main] 
    propagate: true 
    tools: 
    level: DEBUG 
    handlers: [console, main] 
    propagate: true 
    data: 
    level: DEBUG 
    handlers: [console, main] 
    propagate: true 

注行() : __main__.logpath這裏,爲了得到的FileHandler調用主腳本調用logpath功能。我這樣做是爲了輸出文件名的條件設置。把你需要的文件或其他Filehandler邏輯放在裏面。看到這個 '主' 的應用程序的Python程序:

app.py

!/usr/bin/env python 
# -*- coding: utf-8 -*- 

''' 
My app 
''' 
# ~~~~~ LOGGING SETUP ~~~~~ # 
# set up the first logger for the app 
import os 
import log as vlog 
# path to the current script's dir 
scriptdir = os.path.dirname(os.path.realpath(__file__)) 

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

config_yaml = os.path.join(scriptdir,'logging.yml') 
logger = vlog.log_setup(config_yaml = config_yaml, logger_name = "app") 
logger.debug("App is starting...") 

這是伴隨着log.py(在我的主要的應用程序導入爲vlog);

log。PY

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
''' 
Functions to set up the app logger 
''' 
import yaml 
import logging 
import logging.config 
import os 

def logpath(scriptdir, logfile = 'log.txt'): 
    ''' 
    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) 
    return(logging.FileHandler(log_file)) 

def log_setup(config_yaml, logger_name): 
    ''' 
    Set up the logger for the script 
    config = path to YAML config file 
    ''' 
    # Config file relative to this file 
    loggingConf = open(config_yaml, 'r') 
    logging.config.dictConfig(yaml.load(loggingConf)) 
    loggingConf.close() 
    return(logging.getLogger(logger_name)) 

此外,我導入app.py建立記錄有後),我自己的任何其他模塊包括在模塊開始這個記錄設置:

data.py

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
''' 
Module to do data stuff for my app 
''' 
import logging 
logger = logging.getLogger("data") 

我認爲這涵蓋了你所談論的所有問題。我花了一段時間才弄明白這一點。希望能幫助到你。

+0

這是完美的!令人難以置信的幫助。謝謝。如果有任何問題,我會回顧一下並告訴你。 –

+0

我得到這個控制檯輸出工作,但由於某種原因,它沒有創建一個日誌文件。 –

+0

嘗試在'return(logging.FileHandler(log_file))'行對'logpath()'中的路徑進行硬編碼,檢查我放入logging.yml中的更新,其中'loggers:'包含一個條目(例如'app' )''handlers:[console,main]'其中'main'是日誌文件的名稱,並確保在腳本中調用一個名爲loggers下的logger(例如'app') – user5359531