本文为博主原创,未经授权,严禁转载及使用。 本文链接:https://blog.csdn.net/zyooooxie/article/details/123635856
很早之前在跑脚本时,我都是用print() 来输出、展示数据,方便是方便,但 就是一次性(没法保存,用来追溯);后面 我了解到logging,最近做了些学习后,分享下。
【实际这篇博客推迟发布N个月】
个人博客:https://blog.csdn.net/zyooooxie
【以下所有内容仅为个人项目经历,如有不同,纯属正常】
logging
https://docs.python.org/zh-cn/3.8/library/logging.html https://docs.python.org/zh-cn/3.8/howto/logging.html https://docs.python.org/zh-cn/3.8/howto/logging-cookbook.html
https://docs.python.org/zh-cn/3.8/library/logging.html#logrecord-attributes
"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
"""
import logging.handlers
import logging
import logging.config
import time
abc = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
def test_10():
logging.debug('debug日志')
logging.info('info日志')
logging.warning('warning日志')
logging.error('error日志')
logging.critical('critical日志')
logging.critical('critical,%s,%s', '123456', 123456789)
def test_11():
pass
"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
"""
def test_0():
pass
def test_1():
pass
def test_2():
pass
def test_3():
pass
def test_dictConfig():
pass
def test_fileConfig():
pass
"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
"""
def test_0_a():
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('debug日志')
logging.info('info日志')
logging.warning('warning日志')
logging.error('error日志')
logging.critical('critical日志')
def test_0_b():
logging.basicConfig(format='%(asctime)s:%(message)s', level=logging.WARNING, datefmt='%m/%d/%Y %I:%M:%S %p')
logging.debug('debug日志')
logging.info('info日志')
logging.warning('warning日志')
logging.error('error日志')
logging.critical('critical日志')
def test_0_c():
logging.basicConfig(filename='example_1025001.log', level=logging.INFO, format='%(asctime)s:%(message)s')
logger = logging.getLogger(__name__)
logger.debug('debug日志')
logger.info('info日志')
logger.warning('warning日志')
logger.error('error日志')
logger.critical('critical日志')
logger.critical('{}'.format(abc))
def test_0_d():
logging.basicConfig(filename='example_1025003.log', level=logging.ERROR, filemode='w',
datefmt='%m/%d/%Y %I:%M:%S %p', format='%(asctime)s ** %(message)s')
logger = logging.getLogger(__name__)
logger.info('info日志')
logger.warning('warning日志')
logger.error('error日志')
logger.critical('critical日志')
logger.critical('{}'.format(abc))
def test_1_a():
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
try:
result = 10 / 0
except Exception:
logger.debug('Faild-debug', exc_info=True)
logger.info('Faild-info', exc_info=True)
logger.error('Faild-error', exc_info=True)
logger.warning('Faild-warning', exc_info=True)
logger.critical('Faild-critical', exc_info=True)
logger.info('-----')
logger.debug('Faild-debug', exc_info=True, stack_info=True)
logger.info('Faild-info', exc_info=True, stack_info=True)
logger.error('Faild-error', exc_info=True, stack_info=True)
logger.warning('Faild-warning', exc_info=True, stack_info=True)
logger.critical('Faild-critical', exc_info=True, stack_info=True)
logger.info('-----')
try:
result = 10 / 0
except Exception:
logger.exception('Faild-exception')
logger.error('Faild222')
logger.exception('Faild222')
logger.log(logging.DEBUG, "This is a debug log.")
logger.log(logging.INFO, "This is a info log.")
logger.log(logging.WARNING, "This is a warning log.")
logger.log(logging.ERROR, "This is a error log.")
logger.log(logging.CRITICAL, "This is a critical log.")
logger.info('-----')
logger.log(10, "a debug log.")
logger.log(20, "a info log.")
logger.log(30, "a warning log.")
logger.log(40, "a error log.")
logger.log(50, "a critical log.")
logger.log(45, "这是啥level")
logger.log(500, "这是啥level")
def test_2_a():
LOG_FILENAME = '2_a.log'
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.WARN)
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=10, backupCount=5)
my_logger.addHandler(handler)
my_logger.debug('debug日志')
my_logger.info('info日志')
my_logger.warning('warning日志')
my_logger.error('error日志')
my_logger.critical('critical日志')
my_logger.critical('{}'.format(abc))
my_logger.debug('debug日志111')
my_logger.info('info日志111')
my_logger.warning('warning日志111')
my_logger.error('error日志111')
my_logger.critical('critical日志111')
def test_2_b():
when_ = 'd'
interval_ = 1
backup_count = 100
file_name = 'zy'
handler = logging.handlers.TimedRotatingFileHandler(filename=file_name, when=when_, backupCount=backup_count,
interval=interval_, encoding='utf-8')
def test_3_a():
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
root.addHandler(handler)
bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}', style='{')
handler.setFormatter(bf)
root.debug('DEBUG日志')
root.info('info日志')
root.warning('warning日志')
root.error('error日志')
root.critical('critical日志')
root.log(30, '')
df = logging.Formatter('$asctime--${name}--${levelname}--$message', style='$')
handler.setFormatter(df)
root.debug('DEBUG日志')
root.info('info日志')
root.warning('warning日志')
root.error('error日志')
root.critical('critical日志')
root.critical('critical,%s', '--123--CRITICAL')
root.critical('critical,%s', 123)
root.critical('critical,%s', 123.589)
root.critical('critical,%s', [123.589, 78965.20])
创建Logger、Handler和Formatter,进行相关设置
"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
"""
import logging
import logging.config
import time
abc = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
def test_10_a1():
logger = logging.getLogger('a1')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.debug('debug message日志')
logger.info('info message日志')
logger.warning('warn message日志')
logger.error('error message日志')
logger.critical('critical message日志')
def test_10_a2():
logger = logging.getLogger('a2')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('10_a2.log')
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
formatter = logging.Formatter('%(name)s - %(asctime)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
logger.debug('debug message日志')
logger.info('info message日志')
logger.warning('warn message日志')
logger.error('error message日志')
logger.critical('critical message日志')
基于日志配置文件 进行配置,使用fileConfig()
[loggers]
keys=root,simpleExample
[logger_root]
level=DEBUG
handlers=consoleHandler,FileHandler,RH
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handlers]
keys=consoleHandler,FileHandler,RH
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=simpleFormatter
args=(sys.stdout,)
[handler_FileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('10_b.log', 'w')
[handler_RH]
class=handlers.RotatingFileHandler
level=ERROR
args=('10_b_RH.log', 'w', 5, 10)
[formatters]
keys=simpleFormatter
[formatter_simpleFormatter]
format= %(name)s - %(levelname)s - %(asctime)s - %(message)s
datefmt=%y-%m-%d %H:%M:%S
"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
"""
def test_10_b():
logging.config.fileConfig('logging2.conf')
logger = logging.getLogger()
logger.debug('debug message日志')
logger.info('info message日志')
logger.warning('warn message日志')
logger.error('error message日志')
logger.critical('critical message日志')
基于配置信息字典 进行配置,使用dictConfig()
"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
"""
def test_10_c():
log_dict = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'simple': {'format': '%(levelname)s | %(asctime)s | %(message)s', 'datefmt': '%y-%m-%d %H:%M:%S'},
'other': {'format': '%(asctime)s -- %(message)s'}},
'handlers': {
'console': {'level': 'ERROR', 'class': 'logging.StreamHandler', 'formatter': 'simple'},
'file': {'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '10_c.log',
'mode': 'w', 'encoding': 'utf-8', 'formatter': 'other'},
'r_file': {'class': 'logging.handlers.RotatingFileHandler',
'filename': '10_c_{}.log'.format(abc),
'maxBytes': 10, 'backupCount': 2}},
'loggers': {
'simpleExample': {'level': 'DEBUG', 'handlers': ['console', 'file', 'r_file']}
},
'root': {'level': 'INFO', 'handlers': ['console', 'r_file']}
}
logging.config.dictConfig(log_dict)
logger = logging.getLogger('simpleExample')
logger.debug('debug message日志')
logger.info('info message日志')
logger.warning('warn message日志')
logger.error('error message日志')
logger.critical('critical message日志')
本文链接:https://blog.csdn.net/zyooooxie/article/details/123635856
个人博客 https://blog.csdn.net/zyooooxie
|