loggger.py
import logging
import sys
def init():
"""
This function only run once
create 2 log outputs : a file and console
:return:
"""
#-----------------------------------------------------
# create an instance of logging.Logger
#-----------------------------------------------------
logger=logging.getLogger("myproj")
#-----------------------------------------------------
# create an instance of FileHandler for the log file
#-----------------------------------------------------
log_file=r'C:\users\bckong\desktop\tmp\test.log'
fp=logging.FileHandler(filename=log_file, mode='a')
# output message format: [level ], [module name ],[function name ], [line number ] message
# you can change output format
fmt_string = '[%(levelname)-9s] [%(module)-20s] [%(funcName)-20s %(lineno)4d] %(message)s'
# create an instance of logging.Formatter
formatter = logging.Formatter(fmt=fmt_string)
fp.setFormatter(formatter)
# add the log file handler to the logger
logger.addHandler(fp)
#-----------------------------------------------------
# create an instance of StreamHandler for console output
#-----------------------------------------------------
log_console=logging.StreamHandler(stream=sys.stdout)
log_console.setFormatter(formatter)
# add the console output to the logger
logger.addHandler(log_console)
using_mylogger.py
import logging
import logger
class Foo():
def __init__(self):
print "----> ", __file__
self.log=logging.getLogger("myproj.module.file02")
self.log.setLevel(logging.DEBUG)
self.log.info("instance of Foo")
def greatings(self):
self.log.debug("Welcome to logging module")
f=Foo()
f.greatings()
本文介绍了一个Python项目中日志模块的配置与使用方法,包括如何创建文件日志输出和控制台输出,并通过实例展示了如何在一个具体类中使用自定义的日志记录器。
841

被折叠的 条评论
为什么被折叠?



