另一个Python日志记录设置

问题描述:

我一直在阅读日志模块在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" 

我做了类似的事情,这是我如何把它设置

外部配置文件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