自定義python日志文件系統(tǒng)實例
更新時間:2023年08月16日 08:40:18 作者:littleRpl
這篇文章主要介紹了自定義python日志文件系統(tǒng)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
自定義python日志文件系統(tǒng)
python的日志系統(tǒng)非常實用,可以自定義使用。
以下程序是基于logging模塊編輯的一個自定義的logging系統(tǒng),包括自定義日志輸出級別、輸出格式、輸出方式, 自定義日志文件切分方式, 自定義日志分類等功能。
# coding=utf-8
"""
Author: rpl
date: 19-12-9 下午2:46
desc:
"""
import os
import socket
import datetime
import logging
from logging import handlers
# 日志文件的保存位置
Log_path = os.path.dirname(__file__)
# 用字典保存日志級別
format_dict = {
1: logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
2: logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - filename:%(filename)s - line:%(lineno)d '
'- message:%(message)s'),
3: None, # 不做任何格式
}
def get_host_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
return ip
class Logger(object):
def __init__(self, log_filename=None, log_objname='Log', classify=None,
format_type=1, detial_time=True, stdout=True,
time_split=False, when='D', interval=1,
chunk_split=False, maxchunk=1024*1024*10,
backupCount=10,
ip=True):
"""
:param log_filename: 日志文件名, 是否輸出到文件, 默認(rèn)否
:param log_objname: 日志類名
:param classify: 日志分類,用于分類輸入到不同的文件夾, 默認(rèn)無
:param format_type: 日志的輸出格式,可自定義
:param detial_time: 日志文件是否輸出詳細(xì)時間(時分秒), 默認(rèn)輸出
:param stdout: 是否打印到屏幕, 默認(rèn)打印到屏幕
:param time_split: 是否按時間切分日志文件
:param when: D按天切分
:param interval: 間隔
:param chunl_split: 是否按文件大小切分文件
:param maxchunk 10 切分標(biāo)準(zhǔn) 1024*1024*10是超過10M切分
:param backupCount 最大備份數(shù) 10 最多保留10個切分文件,之后會丟棄最舊的。
:param ip ip=True 獲取本機ip作為不同機器日志文件的識別標(biāo)志
"""
self.logger = logging.getLogger(log_objname)
self.logger.setLevel(logging.DEBUG)
if ip:
self.ip = get_host_ip().split('.')[-1]
formatter = format_dict[format_type]
if detial_time: # 日志文件名 詳細(xì)時間, 帶時分秒
log_date = datetime.datetime.now().strftime('.%Y-%m-%d-%H%M%S')
else:
log_date = datetime.datetime.now().strftime('.%Y-%m-%d')
# 是否有文件名, 有則輸出到此文件
if log_filename:
if classify and ip:
log_path = os.path.join(Log_path, self.ip+'_log_file', classify)
elif classify and not ip:
log_path = os.path.join(Log_path, 'log_file', classify)
elif not classify and ip:
log_path = os.path.join(Log_path, self.ip + '_log_file')
else:
log_path = os.path.join(Log_path, 'log_file')
if not os.path.exists(log_path):
os.makedirs(log_path)
self.log_filename = os.path.join(log_path, log_filename+log_date)
if time_split:
fh = logging.handlers.TimedRotatingFileHandler(log_filename, when=when, interval=interval, backupCount=backupCount)
elif chunk_split:
# 按大小切分日志文件, 超過30M分割, 最多備份10個
fh = logging.handlers.RotatingFileHandler(log_filename, maxBytes=maxchunk, backupCount=backupCount)
else:
fh = logging.FileHandler(self.log_filename)
fh.setLevel(logging.DEBUG)
if formatter:
fh.setFormatter(formatter)
self.logger.addHandler(fh)
if stdout: # 是否輸出到屏幕
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
self.logger.addHandler(ch)
def getLog(self):
return self.logger
if __name__ == '__main__':
log = Logger(log_filename='test_log', classify='test', log_objname='test1',
detial_time=True, stdout=True, format_type=1, ip=False).getLog()
log.info('this is log test')python文件與文件系統(tǒng)
open()
open(file, mode=‘r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
·file: 必需,文件路徑(相對或者絕對路徑)。·mode: 可選,文件打開模式·buffering: 設(shè)置緩沖·encoding: 一般使用utf8·errors: 報錯級別·newline: 區(qū)分換行符·closefd: 傳入的file參數(shù)類型
文件打開模式(mode)

文件對象方法

f=open('.\\python.txt',mode='r')
print(f)
for i in f:
print(i)
c=open('C:\\Users\\帥哥的電腦\\Desktop\python練習(xí)\\韓繪錦.txt',mode='w')
c.write("hanhuijin")
c.close()
c=open('.\\韓繪錦.txt',mode='r+')
print(c.read())
c.seek(3,0)
print(c.read())
c.write('love lsgo')
c.seek(0,0)
print(c.read())
c.writelines (["韓繪錦",'love','lsgo'])
c.seek(0,0)
print(c.read())
print(c.tell ())
c.seek(0,0)
c.truncate ()
print(c.read())
#
<_io.TextIOWrapper name='.\\python.txt' mode='r' encoding='cp936'>
line1
line2
line3
hanhuijin
huijin
hanhuijinlove lsgo
hanhuijinlove lsgo韓繪錦lovelsgo
34
>>> os模塊中常用函數(shù)的使用方法

os.path模塊中常用函數(shù)使用方法

import os
path=os.getcwd ()
print(os.getcwd ())
print(os.listdir('.'))
os.chdir('C:\\Users\\帥哥的電腦\\Desktop\\python練習(xí)\\text ')
print(os.getcwd ())
print(os.listdir('.'))
os.makedirs(r'.\test\1\2\3')
#
C:\Users\帥哥的電腦\Desktop\python練習(xí)
['continue 練習(xí).py', 'os.path模塊中常用的函數(shù).png', 'os模塊中常用函數(shù).png', 'pyhon練習(xí)txt', 'python.txt', 'python文件與文件系統(tǒng)mode打開模式.png', 'python文件與文件系統(tǒng)文件對象方法.png', 'test.txt', 'text', 'text.txt', '基礎(chǔ)練習(xí).py', '字符串格式化符號.png', '市場營銷.docx', '格式化操作符輔助指令.png', '猜數(shù).py', '聯(lián)系.py', '運算符.png', '韓繪錦.txt']
C:\Users\帥哥的電腦\Desktop\python練習(xí)\text
['test']import os
path=os.getcwd ()
print(os.getcwd ())
print(os.listdir('.'))
os.chdir('C:\\Users\\帥哥的電腦\\Desktop\\python練習(xí)\\text ')
print(os.getcwd ())
print(os.listdir('.'))
print(os.walk('C:'))
#
C:\Users\帥哥的電腦\Desktop\python練習(xí)
['continue 練習(xí).py', 'os.path模塊中常用的函數(shù).png', 'os模塊中常用函數(shù).png', 'pyhon練習(xí)txt', 'python.txt', 'python文件與文件系統(tǒng)mode打開模式.png', 'python文件與文件系統(tǒng)文件對象方法.png', 'text', '基礎(chǔ)練習(xí).py', '字符串格式化符號.png', '格式化操作符輔助指令.png', '猜數(shù).py', '聯(lián)系.py', '運算符.png', '韓繪錦.txt']
C:\Users\帥哥的電腦\Desktop\python練習(xí)\text
['test', '刪除.txt']
<generator object walk at 0x000001E0AA483F48>序列化和反序列化的定義
- 序列化:就是把不可傳輸?shù)膶ο筠D(zhuǎn)換為可存儲或可傳輸?shù)倪^程
- 反序列化:就是把在磁盤,等介質(zhì)中的數(shù)據(jù)轉(zhuǎn)換為對象
pickle模塊的使用
import pickle
dic1={'one':1,'two':2,'three':3}
a=pickle.dumps (dic1)
print(a,type(a))
b=pickle.loads(a)
print(b,type(b))
#
b'\x80\x03}q\x00(X\x03\x00\x00\x00oneq\x01K\x01X\x03\x00\x00\x00twoq\x02K\x02X\x05\x00\x00\x00threeq\x03K\x03u.' <class 'bytes'>
{'one': 1, 'two': 2, 'three': 3} <class 'dict'>import pickle
dic1={'one':1,'two':2,'three':3}
a=open('.\\text.txt','wb')
pickle.dump(dic1,a)
a.close()
b=open('.\\text.txt','rb')
result=pickle.load(b)
print(b.read())
b.close()
print(id(dic1),result,id(result))
#
b''
1806383632776 {'one': 1, 'two': 2, 'three': 3} 1806383812024
結(jié)果說明反序列化后的對象不是原來的對象了總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
macOS M1(AppleSilicon) 安裝TensorFlow環(huán)境
蘋果為M1芯片的Mac提供了TensorFlow的支持,本文主要介紹了如何給使用M1芯片的macOS安裝TensorFlow的環(huán)境,感興趣的可以了解一下2021-08-08
Python基于win32ui模塊創(chuàng)建彈出式菜單示例
這篇文章主要介紹了Python基于win32ui模塊創(chuàng)建彈出式菜單,結(jié)合實例形式分析了Python使用win32ui模塊創(chuàng)建彈出式菜單的具體步驟與相關(guān)操作技巧,并附帶說明了win32ui模塊的安裝命令,需要的朋友可以參考下2018-05-05
Python如何獲取當(dāng)前路徑并列出當(dāng)前路徑下的所有文件
這篇文章主要介紹了Python如何獲取當(dāng)前路徑并列出當(dāng)前路徑下的所有文件問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06

