新版python logging 封裝,支援同時向console,file,socket輸出

來源:互聯網
上載者:User

將python的logging封裝更新了一下,目前支援同時向console,file,socket輸出,同時在config_logging或者config_logging_plus的時候先清除根logger的所有handler,避免在某些情況下的重複輸出。
具體代碼如下:

# -*- coding: utf-8 -*-'''Modified on 2012-11-27@summary: clear old root logger handlers when reconfig logging@author: JerryKwanCreated on 2012-06-14 19:50@summary:  logging config@author: JerryKwan'''import loggingimport logging.handlersimport osimport sysLEVELS = {'NOSET': logging.NOTSET,          'DEBUG': logging.DEBUG,          'INFO': logging.INFO,          'WARNING': logging.WARNING,          'ERROR': logging.ERROR,          'CRITICAL': logging.CRITICAL}#set up logging to file#logging.basicConfig(level = logging.NOTSET,#                    format = "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"#                    )##                    filename = "./log.txt",##                    filemode = "w")# create logs file folderdef config_logging(file_name = "log.txt", log_level = "NOSET"):    '''    @summary: config logging to write logs to local file    @param file_name: name of log file    @param log_level: log level    '''    logs_dir = os.path.join(os.path.dirname(__file__), "logs")    if os.path.exists(logs_dir) and os.path.isdir(logs_dir):        pass    else:        os.makedirs(logs_dir)    # clear old root logger handlers    logging.getLogger("").handlers = []    file_name = os.path.join(logs_dir, file_name)    # define a rotating file handler    rotatingFileHandler = logging.handlers.RotatingFileHandler(filename =file_name,                                                      maxBytes = 1024 * 1024 * 50,                                                      backupCount = 5)    formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s")    rotatingFileHandler.setFormatter(formatter)    logging.getLogger("").addHandler(rotatingFileHandler)    # define a handler whitch writes messages to sys    console = logging.StreamHandler()    # set a format which is simple for console use    formatter = logging.Formatter("%(name)-12s: %(levelname)-8s %(message)s")    # tell the handler to use this format    console.setFormatter(formatter)    # add the handler to the root logger    logging.getLogger("").addHandler(console)    # set initial log level    logger = logging.getLogger("")    level = LEVELS[log_level.upper()]    logger.setLevel(level)def config_logging_plus(file_name = "log.txt", log_level = "NOSET", remote_address = ("127.0.0.1", 8888), write_console = False):    '''    @summary: config logging to write logs to remote service    @param host: hostname or ip address of the log server    @param port: port to be used for log server    @log_level: log level    '''    logs_dir = os.path.join(os.path.dirname(__file__), "logs")    if os.path.exists(logs_dir) and os.path.isdir(logs_dir):        pass    else:        os.makedirs(logs_dir)    # format file name    if file_name is None:        file_name = os.path.splitext(sys.argv[0])[0]        file_name = os.path.join(logs_dir, "%s_%s.log"%(file_name, os.getpid()))    else:        file_name = os.path.join(logs_dir, file_name)    # clear old root logger handlers    logging.getLogger("").handlers = []        # define a rotating file handler    rotatingFileHandler = logging.handlers.RotatingFileHandler(filename =file_name,                                                      maxBytes = 1024 * 1024 * 50,                                                      backupCount = 5)    formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s")    rotatingFileHandler.setFormatter(formatter)    # add log handler    logging.getLogger("").addHandler(rotatingFileHandler)    if write_console is not None and  write_console == True:        # define a handler whitch writes messages to sys        console = logging.StreamHandler()        console.setLevel(logging.NOTSET)        # set a format which is simple for console use        formatter = logging.Formatter("%(name)-12s: %(levelname)-8s %(message)s")        # tell the handler to use this format        console.setFormatter(formatter)        # add log handler        logging.getLogger("").addHandler(console)    if remote_address is not None and hasattr(remote_address, "__iter__") and len(remote_address) > 1:        # define a socket handler        socketHandler = logging.handlers.SocketHandler(remote_address[0], remote_address[1])        formatter = logging.Formatter("%(asctime)s %(processName)s %(process)s %(name)-12s %(levelname)-8s %(message)s")        socketHandler.setFormatter(formatter)        # add log handler        logging.getLogger("").addHandler(socketHandler)    # set initial log level    logger = logging.getLogger("")    level = LEVELS[log_level.upper()]    logger.setLevel(level)

使用方法很簡單,只需要需要config logging的時候config一下即可,範例程式碼如下:

import loggingconfigloggingconfig.config_logging(file_name = "log.log", log_level = "NOSET")
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.