def TestLogBasic():
import logging
logging.basicConfig(filename = 'log.txt', filemode = 'a', level = logging.NOTSET, format = '%(asctime)s - %(levelname)s: %(message)s')
logging.debug('this is a message')
logging.info("this is a info")
logging.disable(30)#logging.WARNING
logging.warning("this is a warnning")
logging.critical("this is a critical issue")
logging.error("this is a error")
logging.addLevelName(88,"MyCustomError")
logging.log(88,"this is an my custom error")
try:
raise Exception('this is a exception')
except:
logging.exception( 'exception')
logging.shutdown()
TestLogBasic() 说明:(此实例为最简单的用法,用来将log记录到log文件中)
1)logging.basicConfig()中定义默认的log到log.txt,log文件为append模式,处理所有的level大于logging.NOTSET的logging,log的格式定义为'%(asctime)s - %(levelname)s: %(message)s';
2)使用logging.debug()...等来log相应level的log;
3)使用logging.disable()来disable某个logging level;
4)使用logging.addLevelName增加自定义的logging level;
5)使用logging.log来log自定义的logging level的log;
输出的text的log如下:
2011-01-18 10:02:45,415 - DEBUG: this is a message
2011-01-18 10:02:45,463 - INFO: this is a info
2011-01-18 10:02:45,463 - CRITICAL: this is a critical issue
2011-01-18 10:02:45,463 - ERROR: this is a error
2011-01-18 10:02:45,463 - MyCustomError: this is an my custom error
2011-01-18 10:02:45,463 - ERROR: exception
Traceback (most recent call last):
File "testlog.py", line 15, in TestLogBasic
raise Exception('this is a exception')
Exception: this is a exception
# create file handler which logs even debug messages
fh = logging.FileHandler("simple.log")
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
fh.setFormatter(formatter)
LOG_FILENAME = 'logging_rotatingfile_example.out'
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20, backupCount=5)
my_logger.addHandler(handler)
# Log some messages
for i in range(20):
my_logger.debug('i = %d' % i)
# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)
for filename in logfiles:
print(filename)