2012-07-20 35 views
20

阅读documentation on logging后,我知道我可以使用这样的代码进行简单的记录:如何在每个记录器的基础上更改Python日志消息的格式?

import logging 

def main(): 
    logging.basicConfig(filename="messages.log", 
         level=logging.WARNING, 
         format='%(filename)s: '  
           '%(levelname)s: ' 
           '%(funcName)s(): ' 
           '%(lineno)d:\t' 
           '%(message)s') 

    logging.debug("Only for debug purposes\n") 
    logging.shutdown() 

main() 

但是,我意识到,我不知道如何更改日志消息的格式在每个记录器的基础,因为basicConfig是模块级功能。此代码适用于创建具有不同级别,名称等的不同记录器,但是有没有办法以每个记录器为基础更改这些日志消息的格式,类似于basicConfig

import inspect 
import logging 

def function_logger(level=logging.DEBUG): 
    function_name = inspect.stack()[1][3] 
    logger = logging.getLogger(function_name) 
    logger.setLevel(level) 
    logger.addHandler(logging.FileHandler("{0}.log".format(function_name))) 
    return logger 

def f1(): 
    f1_logger = function_logger() 
    f1_logger.debug("f1 Debug message") 
    f1_logger.warning("f1 Warning message") 
    f1_logger.critical("f1 Critical message") 

def f2(): 
    f2_logger = function_logger(logging.WARNING) 
    f2_logger.debug("f2 Debug message") 
    f2_logger.warning("f2 Warning message") 
    f2_logger.critical("f2 Critical message") 

def main(): 
    f1() 
    f2() 
    logging.shutdown() 

main() 

回答

31

试试这个

import logging 

logger = logging.getLogger('simple_example') 
logger.setLevel(logging.DEBUG) 
# create file handler that logs debug and higher level messages 
fh = logging.FileHandler('spam.log') 
fh.setLevel(logging.DEBUG) 
# create console handler with a higher log level 
ch = logging.StreamHandler() 
ch.setLevel(logging.ERROR) 
# create formatter and add it to the handlers 
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
ch.setFormatter(formatter) 
fh.setFormatter(formatter) 
# add the handlers to logger 
logger.addHandler(ch) 
logger.addHandler(fh) 

# 'application' code 
logger.debug('debug message') 
logger.info('info message') 
logger.warn('warn message') 
logger.error('error message') 
logger.critical('critical message') 

了解更多信息

+0

+1见http://docs.python.org/howto/logging-cookbook.html#multiple-handlers-and-formatters和+1再次(遗憾的是没有)添加代码。我编辑它到我的[以前的答案](http://stackoverflow.com/a/11581118/869912)以记录问题以及它完美的作品。 – 2012-07-20 15:50:55

+9

我总是感到惊讶,它不像'logger = logging.getLogger('mylogger')logger.basicConfig(level = ...,format = ...)那么简单......“ – theartofrain 2015-02-18 21:58:45

+0

工作很棒!谢谢! – Eli 2016-12-01 14:58:24

1

您创建或使用的logging.Handler现有的子类,并调用一个实例的方法setformatter()logger.Formatter定制子类的实例上。如果你为已经附加到记录器的处理程序设置了格式化程序,那么你就可以修改输出了,否则你必须用logging.getLogger()检索一个记录程序对象,并用你的处理程序类的实例调用它的addHandler()方法您将格式化程序设置为参数。

相关问题