自定義log?
#coding=utf-8
import datetime
class Logs:
debug = 1
def logwr(self,logdd):
tms = datetime.datetime.now().strftime("%Y-%m-%d")
name='wenshu_{0}.log'.format(tms)
tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
line = "{0} : {1}".format(tm, logdd)
print(line)
with open(name,'a') as loged:
loged.write(line+"\n")
loged.close()
def log_debug(self,logdd):
logdd='debug:{0}'.format(logdd)
if self.debug==1:
self.logwr(logdd)
if __name__ == '__main__':
logs=Logs()
logs.logwr('test')
logs.log_debug('debuglog')
?
#!/usr/bin/env python
#_*_coding:utf-8_*_
import logging
logging.basicConfig( #通過具體的參數來更改logging模塊默認行為;
level=logging.ERROR, #設置告警級別為ERROR;
format="%(asctime)s---%(lineno)s----%(name)s: %(message)s", #自定義打印的格式;
filename="yinzhengjie.txt", #將日志輸出到指定的文件中;
filemode="a", #以追加的方式將日志寫入文件中,w是以覆蓋寫的方式喲;
)
"""
format參數中可能用到的格式化串:
1>.%(name)s
Logger的名字
2>.%(levelno)s
數字形式的日志級別
3>.%(levelname)s
文本形式的日志級別
4>.%(pathname)s
調用日志輸出函數的模塊的完整路徑名,可能沒有
5>.%(filename)s
調用日志輸出函數的模塊的文件名
6>.%(module)s
調用日志輸出函數的模塊名
7>.%(funcName)s
調用日志輸出函數的函數名
8>.%(lineno)d
調用日志輸出函數的語句所在的代碼行
9>.%(created)f
當前時間,用UNIX標準的表示時間的浮 點數表示
10>.%(relativeCreated)d
輸出日志信息時的,自Logger創建以 來的毫秒數
11>.%(asctime)s
字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號后面的是毫秒
12>.%(thread)d
線程ID。可能沒有
13>.%(threadName)s
線程名。可能沒有
14>.%(process)d
進程ID。可能沒有
15>.%(message)s
用戶輸出的消息
"""
logging.debug("debug message") #告警級別最低,只有在診斷問題時才有興趣的詳細信息。
logging.info("info message") #告警級別比debug要高,確認事情按預期進行。
logging.warning("warning message") #告警級別比info要高,該模式是默認的告警級別!預示著一些意想不到的事情發生,或在不久的將來出現一些問題(例如“磁盤空間低”)。該軟件仍在正常工作。
logging.error("error message") #告警級別要比warning藥膏,由于一個更嚴重的問題,該軟件還不能執行某些功能。
logging.critical("critical message") #告警級別要比error還要高,嚴重錯誤,表明程序本身可能無法繼續運行。
#!/usr/bin/env python
#_*_coding:utf-8_*_
import logging
from logging import handlers
logger = logging.getLogger(__name__)
log_file = "timelog.log"
#fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3)
fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3) #filename定義將信息輸入到指定的文件,
# when指定單位是s(秒),interval是時間間隔的頻率,單位是when所指定的喲(所以,你可以理解頻率是5s);backupCount表示備份的文件個數,我這里是指定的3個文件。
formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s') #定義輸出格式
fh.setFormatter(formatter) #添加格式化輸出
logger.addHandler(fh)
logger.warning("test1")
logger.warning("test2")
logger.warning("test3")
logger.warning("test4")
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
