首页 > 代码库 > 打印日志
打印日志
=============================================== #最普通的log打印 import logging log_file="/tmp/mylog.log" logging.basicConfig(filename=log_file,level=logging.DEBUG) def fun1(): logging.debug("This is running fun1") if __name__=="__main__": fun1() ==============================================略复杂============ import logging log_file="/tmp/mylog2.log" log_level=logging.DEBUG handler = logging.FileHandler(log_file) #handler设置日志输出到的文件地址 formatter = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s") # formatter定义日志输出的格式 handler .setFormatter(formatter) #将格式加载到handler中 logger = logging.getLogger("test2")#定义logger logger.addHandler(handler)#将指定日志输出的handler加载到logger中 logger.setLevel(log_level)#定义logger的输出级别 def func1(): logger.debug("This is debug msg ") logger.info("This is info msg") logger.warn("This is warning msg") logger.error("This is error msg") logger.critical("This is critical msg") if __name__ == "__main__": func1() ======================================实现单例模式的logger============ import logging.handlers class FinalLogger: logger=None level={"n":logging.NOTSET, "d":logging.DEBUG, "i":logging.INFO, "w":logging.WARN, "e":logging.ERROR, "c":logging.CRITICAL} log_level = "d" log_file="final_logger.log" #日志路径,这样写是当前目录 log_max_byte=10*1024*1024 #每个备份文件最多10M log_bakcup_count=5 # 最多备份文件 @classmethod def getLogger(self): if FinalLogger.logger: return FinalLogger.logger FinalLogger.logger = logging.getLogger("logging_test3") log_handler = logging.handlers.RotatingFileHandler(filename=FinalLogger.log_file,maxBytes=FinalLogger.log_max_byte,backupCount=FinalLogger.log_bakcup_count) log_fmt = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s") log_handler.setFormatter(log_fmt) FinalLogger.logger.addHandler(log_handler) FinalLogger.logger.setLevel(FinalLogger.level.get(FinalLogger.log_level)) return FinalLogger.logger class TestFialLogger: logger = FinalLogger.getLogger() def func1(self): self.logger.debug("This is debug msg ") self.logger.info("This is info msg") self.logger.warn("This is warning msg") def func2(self): self.logger.error("This is error msg") self.logger.critical("This is critical msg") if __name__ == "__main__": testLogger = TestFialLogger() testLogger.func1() testLogger2 = TestFialLogger() testLogger2.func2() if testLogger.logger == testLogger2.logger: print "YES" else: print "NO" ================================================================ logging.basicConfig函数各参数: filename: 指定日志文件名 filemode: 和file函数意义相同,指定日志文件的打开模式,‘w‘或‘a‘ format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示: %(levelno)s: 打印日志级别的数值 %(levelname)s: 打印日志级别名称 %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0] %(filename)s: 打印当前执行程序名 %(funcName)s: 打印日志的当前函数 %(lineno)d: 打印日志的当前行号 %(asctime)s: 打印日志的时间 %(thread)d: 打印线程ID %(threadName)s: 打印线程名称 %(process)d: 打印进程ID %(message)s: 打印日志信息 datefmt: 指定时间格式,同time.strftime() level: 设置日志级别,默认为logging.WARNING stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略 ======================================================================================== import sys #将输出重定向到文件 origin = sys.stdout f = open(‘file.txt‘,‘w‘) sys.stdout = f print ‘start............‘ print ‘end..............‘ sys.stdout = origin f.close() #将日志同时输出到文件和屏幕 import logging logging.basicConfig(level=logging.DEBUG,format=‘%(asctime)s %(filename)s [line:%(lineno)s] %(levelname)s %(message)s‘,filename=‘logging_test4.log‘,filemode=‘w‘) #定义一个StreamHandler将INFO或更高级别的日志信息打印到标准错误,并将其添加到当前日志处理对象 console=logging.StreamHandler() console.setLevel(logging.INFO) formatter=logging.Formatter(‘%(name)-12s: %(levelname)-8s %(message)s‘) console.setFormatter(formatter) logging.getLogger(‘‘).addHandler(console) logging.debug("This is debug msg") logging.info("This is info msg") logging.warning("This is warning msg") 参考文章: http://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html https://my.oschina.net/leejun2005/blog/126713
打印日志
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。