Python logging

发布于 2018-03-05 · 本文总共 1798 字 · 阅读大约需要 6 分钟

配置文件logging.config.dictConfig

logging = {
    'version': 1,
    'loggers': {
        'cluster_tool': {'level': 'DEBUG', 'handlers': ['console', 'file'], 'propagate': False},
        'basic_check': {'level': 'DEBUG', 'handlers': ['console', 'file_bc'], 'propagate': False},
        'py.warnings': {'handlers': ['console']},
    },
    'handlers': {
        'console': {
            'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'color'
            }, 'file': {
            'class': 'logging.FileHandler', 'filename': 'server_name.log', 'level': 'DEBUG', 'formatter': 'simple'
        }, 'file_bc': {
            'class': 'logging.FileHandler', 'filename': 'filename.log', 'level': 'DEBUG', 'formatter': 'simple'
        },
    },
    'formatters': {
        'simple': {
            'format': (
                '%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)-5.5s [%(name)s] [%(threadName)s]: %(message)s')
        }, 'color': {
            'format': ('%(asctime)s %(filename)s [line:%(lineno)d] [%(levelname)s] [%(name)s] [%(threadName)s]: \033['
                       '1;33;40m%(message)s\033[0m'),
        }
    }
}

import logging.config

from config import logging as LogConfig

logging.config.dictConfig(LogConfig)

LOG = logging.getLogger("cluster_tool")

LOG.info(“xxxx”)

不优雅的写法

#-*- coding=UTF-8 -*-
import logging
import logging.config
import ConfigParser
import sqlite3
import chardet
from pyh import *
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def createlog(name=__name__,log_file_name = 'test.log',debug=[],info=[],warn= [],error= [],fetal=[]):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    if not logger.handlers:
        # create a file handler
        handler = logging.FileHandler(log_file_name)
        handler.setLevel(logging.DEBUG)
        # create a logging format
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
        handler.setFormatter(formatter)
        # add the handlers to the logger
        logger.addHandler(handler)
        ########################解决日志重复的问题logger.removeHandler(handler)
    if info:logger.info(info)
    if debug:logger.debug(debug)
    if warn:logger.warning(warn)
    if error:logger.error(error)
    if fetal:logger.fatal(fetal)



本博客所有文章采用的授权方式为 自由转载-非商用-非衍生-保持署名 ,转载请务必注明出处,谢谢。
声明:
本博客欢迎转发,但请保留原作者信息!
博客地址:邱文奇(qiuwenqi)的博客;
内容系本人学习、研究和总结,如有雷同,实属荣幸!
阅读次数:

文章评论

comments powered by Disqus


章节列表