=============================================== #最普通的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
打印日誌
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.