#coding:utf-8 import logging from logging import handlers import time #简单的不同级别日志输出 # logging.debug('this is debug msg') # logging.info('this is info msg') # logging.warning('this is warning msg') # logging.error('this is error msg') #formatter 参数含义 # format参数中可能用到的格式化串: # %(name)s Logger的名字 # %(levelno)s 数字形式的日志级别 # %(levelname)s 文本形式的日志级别 # %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有 # %(filename)s 调用日志输出函数的模块的文件名 # %(module)s 调用日志输出函数的模块名 # %(funcName)s 调用日志输出函数的函数名 # %(lineno)d 调用日志输出函数的语句所在的代码行 # %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示 # %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数 # %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 # %(thread)d 线程ID。可能没有 # %(threadName)s 线程名。可能没有 # %(process)d 进程ID。可能没有 # %(message)s用户输出的消息 # ----------------快速部署------------------ # logging.basicConfig(filename='./loger.log', filemode='a+', # datefmt='%Y-%m-%d, %H-%M-%S', # format='%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s', # level=logging.WARNING) # for x in range(1, 20): # logging.warning('test warning msg log') #-----------------自定义个handle------------- # myloger = logging.getLogger('myloger') # fname = time.strftime('%Y-%m-%d', time.localtime()) + '.log' # handler = logging.FileHandler(fname, mode='a+') # handler.setLevel(logging.WARNING) # #传入一个formatter类 # formatter = logging.Formatter(datefmt='%Y-%m-%d, %H-%M-%S', # fmt='%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s') # handler.setFormatter(formatter) # # myloger.addHandler(handler) # for t in range(1, 20): # myloger.warning('test by usersetting....') #-------------------日志的回滚应用更复杂的场景------------ handler = logging.handlers.TimedRotatingFileHandler(filename='log', when='S', interval=2) handler.setLevel(logging.WARNING) handler.setFormatter(logging.Formatter(fmt='%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s', datefmt='%Y-%m-%d, %H-%M-%S')) handler.suffix = "%Y%m%d_%H%M%S.log" loger = logging.getLogger('mylog') loger.addHandler(handler) for t in range(1, 10): loger.warning('loger test....') time.sleep(1)