Python logging日志模块+读取配置文件
1配置文件config.ini [log]level=INFOfilepath=./loglogname=run.log[master]ip=127.0.0.1port=80802.读取配置文件config_base.py#!/usr/bin/env python# -*- coding: utf-8 -*-import ConfigParserclass ...
1配置文件config.ini
[log]
level=INFO
filepath=./log
logname=run.log
[master]
ip=127.0.0.1
port=8080
2.读取配置文件config_base.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
class Config(object):
def __init__(self, filename):
self.filename = filename
self.config = ConfigParser.ConfigParser()
self.config.read(self.filename)
#日志配置
def read_log(self):
self.level = self.config.get("log", "level")
self.filepath = self.config.get("log", "filepath")
self.logname = self.config.get("log", "logname")
#ip端口配置
def read_master(self):
self.ip = self.config.get("master", "ip")
self.port = self.config.get("master", "port")
3.创建公共类PuplicUnt.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@note: 公共类
'''
class PublicManger(object):
logger=None
conf=None
4.初始化log文件设置
#!/usr/bin/env python
#-*- coding:UTF-8 -*-
import os, sys, logging
import logging.handlers
import time
from PublicUnt import PublicManger
#初始化日志配置文件
def init_log():
PublicManger.conf.read_log()
PublicManger.logger=logging.getLogger()
PublicManger.logger.setLevel(PublicManger.conf.level)
fh = logging.handlers.TimedRotatingFileHandler(os.path.join(PublicManger.conf.filepath, PublicManger.conf.logname), when = 'D', maxBytes=10*1024*1024, backupCount = 10)
sh = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s-%(module)s:%(filename)s-L%(levelname)s:%(message)s')
fh.setFormatter(formatter)
PublicManger.logger.addHandler(fh)
PublicManger.logger.addHandler(sh)
TimedRotatingFileHandler(filename [,when [,interval [,backupCount]]])
filename 是输出日志文件名的前缀
when 是一个字符串的定义如下:
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight
interval 是指等待多少个单位when的时间后,Logger会自动重建文件,当然,这个文件的创建
取决于filename+suffix,若这个文件跟之前的文件有重名,则会自动覆盖掉以前的文件,所以
有些情况suffix要定义的不能因为when而重复。
backupCount 是保留日志个数。默认的0是不会自动删除掉日志。若设10,则在文件的创建过程中
库会判断是否有超过这个10,若超过,则会从最先创建的开始删除。
# -*- coding:utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
class Logger:
@classmethod
def getlogger(cls,log,level):
logger = logging.getLogger()
rotfh = RotatingFileHandler(log,maxBytes=10*1024*1024,backupCount=5)
#sh = logging.StreamHandler()
fmatter = logging.Formatter("%(asctime)s - %(filename)s [line:%(lineno)d] %(name)-10s:%(levelname)-8s %(message)s")
rotfh.setFormatter(fmatter)
logger.addHandler(rotfh)
logger.setLevel(level)
Logger.logging = logger
RotatingFileHandler(os.path.join(filepath,logname),maxBytes=10*1024*1024,backupCount=5) 按日志文件大小保留
from log import Logger
Logger.getlogger('./log/test1', 'INFO')
Logger.logging.info('hello')
5.写入日志
from config_base import Config
from initconf import init_log
from PublicUnt import PublicManger
CONFIG_FILE = "./config.ini"
def main():
PublicManger.conf = Config(CONFIG_FILE)
init_log()
if __name__ == '__main__':
main()
PublicManger.logger.info('save logging')
aa.写入配置文件
import ConfigParser
class Configer:
@classmethod
def load(cls,path):
conf = ConfigParser.SafeConfigParser(allow_no_value=True)
conf.read(path)
items = conf.sections()
opts = {}
for item in items:
opt = dict(conf.items(item))
opts = dict(opts,**opt) #合并字典
Configer.confs = opts
@classmethod
def update(cls,path,sec):
conf = ConfigParser.ConfigParser(allow_no_value=True)
conf.read(path)
#for k,v in sec[1].iteritems():
# print k,v
for key in sec[1]:
conf.set(sec[0],key,sec[1][key])
with open(path,'w') as cfile:
conf.write(cfile)
cls.load(path)
import Configer
import Logger
ip = ip = Configer.confs["ip"]
log = Logger.logging
log.info("ip is %s" %ip)
# -* - coding: UTF-8 -* -
import ConfigParser
conf = ConfigParser.ConfigParser()
conf.read("c:\\test.conf")
# 获取指定的section, 指定的option的值
name = conf.get("section1", "name")
print(name)
age = conf.get("section1", "age")
print age
#获取所有的section (log, master)
sections = conf.sections()
print sections
#写配置文件
# 更新指定section, option的值
conf.set("section2", "port", "8081")
# 写入指定section, 增加新option的值
conf.set("section2", "IEPort", "80")
# 添加新的 section
conf.add_section("new_section")
conf.set("new_section", "new_option", "http://www.cnblogs.com/tankxiao")
# 写回配置文件
conf.write(open("c:\\test.conf","w"))
更多推荐
所有评论(0)