特点:
1) 此GlobalLogging 采用了singlten模式,全局唯一,必须通过getInstance方法来获得GlobalLogging的实例;
2) 此GlobalLogging可以采用logging提供的log handlers(例如log到console,file。。。),同时支持提供自定义函数来处理log的接口,可以自己定义如何处理log;
GlobalLogging的使用如下: (将系统的所有的函数的log,同时写到log文件和UI中的text控件中)
from
GlobalLogging
import
GlobalLogging
class
A:
def
__init__
(self):
GlobalLogging.getInstance().setLoggingToHanlder(self.getLog)
GlobalLogging.getInstance().setLoggingToFile(
'
logfile.txt
'
)
GlobalLogging.getInstance().setLoggingLevel(logging.INFO)
def
getLog(self, s):
self.outputText.append(s)
def
FA(self):
GlobalLogging.getInstance().info(
'
XXX
'
)
GlobalLogging.getInstance().error(
'
XXX
'
)
GlobalLogging代码:
import
logging
class
NullHandler(logging.Handler):
def
emit(self, record):
pass
class
GlobalLogging:
log
=
None
@staticmethod
def
getInstance():
if
GlobalLogging.log
==
None:
GlobalLogging.log
=
GlobalLogging()
return
GlobalLogging.log
def
__init__
(self):
self.logger
=
None
self.handler
=
None
self.level
=
logging.INFO
self.logger
=
logging.getLogger(
"
GlobalLogging
"
)
self.formatter
=
logging.Formatter(
"
%(levelname)s - %(message)s
"
)
h
=
NullHandler()
self.logger.addHandler(h)
def
setLoggingToFile(self,file):
fh
=
logging.FileHandler(file)
fh.setFormatter(self.formatter)
self.logger.addHandler(ch)
def
setLoggingToConsole(self) :
ch
=
logging.StreamHandler()
ch.setFormatter(self.formatter)
self.logger.addHandler(fh)
def
setLoggingToHanlder(self,handler):
self.handler
=
handler
def
setLoggingLevel(self,level):
self.level
=
level
self.logger.setLevel(level)
def
debug(self,s):
self.logger.debug(s)
if
not
self.handler
==
None
and
self.level
<=
logging.DEBUG :
print
logging.DEBUG
print
self.level
self.handler(
'
debug:
'
+
s)
def
info(self,s):
self.logger.info(s)
if
not
self.handler
==
None
and
self.level
<=
logging.INFO:
self.handler(
'
info:
'
+
s)
def
warn(self,s):
self.logger.warn(s)
if
not
self.handler
==
None
and
self.level
<=
logging.WARNING:
self.handler(
'
warn:
'
+
s)
def
error(self,s):
self.logger.error(s)
if
not
self.handler
==
None
and
self.level
<=
logging.ERROR:
self.handler(
'
error:
'
+
s)
def
critical(self,s):
self.logger.critical(s)
if
not
self.handler
==
None
and
self.level
<=
logging.CRITICAL:
self.handler(
'
critical:
'
+
s)
完!