python logging 工具

使用 python logging记录debug 等日志信息

debug 以上信息写入文件

info 以上信息输出在控制台

import os
import logging

VDE_LOGGING_NAME = "vde_logging"
LOG_FILE_PATH = os.path.join(os.path.dirname(__file__), "vde_regression.log")

vde_logging = None


def init_log(func):
def _decorator(msg):
if not vde_logging:
logging_initialize()
return func(msg)

return _decorator


def logging_initialize():
global vde_logging
# 1. logging
vde_logging = logging.getLogger(VDE_LOGGING_NAME)
vde_logging.setLevel(logging.DEBUG)
# 2.handler
# file handler
fh = logging.FileHandler(LOG_FILE_PATH, mode="w")
fh.setLevel(logging.DEBUG)
# standard control console
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# 3.format
formatter = logging.Formatter("[%(asctime)s %(name)s].%(levelname)s: %(message)s")
fh.setFormatter(formatter)
ch.setFormatter(formatter)

vde_logging.addHandler(fh)
vde_logging.addHandler(ch)


@init_log
def logging_debug(debug_msg):
vde_logging.debug(debug_msg)


@init_log
def logging_info(info_msg):
vde_logging.info(info_msg)


@init_log
def logging_error(error_msg):
vde_logging.error(error_msg)


@init_log
def logging_warn(warn_msg):
vde_logging.warn(warn_msg)


if __name__ == '__main__':
logging_initialize()
logging_debug("debug")
logging_info("info")
print "print info"

  References:

http://www.zlovezl.cn/articles/replacing-print-simple-introduction-to-logging/

https://blog.igevin.info/posts/python-log/

posted @ 2017-12-25 15:18  百变小超  阅读(410)  评论(0编辑  收藏  举报