l o g 1 , l o g 2 , l o g 3 log1,log2,log3 log1,log2,log3分别对应三种实现方式,其中 l o g 1 log1 log1的实现比较简单,但是使用不便,尤其是需要在多个地方调用且写入同一文件的时候, l o g 2 , l o g 3 log2,log3 log2,log3则使用对象实现,方便在多个地方调用,且演示了如何同时向控制台和文件输出,以下是简单的示例代码:
import loggingimport os.pathimport timedef log1():logging.basicConfig(level=logging.INFO,filename='log.txt',filemode='w',format="%(levelname)s:%(asctime)s:%(message)s")logging.error("出现了错误")logging.info("打印信息")logging.warning("警告信息")def log2():log_obj = logging.getLogger() # 创建对象log_obj.setLevel("INFO")# 设置日志等级fileHandle = logging.FileHandler('log2.txt',mode='w') # 创建日志文件流对象streamHandle = logging.StreamHandler() # 创建控制台对象# 将创建的两个对象添加到日志对象中log_obj.addHandler(fileHandle)log_obj.addHandler(streamHandle)#打印信息log_obj.info('普通信息')log_obj.error('出现错误')log_obj.warning('出现警告')def log3():logger = logging.getLogger()logger.setLevel(level=logging.DEBUG)handler = logging.FileHandler('log3.txt', mode='w')handler.setLevel(logging.INFO)formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")handler.setFormatter(formatter)console = logging.StreamHandler()console.setLevel(logging.WARNING)logger.addHandler(handler)logger.addHandler(console)logger.debug('This is a debug message.')logger.info('This is an info message.')logger.warning('This is a warning message.')logger.error('This is an error message.')logger.critical('This is a critical message.')def log():logger = logging.getLogger()logger.setLevel(level=logging.DEBUG)handler = logging.FileHandler('log3.txt', mode='w')handler.setLevel(logging.INFO)formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")handler.setFormatter(formatter)console = logging.StreamHandler()console.setLevel(logging.WARNING)logger.addHandler(handler)logger.addHandler(console)return loggerdef log4(loger):loger.warning("This is log4")def f():loger=log()loger.info("infomation1")loger.info("infomation2")loger.warning("warning1")log4(loger)if __name__=='__main__':f()
我们可以通过设置等级来控制信息是否输出,这一点在调试时尤为有用,若使用 p r i n t print print调试,则在调试完成后还需要将所有 p r i n t print print注释掉,而采用 l o g log log模块,只需修改等级即可。